source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 27475200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x5c634E787ec76b9084BEb6188f9d76250Ff4d2Eb;
}
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 = 30326400
;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x5d1045F1F7b42261D7e0826B47Eab4EE0F0FE717 ;
}
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.0;
contract AbstractENS {
function owner(bytes32 node) constant returns(address);
function resolver(bytes32 node) constant returns(address);
function ttl(bytes32 node) constant returns(uint64);
function setOwner(bytes32 node, address owner);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner);
function setResolver(bytes32 node, address resolver);
function setTTL(bytes32 node, uint64 ttl);
event Transfer(bytes32 indexed node, address owner);
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
}
contract Deed {
address public registrar;
address constant burn = 0xdead;
uint public creationDate;
address public owner;
address public previousOwner;
uint public value;
event OwnerChanged(address newOwner);
event DeedClosed();
bool active;
modifier onlyRegistrar {
if (msg.sender != registrar) throw;
_;
}
modifier onlyActive {
if (!active) throw;
_;
}
function Deed(uint _value) {
registrar = msg.sender;
creationDate = now;
active = true;
value = _value;
}
function setOwner(address newOwner) onlyRegistrar {
previousOwner = owner;
owner = newOwner;
OwnerChanged(newOwner);
}
function setRegistrar(address newRegistrar) onlyRegistrar {
registrar = newRegistrar;
}
function setBalance(uint newValue) onlyRegistrar onlyActive payable {
if (value < newValue) throw;
value = newValue;
if (!owner.send(this.balance - newValue)) throw;
}
function closeDeed(uint refundRatio) onlyRegistrar onlyActive {
active = false;
if (! burn.send(((1000 - refundRatio) * this.balance)/1000)) throw;
DeedClosed();
destroyDeed();
}
function destroyDeed() {
if (active) throw;
if(owner.send(this.balance))
selfdestruct(burn);
}
function () payable {}
}
contract Registrar {
AbstractENS public ens;
bytes32 public rootNode;
mapping (bytes32 => entry) _entries;
mapping (address => mapping(bytes32 => Deed)) public sealedBids;
enum Mode { Open, Auction, Owned, Forbidden, Reveal }
uint32 constant auctionLength = 5 days;
uint32 constant revealPeriod = 48 hours;
uint32 constant initialAuctionPeriod = 4 weeks;
uint constant minPrice = 0.01 ether;
uint public registryStarted;
event AuctionStarted(bytes32 indexed hash, uint registrationDate);
event NewBid(bytes32 indexed hash, address indexed bidder, uint deposit);
event BidRevealed(bytes32 indexed hash, address indexed owner, uint value, uint8 status);
event HashRegistered(bytes32 indexed hash, address indexed owner, uint value, uint registrationDate);
event HashReleased(bytes32 indexed hash, uint value);
event HashInvalidated(bytes32 indexed hash, string indexed name, uint value, uint registrationDate);
struct entry {
Deed deed;
uint registrationDate;
uint value;
uint highestBid;
}
function state(bytes32 _hash) constant returns (Mode) {
var entry = _entries[_hash];
if(now < entry.registrationDate) {
if(now < entry.registrationDate - revealPeriod) {
return Mode.Auction;
} else {
return Mode.Reveal;
}
} else {
if(entry.highestBid == 0) {
return Mode.Open;
} else if(entry.deed == Deed(0)) {
return Mode.Forbidden;
} else {
return Mode.Owned;
}
}
}
modifier inState(bytes32 _hash, Mode _state) {
if(state(_hash) != _state) throw;
_;
}
modifier onlyOwner(bytes32 _hash) {
if (state(_hash) != Mode.Owned || msg.sender != _entries[_hash].deed.owner()) throw;
_;
}
modifier registryOpen() {
if(now < registryStarted || now > registryStarted + 4 years || ens.owner(rootNode) != address(this)) throw;
_;
}
function entries(bytes32 _hash) constant returns (Mode, address, uint, uint, uint) {
entry h = _entries[_hash];
return (state(_hash), h.deed, h.registrationDate, h.value, h.highestBid);
}
function Registrar(address _ens, bytes32 _rootNode, uint _startDate) {
ens = AbstractENS(_ens);
rootNode = _rootNode;
registryStarted = _startDate > 0 ? _startDate : now;
}
function max(uint a, uint b) internal constant returns (uint max) {
if (a > b)
return a;
else
return b;
}
function min(uint a, uint b) internal constant returns (uint min) {
if (a < b)
return a;
else
return b;
}
function strlen(string s) internal constant returns (uint) {
uint ptr;
uint end;
assembly {
ptr := add(s, 1)
end := add(mload(s), ptr)
}
for (uint len = 0; ptr < end; len++) {
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;
}
}
return len;
}
function startAuction(bytes32 _hash) inState(_hash, Mode.Open) registryOpen() {
entry newAuction = _entries[_hash];
newAuction.registrationDate = max(now + auctionLength, registryStarted + initialAuctionPeriod);
newAuction.value = 0;
newAuction.highestBid = 0;
AuctionStarted(_hash, newAuction.registrationDate);
}
function startAuctions(bytes32[] _hashes) {
for (uint i = 0; i < _hashes.length; i ++ ) {
startAuction(_hashes[i]);
}
}
function shaBid(bytes32 hash, address owner, uint value, bytes32 salt) constant returns (bytes32 sealedBid) {
return sha3(hash, owner, value, salt);
}
function newBid(bytes32 sealedBid) payable {
if (address(sealedBids[msg.sender][sealedBid]) > 0 ) throw;
if (msg.value < minPrice) throw;
Deed newBid = new Deed(msg.value);
sealedBids[msg.sender][sealedBid] = newBid;
NewBid(sealedBid, msg.sender, msg.value);
if (!newBid.send(msg.value)) throw;
}
function unsealBid(bytes32 _hash, address _owner, uint _value, bytes32 _salt) {
bytes32 seal = shaBid(_hash, _owner, _value, _salt);
Deed bid = sealedBids[msg.sender][seal];
if (address(bid) == 0 ) throw;
sealedBids[msg.sender][seal] = Deed(0);
bid.setOwner(_owner);
entry h = _entries[_hash];
uint actualValue = min(_value, bid.value());
bid.setBalance(actualValue);
var auctionState = state(_hash);
if(auctionState == Mode.Owned) {
bid.closeDeed(5);
BidRevealed(_hash, _owner, actualValue, 1);
} else if(auctionState != Mode.Reveal) {
throw;
} else if (_value < minPrice || bid.creationDate() > h.registrationDate - revealPeriod) {
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 0);
} else if (_value > h.highestBid) {
if(address(h.deed) != 0) {
Deed previousWinner = h.deed;
previousWinner.closeDeed(995);
}
h.value = h.highestBid;
h.highestBid = actualValue;
h.deed = bid;
BidRevealed(_hash, _owner, actualValue, 2);
} else if (_value > h.value) {
h.value = actualValue;
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 3);
} else {
bid.closeDeed(995);
BidRevealed(_hash, _owner, actualValue, 4);
}
}
function cancelBid(address bidder, bytes32 seal) {
Deed bid = sealedBids[bidder][seal];
if (address(bid) == 0
|| now < bid.creationDate() + initialAuctionPeriod
|| bid.owner() > 0) throw;
bid.setOwner(msg.sender);
bid.closeDeed(5);
sealedBids[bidder][seal] = Deed(0);
BidRevealed(seal, bidder, 0, 5);
}
function finalizeAuction(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
h.value = max(h.value, minPrice);
ens.setSubnodeOwner(rootNode, _hash, h.deed.owner());
Deed deedContract = h.deed;
deedContract.setBalance(h.value);
HashRegistered(_hash, deedContract.owner(), h.value, h.registrationDate);
}
function transfer(bytes32 _hash, address newOwner) onlyOwner(_hash) {
entry h = _entries[_hash];
h.deed.setOwner(newOwner);
ens.setSubnodeOwner(rootNode, _hash, newOwner);
}
function releaseDeed(bytes32 _hash) onlyOwner(_hash) {
entry h = _entries[_hash];
Deed deedContract = h.deed;
if (now < h.registrationDate + 1 years
|| now > registryStarted + 8 years) throw;
HashReleased(_hash, h.value);
h.value = 0;
h.highestBid = 0;
h.deed = Deed(0);
ens.setSubnodeOwner(rootNode, _hash, 0);
deedContract.closeDeed(1000);
}
function invalidateName(string unhashedName) inState(sha3(unhashedName), Mode.Owned) {
if (strlen(unhashedName) > 6 ) throw;
bytes32 hash = sha3(unhashedName);
entry h = _entries[hash];
ens.setSubnodeOwner(rootNode, hash, 0);
if(address(h.deed) != 0) {
h.deed.setBalance(h.deed.value()/2);
h.deed.setOwner(msg.sender);
h.deed.closeDeed(1000);
}
HashInvalidated(hash, unhashedName, h.value, h.registrationDate);
h.deed = Deed(0);
}
function transferRegistrars(bytes32 _hash) onlyOwner(_hash) {
var registrar = ens.owner(rootNode);
if(registrar == address(this))
throw;
entry h = _entries[_hash];
h.deed.setRegistrar(registrar);
}
function returnDeed(Deed deed) {
if(deed.registrar() != address(this) || deed.creationDate() > registryStarted)
throw;
deed.closeDeed(1000);
}
} | 0 |
pragma solidity ^0.4.19;
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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) 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) {
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 Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = true;
modifier whenNotPaused() {
require(!paused || msg.sender == owner);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
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 LMDA is PausableToken {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
function LMDA() public {
name = "LaMonedaCoin";
symbol = "LMDA";
decimals = 18;
totalSupply = 500000000e18;
balances[owner] = totalSupply;
Transfer(address(this), owner, totalSupply);
}
}
contract ICO is Ownable {
using SafeMath for uint256;
event AidropInvoked();
event MainSaleActivated();
event TokenPurchased(address recipient, uint256 tokens);
event DeadlineExtended(uint256 daysExtended);
event DeadlineShortened(uint256 daysShortenedBy);
event OffChainPurchaseMade(address recipient, uint256 tokensBought);
event TokenPriceChanged(string stage, uint256 newTokenPrice);
event ExchangeRateChanged(string stage, uint256 newRate);
event BonusChanged(string stage, uint256 newBonus);
event TokensWithdrawn(address to, uint256 LMDA);
event TokensUnpaused();
event ICOPaused(uint256 timeStamp);
event ICOUnpaused(uint256 timeStamp);
address public receiverOne;
address public receiverTwo;
address public receiverThree;
address public reserveAddress;
address public teamAddress;
uint256 public endTime;
uint256 public tokenPriceForPreICO;
uint256 public rateForPreICO;
uint256 public tokenPriceForMainICO;
uint256 public rateForMainICO;
uint256 public tokenCapForPreICO;
uint256 public tokenCapForMainICO;
uint256 public bonusForPreICO;
uint256 public bonusForMainICO;
uint256 public tokensSold;
uint256 public timePaused;
bool public icoPaused;
enum StateOfICO {
PRE,
MAIN
}
StateOfICO public stateOfICO;
LMDA public lmda;
mapping (address => uint256) public investmentOf;
modifier whenNotPaused {
require(!icoPaused);
_;
}
function ICO() public {
lmda = new LMDA();
owner = 0x2488F34A2c2eBabbb44d5E8AD81E1D689fD76E50;
receiverOne = 0x43adebFC525FEcf9b2E91a4931E4a003a1F0d959;
receiverTwo = 0xB447292181296B8c7F421F1182be20640dc8Bb05;
receiverThree = 0x3f68b06E7C0E87828647Dbba0b5beAef3822b7Db;
reserveAddress = 0x7d05F660124B641b74b146E9aDA60D7D836dcCf5;
teamAddress = 0xAD942E5085Af6a7A4C31f17ac687F8d5d7C0225C;
lmda.transfer(reserveAddress, 90000000e18);
lmda.transfer(teamAddress, 35500000e18);
stateOfICO = StateOfICO.PRE;
endTime = now.add(21 days);
tokenPriceForPreICO = 0.00005 ether;
rateForPreICO = 20000;
tokenPriceForMainICO = 0.00007 ether;
rateForMainICO = 14285;
tokenCapForPreICO = 144000000e18;
tokenCapForMainICO = 374500000e18;
bonusForPreICO = 20;
bonusForMainICO = 15;
tokensSold = 0;
icoPaused= false;
}
function airdrop(address[] _addrs, uint256[] _values) public onlyOwner {
require(lmda.balanceOf(address(this)) >= getSumOfValues(_values));
require(_addrs.length <= 100 && _addrs.length == _values.length);
for(uint i = 0; i < _addrs.length; i++) {
lmda.transfer(_addrs[i], _values[i]);
}
AidropInvoked();
}
function getSumOfValues(uint256[] _values) internal pure returns(uint256 sum) {
sum = 0;
for(uint i = 0; i < _values.length; i++) {
sum = sum.add(_values[i]);
}
}
function activateMainSale() public onlyOwner whenNotPaused {
require(now >= endTime || tokensSold >= tokenCapForPreICO);
stateOfICO = StateOfICO.MAIN;
endTime = now.add(49 days);
MainSaleActivated();
}
function() public payable {
buyTokens(msg.sender);
}
function buyTokens(address _addr) public payable whenNotPaused {
require(now <= endTime && _addr != 0x0);
require(lmda.balanceOf(address(this)) > 0);
if(stateOfICO == StateOfICO.PRE && tokensSold >= tokenCapForPreICO) {
revert();
} else if(stateOfICO == StateOfICO.MAIN && tokensSold >= tokenCapForMainICO) {
revert();
}
uint256 toTransfer = msg.value.mul(getRate().mul(getBonus())).div(100).add(getRate());
lmda.transfer(_addr, toTransfer);
tokensSold = tokensSold.add(toTransfer);
investmentOf[msg.sender] = investmentOf[msg.sender].add(msg.value);
TokenPurchased(_addr, toTransfer);
forwardFunds();
}
function processOffChainPurchase(address _recipient, uint256 _value) public onlyOwner {
require(lmda.balanceOf(address(this)) >= _value);
require(_value > 0 && _recipient != 0x0);
lmda.transfer(_recipient, _value);
tokensSold = tokensSold.add(_value);
OffChainPurchaseMade(_recipient, _value);
}
function forwardFunds() internal {
if(stateOfICO == StateOfICO.PRE) {
receiverOne.transfer(msg.value.div(2));
receiverTwo.transfer(msg.value.div(2));
} else {
receiverThree.transfer(msg.value);
}
}
function extendDeadline(uint256 _daysToExtend) public onlyOwner {
endTime = endTime.add(_daysToExtend.mul(1 days));
DeadlineExtended(_daysToExtend);
}
function shortenDeadline(uint256 _daysToShortenBy) public onlyOwner {
if(now.sub(_daysToShortenBy.mul(1 days)) < endTime) {
endTime = now;
}
endTime = endTime.sub(_daysToShortenBy.mul(1 days));
DeadlineShortened(_daysToShortenBy);
}
function changeTokenPrice(uint256 _newTokenPrice) public onlyOwner {
require(_newTokenPrice > 0);
if(stateOfICO == StateOfICO.PRE) {
if(tokenPriceForPreICO == _newTokenPrice) { revert(); }
tokenPriceForPreICO = _newTokenPrice;
rateForPreICO = uint256(1e18).div(tokenPriceForPreICO);
TokenPriceChanged("Pre ICO", _newTokenPrice);
} else {
if(tokenPriceForMainICO == _newTokenPrice) { revert(); }
tokenPriceForMainICO = _newTokenPrice;
rateForMainICO = uint256(1e18).div(tokenPriceForMainICO);
TokenPriceChanged("Main ICO", _newTokenPrice);
}
}
function changeRateOfToken(uint256 _newRate) public onlyOwner {
require(_newRate > 0);
if(stateOfICO == StateOfICO.PRE) {
if(rateForPreICO == _newRate) { revert(); }
rateForPreICO = _newRate;
tokenPriceForPreICO = uint256(1e18).div(rateForPreICO);
ExchangeRateChanged("Pre ICO", _newRate);
} else {
if(rateForMainICO == _newRate) { revert(); }
rateForMainICO = _newRate;
rateForMainICO = uint256(1e18).div(rateForMainICO);
ExchangeRateChanged("Main ICO", _newRate);
}
}
function changeBonus(uint256 _newBonus) public onlyOwner {
if(stateOfICO == StateOfICO.PRE) {
if(bonusForPreICO == _newBonus) { revert(); }
bonusForPreICO = _newBonus;
BonusChanged("Pre ICO", _newBonus);
} else {
if(bonusForMainICO == _newBonus) { revert(); }
bonusForMainICO = _newBonus;
BonusChanged("Main ICO", _newBonus);
}
}
function withdrawUnsoldTokens() public onlyOwner {
TokensWithdrawn(owner, lmda.balanceOf(address(this)));
lmda.transfer(owner, lmda.balanceOf(address(this)));
}
function unpauseToken() public onlyOwner {
TokensUnpaused();
lmda.unpause();
}
function transferTokenOwnership() public onlyOwner {
lmda.transferOwnership(owner);
}
function pauseICO() public onlyOwner whenNotPaused {
require(now < endTime);
timePaused = now;
icoPaused = true;
ICOPaused(now);
}
function unpauseICO() public onlyOwner {
endTime = endTime.add(now.sub(timePaused));
timePaused = 0;
icoPaused = false;
ICOUnpaused(now);
}
function getTokensSold() public view returns(uint256 _tokensSold) {
_tokensSold = tokensSold;
}
function getBonus() public view returns(uint256 _bonus) {
if(stateOfICO == StateOfICO.PRE) {
_bonus = bonusForPreICO;
} else {
_bonus = bonusForMainICO;
}
}
function getRate() public view returns(uint256 _exchangeRate) {
if(stateOfICO == StateOfICO.PRE) {
_exchangeRate = rateForPreICO;
} else {
_exchangeRate = rateForMainICO;
}
}
function getTokenPrice() public view returns(uint256 _tokenPrice) {
if(stateOfICO == StateOfICO.PRE) {
_tokenPrice = tokenPriceForPreICO;
} else {
_tokenPrice = tokenPriceForMainICO;
}
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is StandardToken, Ownable {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) onlyOwner public {
require(_value > 0);
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 IntelligentMining is BurnableToken {
string public constant name = "Intelligent Mining";
string public constant symbol = "IM";
uint public constant decimals = 18;
uint256 public constant initialSupply = 900000000 * (10 ** uint256(decimals));
constructor() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
} | 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 = 28684800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x5e62AD8b6b3047d5BA7F987F5E7a181E04662002;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.21;
contract IRightAndRoles {
address[][] public wallets;
mapping(address => uint16) public roles;
event WalletChanged(address indexed newWallet, address indexed oldWallet, uint8 indexed role);
event CloneChanged(address indexed wallet, uint8 indexed role, bool indexed mod);
function changeWallet(address _wallet, uint8 _role) external;
function setManagerPowerful(bool _mode) external;
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool);
}
contract ICreator{
IRightAndRoles public rightAndRoles;
function createAllocation(IToken _token, uint256 _unlockPart1, uint256 _unlockPart2) external returns (IAllocation);
function createFinancialStrategy() external returns(IFinancialStrategy);
function getRightAndRoles() external returns(IRightAndRoles);
}
contract IFinancialStrategy{
enum State { Active, Refunding, Closed }
State public state = State.Active;
event Deposited(address indexed beneficiary, uint256 weiAmount);
event Receive(address indexed beneficiary, uint256 weiAmount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
event Started();
event Closed();
event RefundsEnabled();
function freeCash() view public returns(uint256);
function deposit(address _beneficiary) external payable;
function refund(address _investor) external;
function setup(uint8 _state, bytes32[] _params) external;
function getBeneficiaryCash() external;
function getPartnerCash(uint8 _user, address _msgsender) external;
}
contract IToken{
function setUnpausedWallet(address _wallet, bool mode) public;
function mint(address _to, uint256 _amount) public returns (bool);
function totalSupply() public view returns (uint256);
function setPause(bool mode) public;
function setMigrationAgent(address _migrationAgent) public;
function migrateAll(address[] _holders) public;
function burn(address _beneficiary, uint256 _value) public;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount);
function defrostDate(address _beneficiary) public view returns (uint256 Date);
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public;
}
contract IAllocation {
function addShare(address _beneficiary, uint256 _proportion, uint256 _percenForFirstPart) external;
}
contract GuidedByRoles {
IRightAndRoles public rightAndRoles;
function GuidedByRoles(IRightAndRoles _rightAndRoles) public {
rightAndRoles = _rightAndRoles;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
if (b>=a) return 0;
return a - b;
}
}
contract Crowdsale is GuidedByRoles{
uint256 constant USER_UNPAUSE_TOKEN_TIMEOUT = 60 days;
uint256 constant FORCED_REFUND_TIMEOUT1 = 400 days;
uint256 constant FORCED_REFUND_TIMEOUT2 = 600 days;
uint256 constant ROUND_PROLONGATE = 90 days;
using SafeMath for uint256;
enum TokenSaleType {round1, round2}
TokenSaleType public TokenSale = TokenSaleType.round1;
ICreator public creator;
bool isBegin=false;
IToken public token;
IAllocation public allocation;
IFinancialStrategy public financialStrategy;
bool public isFinalized;
bool public isInitialized;
bool public isPausedCrowdsale;
bool public chargeBonuses;
bool public canFirstMint=true;
struct Bonus {
uint256 value;
uint256 procent;
uint256 freezeTime;
}
struct Profit {
uint256 percent;
uint256 duration;
}
struct Freezed {
uint256 value;
uint256 dateTo;
}
Bonus[] public bonuses;
Profit[] public profits;
uint256 public startTime= 1537401600;
uint256 public endTime = 1540079999;
uint256 public renewal;
uint256 public rate = 9855 ether;
uint256 public exchange = 680 ether;
uint256 public softCap = 1400 ether;
uint256 public hardCap = 88300 ether;
uint256 public overLimit = 20 ether;
uint256 public minPay = 15 finney;
uint256 public maxAllProfit = 35;
uint256 public ethWeiRaised;
uint256 public nonEthWeiRaised;
uint256 public weiRound1;
uint256 public tokenReserved;
uint256 public totalSaledToken;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
event Initialized();
event PaymentedInOtherCurrency(uint256 token, uint256 value);
event ExchangeChanged(uint256 indexed oldExchange, uint256 indexed newExchange);
function Crowdsale(ICreator _creator,IToken _token) GuidedByRoles(_creator.getRightAndRoles()) public
{
creator=_creator;
token = _token;
}
function begin() public
{
require(rightAndRoles.onlyRoles(msg.sender,22));
if (isBegin) return;
isBegin=true;
financialStrategy = creator.createFinancialStrategy();
token.setUnpausedWallet(rightAndRoles.wallets(1,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(3,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(4,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(5,0), true);
token.setUnpausedWallet(rightAndRoles.wallets(6,0), true);
bonuses.push(Bonus(73529 finney, 10,0));
bonuses.push(Bonus(147059 finney, 15,0));
bonuses.push(Bonus(367647 finney, 20,0));
profits.push(Profit(15,7 days));
profits.push(Profit(10,7 days));
profits.push(Profit(5,7 days));
}
function firstMintRound0(uint256 _amount ) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(canFirstMint);
begin();
token.mint(rightAndRoles.wallets(3,0),_amount);
}
function firstMintRound0For(address[] _to, uint256[] _amount, bool[] _setAsUnpaused) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(canFirstMint);
begin();
require(_to.length == _amount.length && _to.length == _setAsUnpaused.length);
for(uint256 i = 0; i < _to.length; i++){
token.mint(_to[i],_amount[i]);
if(_setAsUnpaused[i]){
token.setUnpausedWallet(_to[i], true);
}
}
}
function totalSupply() external view returns (uint256){
return token.totalSupply();
}
function getTokenSaleType() external view returns(string){
return (TokenSale == TokenSaleType.round1)?'round1':'round2';
}
function forwardFunds(address _beneficiary) internal {
financialStrategy.deposit.value(msg.value)(_beneficiary);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = (now > startTime && now < endTime.add(renewal));
bool nonZeroPurchase = msg.value >= minPay;
bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit);
return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isFinalized && !isPausedCrowdsale;
}
function hasEnded() public view returns (bool) {
bool isAdmin = rightAndRoles.onlyRoles(msg.sender,6);
bool timeReached = now > endTime.add(renewal);
bool capReached = weiRaised() >= hardCap;
return (timeReached || capReached || (isAdmin && goalReached())) && isInitialized && !isFinalized;
}
function finalize() public {
require(hasEnded());
isFinalized = true;
finalization();
emit Finalized();
}
function finalization() internal {
bytes32[] memory params = new bytes32[](0);
if (goalReached()) {
financialStrategy.setup(1,params);
if (tokenReserved > 0) {
token.mint(rightAndRoles.wallets(3,0),tokenReserved);
tokenReserved = 0;
}
if (TokenSale == TokenSaleType.round1) {
isInitialized = false;
isFinalized = false;
if(financialStrategy.freeCash() == 0){
rightAndRoles.setManagerPowerful(true);
}
TokenSale = TokenSaleType.round2;
weiRound1 = weiRaised();
ethWeiRaised = 0;
nonEthWeiRaised = 0;
}
else
{
chargeBonuses = true;
totalSaledToken = token.totalSupply();
}
}
else
{
financialStrategy.setup(3,params);
}
}
function finalize2() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(chargeBonuses);
chargeBonuses = false;
allocation = creator.createAllocation(token, now + 1 years ,0);
token.setUnpausedWallet(allocation, true);
allocation.addShare(rightAndRoles.wallets(7,0),100,100);
token.mint(rightAndRoles.wallets(5,0), totalSaledToken.mul(2).div(58));
token.mint(rightAndRoles.wallets(6,0), totalSaledToken.mul(25).div(58));
token.mint(allocation, totalSaledToken.mul(15).div(58));
}
function initialize() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(!isInitialized);
begin();
require(now <= startTime);
initialization();
emit Initialized();
renewal = 0;
isInitialized = true;
canFirstMint = false;
}
function initialization() internal {
bytes32[] memory params = new bytes32[](0);
rightAndRoles.setManagerPowerful(false);
if (financialStrategy.state() != IFinancialStrategy.State.Active){
financialStrategy.setup(2,params);
}
}
function getPartnerCash(uint8 _user, bool _calc) external {
if(_calc)
calcFin();
financialStrategy.getPartnerCash(_user, msg.sender);
}
function getBeneficiaryCash(bool _calc) public {
require(rightAndRoles.onlyRoles(msg.sender,22));
if(_calc)
calcFin();
financialStrategy.getBeneficiaryCash();
if(!isInitialized && financialStrategy.freeCash() == 0)
rightAndRoles.setManagerPowerful(true);
}
function claimRefund() external{
financialStrategy.refund(msg.sender);
}
function calcFin() public {
bytes32[] memory params = new bytes32[](2);
params[0] = bytes32(weiTotalRaised());
params[1] = bytes32(msg.sender);
financialStrategy.setup(4,params);
}
function calcAndGet() public {
require(rightAndRoles.onlyRoles(msg.sender,22));
getBeneficiaryCash(true);
for (uint8 i=0; i<0; i++) {
financialStrategy.getPartnerCash(i, msg.sender);
}
}
function goalReached() public view returns (bool) {
return weiRaised() >= softCap;
}
function setup(uint256 _startTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap,
uint256 _rate, uint256 _exchange,
uint256 _maxAllProfit, uint256 _overLimit, uint256 _minPay,
uint256[] _durationTB , uint256[] _percentTB, uint256[] _valueVB, uint256[] _percentVB, uint256[] _freezeTimeVB) public
{
require(rightAndRoles.onlyRoles(msg.sender,6));
require(!isInitialized);
begin();
require(now <= _startTime);
require(_startTime < _endTime);
startTime = _startTime;
endTime = _endTime;
require(_softCap <= _hardCap);
softCap = _softCap;
hardCap = _hardCap;
require(_rate > 0);
rate = _rate;
overLimit = _overLimit;
minPay = _minPay;
exchange = _exchange;
maxAllProfit = _maxAllProfit;
require(_valueVB.length == _percentVB.length && _valueVB.length == _freezeTimeVB.length);
bonuses.length = _valueVB.length;
for(uint256 i = 0; i < _valueVB.length; i++){
bonuses[i] = Bonus(_valueVB[i],_percentVB[i],_freezeTimeVB[i]);
}
require(_percentTB.length == _durationTB.length);
profits.length = _percentTB.length;
for( i = 0; i < _percentTB.length; i++){
profits[i] = Profit(_percentTB[i],_durationTB[i]);
}
}
function weiRaised() public constant returns(uint256){
return ethWeiRaised.add(nonEthWeiRaised);
}
function weiTotalRaised() public constant returns(uint256){
return weiRound1.add(weiRaised());
}
function getProfitPercent() public constant returns (uint256){
return getProfitPercentForData(now);
}
function getProfitPercentForData(uint256 _timeNow) public constant returns (uint256){
uint256 allDuration;
for(uint8 i = 0; i < profits.length; i++){
allDuration = allDuration.add(profits[i].duration);
if(_timeNow < startTime.add(allDuration)){
return profits[i].percent;
}
}
return 0;
}
function getBonuses(uint256 _value) public constant returns (uint256,uint256,uint256){
if(bonuses.length == 0 || bonuses[0].value > _value){
return (0,0,0);
}
uint16 i = 1;
for(i; i < bonuses.length; i++){
if(bonuses[i].value > _value){
break;
}
}
return (bonuses[i-1].value,bonuses[i-1].procent,bonuses[i-1].freezeTime);
}
function tokenUnpause() external {
require(rightAndRoles.onlyRoles(msg.sender,2)
|| (now > endTime.add(renewal).add(USER_UNPAUSE_TOKEN_TIMEOUT) && TokenSale == TokenSaleType.round2 && isFinalized && goalReached()));
token.setPause(false);
}
function tokenPause() public {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(!isFinalized);
token.setPause(true);
}
function setCrowdsalePause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
isPausedCrowdsale = mode;
}
function moveTokens(address _migrationAgent) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
token.setMigrationAgent(_migrationAgent);
}
function migrateAll(address[] _holders) public {
require(rightAndRoles.onlyRoles(msg.sender,6));
token.migrateAll(_holders);
}
function prolong(uint256 _duration) external {
require(rightAndRoles.onlyRoles(msg.sender,6));
require(now > startTime && now < endTime.add(renewal) && isInitialized && !isFinalized);
renewal = renewal.add(_duration);
require(renewal <= ROUND_PROLONGATE);
}
function distructVault() public {
bytes32[] memory params = new bytes32[](1);
params[0] = bytes32(msg.sender);
if (rightAndRoles.onlyRoles(msg.sender,4) && (now > startTime.add(FORCED_REFUND_TIMEOUT1))) {
financialStrategy.setup(0,params);
}
if (rightAndRoles.onlyRoles(msg.sender,2) && (now > startTime.add(FORCED_REFUND_TIMEOUT2))) {
financialStrategy.setup(0,params);
}
}
function paymentsInOtherCurrency(uint256 _token, uint256 _value) public {
require(rightAndRoles.onlyRoles(msg.sender,18));
bool withinPeriod = (now >= startTime && now <= endTime.add(renewal));
bool withinCap = _value.add(ethWeiRaised) <= hardCap.add(overLimit);
require(withinPeriod && withinCap && isInitialized && !isFinalized);
emit PaymentedInOtherCurrency(_token,_value);
nonEthWeiRaised = _value;
tokenReserved = _token;
}
function lokedMint(address _beneficiary, uint256 _value, uint256 _freezeTime) internal {
if(_freezeTime > 0){
uint256 totalBloked = token.freezedTokenOf(_beneficiary).add(_value);
uint256 pastDateUnfreeze = token.defrostDate(_beneficiary);
uint256 newDateUnfreeze = _freezeTime.add(now);
newDateUnfreeze = (pastDateUnfreeze > newDateUnfreeze ) ? pastDateUnfreeze : newDateUnfreeze;
token.freezeTokens(_beneficiary,totalBloked,newDateUnfreeze);
}
token.mint(_beneficiary,_value);
}
function buyTokens(address _beneficiary) public payable {
require(_beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 ProfitProcent = getProfitPercent();
uint256 value;
uint256 percent;
uint256 freezeTime;
(value,
percent,
freezeTime) = getBonuses(weiAmount);
Bonus memory curBonus = Bonus(value,percent,freezeTime);
uint256 bonus = curBonus.procent;
uint256 totalProfit = bonus.add(ProfitProcent);
totalProfit = (totalProfit > maxAllProfit) ? maxAllProfit : totalProfit;
uint256 tokens = weiAmount.mul(rate).mul(totalProfit.add(100)).div(100 ether);
ethWeiRaised = ethWeiRaised.add(weiAmount);
lokedMint(_beneficiary, tokens, curBonus.freezeTime);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
forwardFunds(_beneficiary);
}
function () public payable {
buyTokens(msg.sender);
}
} | 0 |
pragma solidity ^0.4.11;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender == owner)
_;
}
}
contract tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData);
}
contract IERC20Token {
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);
event Burn(address indexed from, uint256 value);
}
contract TESTH is IERC20Token, owned{
string public standard = "TESTH v1.0";
string public name = "TESTH";
string public symbol = "TESTH";
uint8 public decimals = 18;
uint256 public initialSupply = 50000000 * 10 ** 18;
uint256 public tokenFrozenUntilBlock;
uint256 public timeLock = block.timestamp + 2 days;
uint256 supply = initialSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
mapping (address => bool) rAddresses;
event TokenFrozen(uint256 _frozenUntilBlock, string _reason);
function TESTH() {
rAddresses[0x0] = true;
rAddresses[address(this)] = true;
}
function totalSupply() constant returns (uint256 totalSupply) {
return supply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transferOwnership(address newOwner) onlyOwner {
require(transfer(newOwner, balances[msg.sender]));
owner = newOwner;
}
function transfer(address _to, uint256 _value) returns (bool success) {
require (block.number >= tokenFrozenUntilBlock) ;
require (!rAddresses[_to]) ;
require (balances[msg.sender] >= _value);
require (balances[_to] + _value >= balances[_to]) ;
require (!(msg.sender == owner && block.timestamp < timeLock && (balances[msg.sender]-_value) < 10000000 * 10 ** 18));
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
require (block.number > tokenFrozenUntilBlock);
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
approve(_spender, _value);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require (block.number > tokenFrozenUntilBlock);
require (!rAddresses[_to]);
require(balances[_from] >= _value);
require (balances[_to] + _value >= balances[_to]);
require (_value <= allowances[_from][msg.sender]);
require (!(_from == owner && block.timestamp < timeLock && (balances[_from]-_value) < 10000000 * 10 ** 18));
balances[_from] -= _value;
balances[_to] += _value;
allowances[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
supply-=_value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) returns (bool success) {
require(balances[_from] >= _value);
require(_value <= allowances[_from][msg.sender]);
balances[_from] -= _value;
allowances[_from][msg.sender] -= _value;
supply -= _value;
Burn(_from, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
function freezeTransfersUntil(uint256 _frozenUntilBlock, string _reason) onlyOwner {
tokenFrozenUntilBlock = _frozenUntilBlock;
TokenFrozen(_frozenUntilBlock, _reason);
}
function unfreezeTransfersUntil(string _reason) onlyOwner {
tokenFrozenUntilBlock = 0;
TokenFrozen(0, _reason);
}
function editRestrictedAddress(address _newRestrictedAddress) onlyOwner {
rAddresses[_newRestrictedAddress] = !rAddresses[_newRestrictedAddress];
}
function isRestrictedAddress(address _queryAddress) constant returns (bool answer){
return rAddresses[_queryAddress];
}
} | 1 |
pragma solidity ^0.4.24;
contract UsdPrice {
function USD(uint _id) constant returns (uint256);
}
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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
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);
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
}
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 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) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken, Ownable {
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 MintableToken is StandardToken {
event TokensMinted(address indexed to, uint256 value);
function mintTokens(address _addr, uint256 _value) public onlyOwner returns(bool) {
totalSupply = totalSupply.add(_value);
balances[_addr] = balances[_addr].add(_value);
emit Transfer(owner, _addr, _value);
emit TokensMinted(_addr, _value);
}
}
contract Titanization is MintableToken {
function Titanization() public {
name = "Titanization";
symbol = "TXDM";
decimals = 0;
totalSupply = 0;
balances[owner] = totalSupply;
Transfer(address(this), owner, totalSupply);
}
}
contract ICO is Ownable {
using SafeMath for uint256;
Titanization public TXDM;
UsdPrice public constant FIAT = UsdPrice(0x8055d0504666e2B6942BeB8D6014c964658Ca591);
address public constant RESERVE_ADDRESS = 0xF21DAa0CeC36C0d8dC64B5351119888c5a7CFc4d;
uint256 private minTokenPurchase;
uint256 private tokensSold;
uint256 private hardCap;
uint256 private softCap;
bool private IcoTerminated;
uint256 private tokenPrice;
constructor() public {
TXDM = new Titanization();
minTokenPurchase = 50;
hardCap = 65000000;
softCap = 10000000;
IcoTerminated = false;
tokenPrice = 500;
}
function terminateICO() public onlyOwner returns(bool) {
require(!IcoTerminated);
IcoTerminated = true;
return true;
}
function activateICO() public onlyOwner returns(bool) {
require(IcoTerminated);
IcoTerminated = false;
return true;
}
function IcoActive() public view returns(bool) {
return (!IcoTerminated);
}
function getHardCap() public view returns(uint256) {
return hardCap;
}
function changeHardCap(uint256 _newHardCap) public onlyOwner returns(bool) {
require(hardCap != _newHardCap && _newHardCap >= tokensSold && _newHardCap > softCap);
hardCap = _newHardCap;
return true;
}
function getSoftCap() public view returns(uint256) {
return softCap;
}
function changeSoftCap(uint256 _newSoftCap) public onlyOwner returns(bool) {
require(_newSoftCap != softCap && _newSoftCap < hardCap);
softCap = _newSoftCap;
return true;
}
function getTokensSold() public view returns(uint256) {
return tokensSold;
}
function changeTokenPrice(uint256 _newTokenPrice) public onlyOwner returns(bool) {
tokenPrice = _newTokenPrice;
return true;
}
function getTokenPrice() public view returns(uint256) {
return FIAT.USD(0).mul(tokenPrice);
}
function getMinInvestment() public view returns(uint256) {
return getTokenPrice().mul(minTokenPurchase);
}
function getMinTokenPurchase() public view returns(uint256) {
return minTokenPurchase;
}
function setMinTokenPurchase(uint256 _minTokens) public onlyOwner returns(bool) {
require(minTokenPurchase != _minTokens);
minTokenPurchase = _minTokens;
return true;
}
function() public payable {
buyTokens(msg.sender);
}
function buyTokens(address _addr) public payable returns(bool) {
uint256 tokenPrice = getTokenPrice();
require(
msg.value >= getMinInvestment() && msg.value % tokenPrice == 0
|| TXDM.balanceOf(msg.sender) >= minTokenPurchase && msg.value % tokenPrice == 0
);
require(tokensSold.add(msg.value.div(tokenPrice)) <= hardCap);
require(!IcoTerminated);
TXDM.mintTokens(_addr, msg.value.div(tokenPrice));
tokensSold = tokensSold.add(msg.value.div(tokenPrice));
owner.transfer(msg.value);
return true;
}
function claimReserveTokens(uint256 _value) public onlyOwner returns(bool) {
TXDM.mintTokens(RESERVE_ADDRESS, _value);
return true;
}
function transferTokenOwnership(address _newOwner) public onlyOwner returns(bool) {
TXDM.transferOwnership(_newOwner);
}
} | 0 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function 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 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);
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() 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 Bilibit is StandardToken {
string public constant name = "Bilibit";
string public constant symbol = "BLB";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 50000000 * (10 ** uint256(decimals));
function Bilibit() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | 1 |
pragma solidity ^0.4.24;
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
contract modularFast is F3Devents {}
contract FoMo3DFast is modularFast {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xe04c48654AE73771AB6b73767c86D623bDc0bD98);
address private admin = msg.sender;
string constant public name = "OTION";
string constant public symbol = "OTION";
uint256 private rndExtra_ = 30 minutes;
uint256 private rndGap_ = 30 minutes;
uint256 constant private rndInit_ = 88 minutes;
uint256 constant private rndInc_ = 20 seconds;
uint256 constant private rndMax_ = 888 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(80,0);
potSplit_[0] = F3Ddatasets.PotSplit(0,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, _eventData_);
}
function buyXnameQR(address _realSender)
isActivated()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePIDQR(_realSender,_eventData_);
uint256 _pID = pIDxAddr_[_realSender];
buyCoreQR(_realSender, _pID, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function withdrawQR(address _realSender)
isActivated()
payable
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[_realSender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
_realSender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, _realSender, plyr_[_pID].name, _eth, _now);
}
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add(((round_[_rID].pot))),
(plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _affID = 1;
uint256 _team = 0;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(address(0), _rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function buyCoreQR(address _realSender, uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _affID = 1;
uint256 _team = 0;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_realSender,_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
_realSender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function core(address _realSender, uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 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_);
endTxQR(_realSender,_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)
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;
}
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 determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.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 determinePIDQR(address _realSender, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[_realSender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(_realSender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[_realSender] = _pID;
plyr_[_pID].addr = _realSender;
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 verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = _pot;
uint256 _gen = 0;
uint256 _p3d = 0;
uint256 _res = 0;
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _p3d = _eth / 50;
uint256 _aff = _eth.mul(8) / 100;
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
admin.transfer(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _potAmount = _eth / 10;
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _potAmount.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _potAmount;
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 endTxQR(address _realSender,uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
_realSender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Short already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
} | 0 |
pragma solidity ^0.4.16;
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract OtcInterface {
function sellAllAmount(address, uint, address, uint) public returns (uint);
function buyAllAmount(address, uint, address, uint) public returns (uint);
function getPayAmount(address, address, uint) public constant returns (uint);
}
contract TokenInterface {
function balanceOf(address) public returns (uint);
function allowance(address, address) public returns (uint);
function approve(address, uint) public;
function transfer(address,uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
function deposit() public payable;
function withdraw(uint) public;
}
contract OasisDirectProxy is DSMath {
function withdrawAndSend(TokenInterface wethToken, uint wethAmt) internal {
wethToken.withdraw(wethAmt);
require(msg.sender.call.value(wethAmt)());
}
function sellAllAmount(OtcInterface otc, TokenInterface payToken, uint payAmt, TokenInterface buyToken, uint minBuyAmt) public returns (uint buyAmt) {
require(payToken.transferFrom(msg.sender, this, payAmt));
if (payToken.allowance(this, otc) < payAmt) {
payToken.approve(otc, uint(-1));
}
buyAmt = otc.sellAllAmount(payToken, payAmt, buyToken, minBuyAmt);
require(buyToken.transfer(msg.sender, buyAmt));
}
function sellAllAmountPayEth(OtcInterface otc, TokenInterface wethToken, TokenInterface buyToken, uint minBuyAmt) public payable returns (uint buyAmt) {
wethToken.deposit.value(msg.value)();
if (wethToken.allowance(this, otc) < msg.value) {
wethToken.approve(otc, uint(-1));
}
buyAmt = otc.sellAllAmount(wethToken, msg.value, buyToken, minBuyAmt);
require(buyToken.transfer(msg.sender, buyAmt));
}
function sellAllAmountBuyEth(OtcInterface otc, TokenInterface payToken, uint payAmt, TokenInterface wethToken, uint minBuyAmt) public returns (uint wethAmt) {
require(payToken.transferFrom(msg.sender, this, payAmt));
if (payToken.allowance(this, otc) < payAmt) {
payToken.approve(otc, uint(-1));
}
wethAmt = otc.sellAllAmount(payToken, payAmt, wethToken, minBuyAmt);
withdrawAndSend(wethToken, wethAmt);
}
function buyAllAmount(OtcInterface otc, TokenInterface buyToken, uint buyAmt, TokenInterface payToken, uint maxPayAmt) public returns (uint payAmt) {
uint payAmtNow = otc.getPayAmount(payToken, buyToken, buyAmt);
require(payAmtNow <= maxPayAmt);
require(payToken.transferFrom(msg.sender, this, payAmtNow));
if (payToken.allowance(this, otc) < payAmtNow) {
payToken.approve(otc, uint(-1));
}
payAmt = otc.buyAllAmount(buyToken, buyAmt, payToken, payAmtNow);
require(buyToken.transfer(msg.sender, min(buyAmt, buyToken.balanceOf(this))));
}
function buyAllAmountPayEth(OtcInterface otc, TokenInterface buyToken, uint buyAmt, TokenInterface wethToken) public payable returns (uint wethAmt) {
wethToken.deposit.value(msg.value)();
if (wethToken.allowance(this, otc) < msg.value) {
wethToken.approve(otc, uint(-1));
}
wethAmt = otc.buyAllAmount(buyToken, buyAmt, wethToken, msg.value);
require(buyToken.transfer(msg.sender, min(buyAmt, buyToken.balanceOf(this))));
withdrawAndSend(wethToken, sub(msg.value, wethAmt));
}
function buyAllAmountBuyEth(OtcInterface otc, TokenInterface wethToken, uint wethAmt, TokenInterface payToken, uint maxPayAmt) public returns (uint payAmt) {
uint payAmtNow = otc.getPayAmount(payToken, wethToken, wethAmt);
require(payAmtNow <= maxPayAmt);
require(payToken.transferFrom(msg.sender, this, payAmtNow));
if (payToken.allowance(this, otc) < payAmtNow) {
payToken.approve(otc, uint(-1));
}
payAmt = otc.buyAllAmount(wethToken, wethAmt, payToken, payAmtNow);
withdrawAndSend(wethToken, wethAmt);
}
function() public payable {}
}
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache;
function DSProxy(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0)
switch iszero(succeeded)
case 1 {
revert(0, 0)
}
}
}
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0);
cache = DSProxyCache(_cacheAddr);
return true;
}
}
contract DSProxyFactory {
event Created(address indexed sender, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
Created(owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
contract ProxyCreationAndExecute is OasisDirectProxy {
function createAndSellAllAmount(DSProxyFactory factory, OtcInterface otc, TokenInterface payToken, uint payAmt, TokenInterface buyToken, uint minBuyAmt) public returns (DSProxy proxy, uint buyAmt) {
proxy = factory.build(msg.sender);
buyAmt = sellAllAmount(otc, payToken, payAmt, buyToken, minBuyAmt);
}
function createAndSellAllAmountPayEth(DSProxyFactory factory, OtcInterface otc, TokenInterface wethToken, TokenInterface buyToken, uint minBuyAmt) public payable returns (DSProxy proxy, uint buyAmt) {
proxy = factory.build(msg.sender);
buyAmt = sellAllAmountPayEth(otc, wethToken, buyToken, minBuyAmt);
}
function createAndSellAllAmountBuyEth(DSProxyFactory factory, OtcInterface otc, TokenInterface payToken, uint payAmt, TokenInterface wethToken, uint minBuyAmt) public returns (DSProxy proxy, uint wethAmt) {
proxy = factory.build(msg.sender);
wethAmt = sellAllAmountBuyEth(otc, payToken, payAmt, wethToken, minBuyAmt);
}
function createAndBuyAllAmount(DSProxyFactory factory, OtcInterface otc, TokenInterface buyToken, uint buyAmt, TokenInterface payToken, uint maxPayAmt) public returns (DSProxy proxy, uint payAmt) {
proxy = factory.build(msg.sender);
payAmt = buyAllAmount(otc, buyToken, buyAmt, payToken, maxPayAmt);
}
function createAndBuyAllAmountPayEth(DSProxyFactory factory, OtcInterface otc, TokenInterface buyToken, uint buyAmt, TokenInterface wethToken) public payable returns (DSProxy proxy, uint wethAmt) {
proxy = factory.build(msg.sender);
wethAmt = buyAllAmountPayEth(otc, buyToken, buyAmt, wethToken);
}
function createAndBuyAllAmountBuyEth(DSProxyFactory factory, OtcInterface otc, TokenInterface wethToken, uint wethAmt, TokenInterface payToken, uint maxPayAmt) public returns (DSProxy proxy, uint payAmt) {
proxy = factory.build(msg.sender);
payAmt = buyAllAmountBuyEth(otc, wethToken, wethAmt, payToken, maxPayAmt);
}
} | 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 CryptoBankToken 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(_value > 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(_value > 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.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity ^0.4.24;
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.4.24;
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
pragma solidity ^0.4.24;
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint256 public releaseTime;
constructor(
ERC20Basic _token,
address _beneficiary,
uint256 _releaseTime
)
public
{
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(address(this));
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
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;
}
}
pragma solidity ^0.4.24;
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
function release(ERC20Basic _token) public {
uint256 unreleased = releasableAmount(_token);
require(unreleased > 0);
released[_token] = released[_token].add(unreleased);
_token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
function revoke(ERC20Basic _token) public onlyOwner {
require(revocable);
require(!revoked[_token]);
uint256 balance = _token.balanceOf(address(this));
uint256 unreleased = releasableAmount(_token);
uint256 refund = balance.sub(unreleased);
revoked[_token] = true;
_token.safeTransfer(owner, refund);
emit Revoked();
}
function releasableAmount(ERC20Basic _token) public view returns (uint256) {
return vestedAmount(_token).sub(released[_token]);
}
function vestedAmount(ERC20Basic _token) public view returns (uint256) {
uint256 currentBalance = _token.balanceOf(address(this));
uint256 totalBalance = currentBalance.add(released[_token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[_token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
pragma solidity ^0.4.24;
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
pragma solidity ^0.4.24;
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
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;
}
}
pragma solidity ^0.4.24;
contract TileToken is StandardToken {
string public constant name = "LOOMIA TILE";
string public constant symbol = "TILE";
uint8 public constant decimals = 18;
uint256 public totalSupply = 109021227 * 1e18;
constructor() public {
balances[msg.sender] = totalSupply;
}
}
pragma solidity ^0.4.24;
contract TileDistribution is Ownable {
using SafeMath for uint256;
uint256 public constant VESTING_DURATION = 2 * 365 days;
uint256 public constant VESTING_START_TIME = 1504224000;
uint256 public constant VESTING_CLIFF = 26 weeks;
uint256 public constant TIMELOCK_DURATION = 365 days;
address public constant LOOMIA1_ADDR = 0x1c59Aa1ec35Cfcc222B0e860066796Ccddbe10c8;
address public constant LOOMIA2_ADDR = 0x4c728E555E647214D834E4eBa37844424C0b7eFD;
address public constant LOOMIA_LOOMIA_REMAINDER_ADDR = 0x8b91Eaa35E694524274178586aCC7701CC56cd35;
address public constant BRANDS_ADDR = 0xe4D876bf0b67Bf4547DD6c55559097cC62058726;
address public constant ADVISORS_ADDR = 0x886E7DE436df0fA4593a8534b798995624DB5837;
address public constant THIRD_PARTY_LOCKUP_ADDR = 0x03a41aD81834E8831fFc65CdC3F61Cf04A31806E;
uint256 public constant LOOMIA1 = 3270636.80 * 1e18;
uint256 public constant LOOMIA2 = 3270636.80 * 1e18;
uint256 public constant LOOMIA_REMAINDER = 9811910 * 1e18;
uint256 public constant BRANDS = 10902122.70 * 1e18;
uint256 public constant ADVISORS = 5451061.35 * 1e18;
uint256 public constant THIRD_PARTY_LOCKUP = 5451061.35 * 1e18;
ERC20Basic public token;
address[3] public tokenVestingAddresses;
address public tokenTimelockAddress;
event AirDrop(address indexed _beneficiaryAddress, uint256 _amount);
modifier validAddressAmount(address _beneficiaryWallet, uint256 _amount) {
require(_beneficiaryWallet != address(0));
require(_amount != 0);
_;
}
constructor () public {
token = createTokenContract();
createVestingContract();
createTimeLockContract();
}
function () external payable {
revert();
}
function batchDistributeTokens(address[] _beneficiaryWallets, uint256[] _amounts) external onlyOwner {
require(_beneficiaryWallets.length == _amounts.length);
for (uint i = 0; i < _beneficiaryWallets.length; i++) {
distributeTokens(_beneficiaryWallets[i], _amounts[i]);
}
}
function distributeTokens(address _beneficiaryWallet, uint256 _amount) public onlyOwner validAddressAmount(_beneficiaryWallet, _amount) {
token.transfer(_beneficiaryWallet, _amount);
emit AirDrop(_beneficiaryWallet, _amount);
}
function createVestingContract() private {
TokenVesting newVault = new TokenVesting(
LOOMIA1_ADDR, VESTING_START_TIME, VESTING_CLIFF, VESTING_DURATION, false);
tokenVestingAddresses[0] = address(newVault);
token.transfer(address(newVault), LOOMIA1);
TokenVesting newVault2 = new TokenVesting(
LOOMIA2_ADDR, VESTING_START_TIME, VESTING_CLIFF, VESTING_DURATION, false);
tokenVestingAddresses[1] = address(newVault2);
token.transfer(address(newVault2), LOOMIA2);
TokenVesting newVault3 = new TokenVesting(
LOOMIA_LOOMIA_REMAINDER_ADDR, VESTING_START_TIME, VESTING_CLIFF, VESTING_DURATION, false);
tokenVestingAddresses[2] = address(newVault3);
token.transfer(address(newVault3), LOOMIA_REMAINDER);
}
function createTimeLockContract() private {
TokenTimelock timelock = new TokenTimelock(token, THIRD_PARTY_LOCKUP_ADDR, now.add(TIMELOCK_DURATION));
tokenTimelockAddress = address(timelock);
token.transfer(tokenTimelockAddress, THIRD_PARTY_LOCKUP);
}
function createTokenContract() private returns (ERC20Basic) {
return new TileToken();
}
} | 0 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract InvestedProvider is Ownable {
uint public invested;
}
contract AddressesFilterFeature is Ownable {
mapping(address => bool) public allowedAddresses;
function addAllowedAddress(address allowedAddress) public onlyOwner {
allowedAddresses[allowedAddress] = true;
}
function removeAllowedAddress(address allowedAddress) public onlyOwner {
allowedAddresses[allowedAddress] = false;
}
}
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 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is AddressesFilterFeature, StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
mapping (address => uint) public initialBalances;
modifier notLocked(address _from) {
require(_from == owner || _from == saleAgent || allowedAddresses[_from] || mintingFinished);
_;
}
function setSaleAgent(address newSaleAgnet) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
initialBalances[_to] = balances[_to];
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
function transfer(address _to, uint256 _value) public notLocked(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address from, address to, uint256 value) public notLocked(from) returns (bool) {
return super.transferFrom(from, to, value);
}
}
contract TokenProvider is Ownable {
MintableToken public token;
function setToken(address newToken) public onlyOwner {
token = MintableToken(newToken);
}
}
contract MintTokensInterface is TokenProvider {
function mintTokens(address to, uint tokens) internal;
}
contract MintTokensFeature is MintTokensInterface {
function mintTokens(address to, uint tokens) internal {
token.mint(to, tokens);
}
}
contract PercentRateProvider {
uint public percentRate = 100;
}
contract PercentRateFeature is Ownable, PercentRateProvider {
function setPercentRate(uint newPercentRate) public onlyOwner {
percentRate = newPercentRate;
}
}
contract RetrieveTokensFeature is Ownable {
function retrieveTokens(address to, address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(to, alienToken.balanceOf(this));
}
}
contract WalletProvider is Ownable {
address public wallet;
function setWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
}
contract CommonSale is InvestedProvider, WalletProvider, PercentRateFeature, RetrieveTokensFeature, MintTokensFeature {
using SafeMath for uint;
address public directMintAgent;
uint public price;
uint public start;
uint public minInvestedLimit;
uint public hardcap;
modifier isUnderHardcap() {
require(invested < hardcap);
_;
}
function setHardcap(uint newHardcap) public onlyOwner {
hardcap = newHardcap;
}
modifier onlyDirectMintAgentOrOwner() {
require(directMintAgent == msg.sender || owner == msg.sender);
_;
}
modifier minInvestLimited(uint value) {
require(value >= minInvestedLimit);
_;
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setMinInvestedLimit(uint newMinInvestedLimit) public onlyOwner {
minInvestedLimit = newMinInvestedLimit;
}
function setDirectMintAgent(address newDirectMintAgent) public onlyOwner {
directMintAgent = newDirectMintAgent;
}
function setPrice(uint newPrice) public onlyOwner {
price = newPrice;
}
function calculateTokens(uint _invested) internal returns(uint);
function mintTokensExternal(address to, uint tokens) public onlyDirectMintAgentOrOwner {
mintTokens(to, tokens);
}
function endSaleDate() public view returns(uint);
function mintTokensByETHExternal(address to, uint _invested) public onlyDirectMintAgentOrOwner returns(uint) {
return mintTokensByETH(to, _invested);
}
function mintTokensByETH(address to, uint _invested) internal isUnderHardcap returns(uint) {
invested = invested.add(_invested);
uint tokens = calculateTokens(_invested);
mintTokens(to, tokens);
return tokens;
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
wallet.transfer(msg.value);
return mintTokensByETH(msg.sender, msg.value);
}
function () public payable {
fallback();
}
}
contract TimeCountBonusFeature is CommonSale {
struct Milestone {
uint hardcap;
uint price;
uint period;
uint invested;
uint closed;
}
uint public period;
Milestone[] public milestones;
function milestonesCount() public constant returns(uint) {
return milestones.length;
}
function addMilestone(uint _hardcap, uint _price, uint _period) public onlyOwner {
require(_hardcap > 0 && _price > 0 && _period > 0);
Milestone memory milestone = Milestone(_hardcap.mul(1 ether), _price, _period, 0, 0);
milestones.push(milestone);
hardcap = hardcap.add(milestone.hardcap);
period = period.add(milestone.period);
}
function removeMilestone(uint8 number) public onlyOwner {
require(number >=0 && number < milestones.length);
Milestone storage milestone = milestones[number];
hardcap = hardcap.sub(milestone.hardcap);
period = period.sub(milestone.period);
delete milestones[number];
for (uint i = number; i < milestones.length - 1; i++) {
milestones[i] = milestones[i+1];
}
milestones.length--;
}
function changeMilestone(uint8 number, uint _hardcap, uint _price, uint _period) public onlyOwner {
require(number >= 0 &&number < milestones.length);
Milestone storage milestone = milestones[number];
hardcap = hardcap.sub(milestone.hardcap);
period = period.sub(milestone.period);
milestone.hardcap = _hardcap.mul(1 ether);
milestone.price = _price;
milestone.period = _period;
hardcap = hardcap.add(milestone.hardcap);
period = period.add(milestone.period);
}
function insertMilestone(uint8 numberAfter, uint _hardcap, uint _price, uint _period) public onlyOwner {
require(numberAfter < milestones.length);
Milestone memory milestone = Milestone(_hardcap.mul(1 ether), _price, _period, 0, 0);
hardcap = hardcap.add(milestone.hardcap);
period = period.add(milestone.period);
milestones.length++;
for (uint i = milestones.length - 2; i > numberAfter; i--) {
milestones[i + 1] = milestones[i];
}
milestones[numberAfter + 1] = milestone;
}
function clearMilestones() public onlyOwner {
for (uint i = 0; i < milestones.length; i++) {
delete milestones[i];
}
milestones.length = 0;
hardcap = 0;
period = 0;
}
function endSaleDate() public view returns(uint) {
return start.add(period * 1 days);
}
function currentMilestone() public constant returns(uint) {
uint closeTime = start;
for(uint i=0; i < milestones.length; i++) {
closeTime += milestones[i].period.mul(1 days);
if(milestones[i].closed == 0 && now < closeTime) {
return i;
}
}
revert();
}
function calculateTokens(uint _invested) internal returns(uint) {
uint milestoneIndex = currentMilestone();
Milestone storage milestone = milestones[milestoneIndex];
uint tokens = milestone.price.mul(_invested).div(1 ether);
milestone.invested = milestone.invested.add(_invested);
if(milestone.invested >= milestone.hardcap) {
milestone.closed = now;
}
return tokens;
}
}
contract AssembledCommonSale is TimeCountBonusFeature {
}
contract WalletsPercents is Ownable {
address[] public wallets;
mapping (address => uint) percents;
function addWallet(address wallet, uint percent) public onlyOwner {
wallets.push(wallet);
percents[wallet] = percent;
}
function cleanWallets() public onlyOwner {
wallets.length = 0;
}
}
contract ExtendedWalletsMintTokensFeature is MintTokensInterface, WalletsPercents {
using SafeMath for uint;
uint public percentRate = 100;
function mintExtendedTokens() public onlyOwner {
uint summaryTokensPercent = 0;
for(uint i = 0; i < wallets.length; i++) {
summaryTokensPercent = summaryTokensPercent.add(percents[wallets[i]]);
}
uint mintedTokens = token.totalSupply();
uint allTokens = mintedTokens.mul(percentRate).div(percentRate.sub(summaryTokensPercent));
for(uint k = 0; k < wallets.length; k++) {
mintTokens(wallets[k], allTokens.mul(percents[wallets[k]]).div(percentRate));
}
}
}
contract SoftcapFeature is InvestedProvider, WalletProvider {
using SafeMath for uint;
mapping(address => uint) public balances;
bool public softcapAchieved;
bool public refundOn;
bool public feePayed;
uint public softcap;
uint public constant devLimit = 7500000000000000000;
address public constant devWallet = 0xEA15Adb66DC92a4BbCcC8Bf32fd25E2e86a2A770;
function setSoftcap(uint newSoftcap) public onlyOwner {
softcap = newSoftcap;
}
function withdraw() public {
require(msg.sender == owner || msg.sender == devWallet);
require(softcapAchieved);
if(!feePayed) {
devWallet.transfer(devLimit);
feePayed = true;
}
wallet.transfer(this.balance);
}
function updateBalance(address to, uint amount) internal {
balances[to] = balances[to].add(amount);
if (!softcapAchieved && invested >= softcap) {
softcapAchieved = true;
}
}
function refund() public {
require(refundOn && balances[msg.sender] > 0);
uint value = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(value);
}
function updateRefundState() internal returns(bool) {
if (!softcapAchieved) {
refundOn = true;
}
return refundOn;
}
}
contract TeamWallet is Ownable{
address public token;
address public crowdsale;
uint public lockPeriod;
uint public endLock;
bool public started;
modifier onlyCrowdsale() {
require(crowdsale == msg.sender);
_;
}
function setToken (address _token) public onlyOwner{
token = _token;
}
function setCrowdsale (address _crowdsale) public onlyOwner{
crowdsale = _crowdsale;
}
function setLockPeriod (uint _lockDays) public onlyOwner{
require(!started);
lockPeriod = 1 days * _lockDays;
}
function start () public onlyCrowdsale{
started = true;
endLock = now + lockPeriod;
}
function withdrawTokens (address _to) public onlyOwner{
require(now > endLock);
ERC20 ERC20token = ERC20(token);
ERC20token.transfer(_to, ERC20token.balanceOf(this));
}
}
contract ITO is ExtendedWalletsMintTokensFeature, SoftcapFeature, AssembledCommonSale {
address public teamWallet;
bool public paused;
function setTeamWallet (address _teamWallet) public onlyOwner{
teamWallet = _teamWallet;
}
function mintTokensByETH(address to, uint _invested) internal returns(uint) {
uint _tokens = super.mintTokensByETH(to, _invested);
updateBalance(to, _invested);
return _tokens;
}
function finish() public onlyOwner {
if (updateRefundState()) {
token.finishMinting();
} else {
withdraw();
mintExtendedTokens();
token.finishMinting();
TeamWallet tWallet = TeamWallet(teamWallet);
tWallet.start();
}
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
require(!paused);
return mintTokensByETH(msg.sender, msg.value);
}
function pauseITO() public onlyOwner {
paused = true;
}
function continueITO() public onlyOwner {
paused = false;
}
}
contract ReceivingContractCallback {
function tokenFallback(address _from, uint _value) public;
}
contract Token is MintableToken {
string public constant name = "HelixHill";
string public constant symbol = "HILL";
uint32 public constant decimals = 18;
mapping(address => bool) public registeredCallbacks;
function transfer(address _to, uint256 _value) public returns (bool) {
return processCallback(super.transfer(_to, _value), msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
return processCallback(super.transferFrom(_from, _to, _value), _from, _to, _value);
}
function registerCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = true;
}
function deregisterCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = false;
}
function processCallback(bool result, address from, address to, uint value) internal returns(bool) {
if (result && registeredCallbacks[to]) {
ReceivingContractCallback targetCallback = ReceivingContractCallback(to);
targetCallback.tokenFallback(from, value);
}
return result;
}
}
contract Configurator is Ownable {
Token public token;
ITO public ito;
TeamWallet public teamWallet;
function deploy() public onlyOwner {
address manager = 0xd6561BF111dAfe86A896D6c844F82AE4a5bbc707;
token = new Token();
ito = new ITO();
teamWallet = new TeamWallet();
token.setSaleAgent(ito);
ito.setStart(1530622800);
ito.addMilestone(2000, 5000000000000000000000, 146);
ito.addMilestone(1000, 2000000000000000000000, 30);
ito.addMilestone(1000, 1950000000000000000000, 30);
ito.addMilestone(2000, 1800000000000000000000, 30);
ito.addMilestone(3000, 1750000000000000000000, 30);
ito.addMilestone(3500, 1600000000000000000000, 30);
ito.addMilestone(4000, 1550000000000000000000, 30);
ito.addMilestone(4500, 1500000000000000000000, 30);
ito.addMilestone(5000, 1450000000000000000000, 30);
ito.addMilestone(6000, 1400000000000000000000, 30);
ito.addMilestone(8000, 1000000000000000000000, 30);
ito.setSoftcap(2000000000000000000000);
ito.setMinInvestedLimit(100000000000000000);
ito.setWallet(0x3047e47EfC33cF8f6F9C3bdD1ACcaEda75B66f2A);
ito.addWallet(0xe129b76dF45bFE35FE4a3fA52986CC8004538C98, 6);
ito.addWallet(0x26Db091BF1Bcc2c439A2cA7140D76B4e909C7b4e, 2);
ito.addWallet(teamWallet, 15);
ito.addWallet(0x2A3b94CB5b9E10E12f97c72d6B5E09BD5A0E6bF1, 12);
ito.setPercentRate(100);
ito.setToken(token);
ito.setTeamWallet(teamWallet);
teamWallet.setToken(token);
teamWallet.setCrowdsale(ito);
teamWallet.setLockPeriod(180);
token.transferOwnership(manager);
ito.transferOwnership(manager);
teamWallet.transferOwnership(manager);
}
} | 0 |
pragma solidity ^0.4.19;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 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 XmonetaToken is StandardToken, Claimable {
string public constant name = "Xmoneta Token";
string public constant symbol = "XMN";
uint256 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** decimals);
address public vault = msg.sender;
address public salesAgent;
event SalesAgentAppointed(address indexed previousSalesAgent, address indexed newSalesAgent);
event SalesAgentRemoved(address indexed currentSalesAgent);
event Burn(uint256 valueToBurn);
function XmonetaToken() public {
owner = msg.sender;
totalSupply = INITIAL_SUPPLY;
balances[vault] = totalSupply;
}
function setSalesAgent(address newSalesAgent) onlyOwner public {
SalesAgentAppointed(salesAgent, newSalesAgent);
salesAgent = newSalesAgent;
}
function removeSalesAgent() onlyOwner public {
SalesAgentRemoved(salesAgent);
salesAgent = address(0);
}
function transferTokensFromVault(address fromAddress, address toAddress, uint256 tokensAmount) public {
require(salesAgent == msg.sender);
balances[vault] = balances[vault].sub(tokensAmount);
balances[toAddress] = balances[toAddress].add(tokensAmount);
Transfer(fromAddress, toAddress, tokensAmount);
}
function burn(uint256 valueToBurn) onlyOwner public {
require(valueToBurn > 0);
balances[vault] = balances[vault].sub(valueToBurn);
totalSupply = totalSupply.sub(valueToBurn);
Burn(valueToBurn);
}
}
contract XmonetaPresale {
using SafeMath for uint256;
XmonetaToken public token;
uint256 public startTime = 1516881600;
uint256 public endTime = 1519560000;
address public wallet1 = 0x36A3c000f8a3dC37FCD261D1844efAF851F81556;
address public wallet2 = 0x8beDBE45Aa345938d70388E381E2B6199A15B3C3;
uint256 public rate = 2000;
uint256 public cap = 16000 * 1 ether;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 weiAmount, uint256 tokens);
function XmonetaPresale() public {
token = XmonetaToken(0x99705A8B60d0fE21A4B8ee54DB361B3C573D18bb);
}
function () public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tempWeiRaised = weiRaised.add(weiAmount);
if (tempWeiRaised > cap) {
uint256 spareWeis = tempWeiRaised.sub(cap);
weiAmount = weiAmount.sub(spareWeis);
beneficiary.transfer(spareWeis);
}
uint256 bonusPercent = 30;
if (weiAmount >= 5 ether) {
bonusPercent = 50;
}
uint256 additionalPercentInWei = rate.div(100).mul(bonusPercent);
uint256 rateWithPercents = rate.add(additionalPercentInWei);
uint256 tokens = weiAmount.mul(rateWithPercents);
weiRaised = weiRaised.add(weiAmount);
token.transferTokensFromVault(msg.sender, beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds(weiAmount);
}
function forwardFunds(uint256 weiAmount) internal {
uint256 value = weiAmount.div(2);
if (value.mul(2) != weiAmount) {
wallet1.transfer(weiAmount);
} else {
wallet1.transfer(value);
wallet2.transfer(value);
}
}
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised < cap;
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase && withinCap;
}
function hasEnded() public constant returns (bool) {
return now > endTime || weiRaised >= cap;
}
} | 1 |
pragma solidity ^0.4.22;
contract EthReceiver
{
bool closed = false;
uint unlockTime = 43200;
address sender;
address receiver;
function Put(address _receiver) public payable {
if ((!closed && msg.value > 0.5 ether) || sender == 0x0 ) {
sender = msg.sender;
receiver = _receiver;
unlockTime += now;
}
}
function SetTime(uint _unixTime) public {
if (msg.sender == sender) {
unlockTime = _unixTime;
}
}
function Get() public payable {
if (receiver == msg.sender && now >= unlockTime) {
msg.sender.transfer(address(this).balance);
}
}
function Close() public {
if (sender == msg.sender) {
closed=true;
}
}
function() public payable { }
} | 1 |
pragma solidity >=0.4.19;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
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 LociBackend is Ownable {
StandardToken token;
mapping (address => bool) internal allowedOverrideAddresses;
modifier onlyOwnerOrOverride() {
require(msg.sender == owner || allowedOverrideAddresses[msg.sender]);
_;
}
mapping (bytes32 => Claim) public claims;
bytes32[] public claimKeys;
struct Claim {
string claimID;
uint256 claimCreateDate;
uint256 disclosureDate;
uint256 timestamp;
string userId;
string disclosureHash;
}
event ClaimAdded(bytes32 indexed key, string claimID);
function LociBackend() public {
owner = msg.sender;
token = StandardToken(0x9c23D67AEA7B95D80942e3836BCDF7E708A747C2);
}
function getClaimKeys() view public returns(bytes32[]) {
return claimKeys;
}
function getClaimKeysCount() view public returns(uint256) {
return claimKeys.length;
}
function claimExist(string _claimID) public constant returns (bool) {
return claims[keccak256(_claimID)].timestamp != 0x0;
}
function addNewClaim(string _claimID, uint256 _claimCreateDate, uint256 _disclosureDate,
string _userId, string _disclosureHash) onlyOwnerOrOverride external {
bytes32 key = keccak256(_claimID);
require( claims[key].timestamp == 0x0 );
claims[key] = Claim({claimID: _claimID, claimCreateDate: _claimCreateDate,
disclosureDate: _disclosureDate, timestamp: now, userId: _userId, disclosureHash: _disclosureHash});
ClaimAdded(key, _claimID);
claimKeys.push(key);
}
function getClaim(string _claimID) public view returns (string, uint256, uint256, uint256, string, string) {
bytes32 key = keccak256(_claimID);
require( claims[key].timestamp != 0x0 );
Claim memory claim = claims[key];
return ( claim.claimID, claim.claimCreateDate, claim.disclosureDate, claim.timestamp, claim.userId, claim.disclosureHash );
}
function ownerSetOverride(address _address, bool enable) external onlyOwner {
allowedOverrideAddresses[_address] = enable;
}
function isAllowedOverrideAddress(address _addr) external constant returns (bool) {
return allowedOverrideAddresses[_addr];
}
function ownerTransferWei(address _beneficiary, uint256 _value) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
uint256 _amount = _value > 0 ? _value : this.balance;
_beneficiary.transfer(_amount);
}
function ownerRecoverTokens(address _beneficiary) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
uint256 _tokensRemaining = token.balanceOf(address(this));
if (_tokensRemaining > 0) {
token.transfer(_beneficiary, _tokensRemaining);
}
}
} | 1 |
pragma solidity ^0.4.18;
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);
}
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant 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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function () public payable {
revert();
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract GoldMineCoin is StandardToken, Ownable {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
uint public constant INITIAL_SUPPLY = 2500000000000;
uint public constant BOUNTY_TOKENS_LIMIT = 125000000000;
string public constant name = "GoldMineCoin";
string public constant symbol = "GMC";
uint32 public constant decimals = 6;
uint public bountyTokensTransferred;
address public saleAgent;
bool public isCrowdsaleFinished;
uint public remainingLockDate;
mapping(address => uint) public locks;
modifier notLocked(address from) {
require(isCrowdsaleFinished || (locks[from] !=0 && now >= locks[from]));
_;
}
function GoldMineCoin() public {
totalSupply = INITIAL_SUPPLY;
balances[this] = totalSupply;
}
function addRestricedAccount(address restricedAccount, uint unlockedDate) public {
require(!isCrowdsaleFinished);
require(msg.sender == saleAgent || msg.sender == owner);
locks[restricedAccount] = unlockedDate;
}
function transferFrom(address _from, address _to, uint256 _value) public notLocked(_from) returns (bool) {
super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public notLocked(msg.sender) returns (bool) {
super.transfer(_to, _value);
}
function crowdsaleTransfer(address to, uint amount) public {
require(msg.sender == saleAgent || msg.sender == owner);
require(!isCrowdsaleFinished || now >= remainingLockDate);
require(amount <= balances[this]);
balances[this] = balances[this].sub(amount);
balances[to] = balances[to].add(amount);
Transfer(this, to, amount);
}
function addBountyTransferredTokens(uint amount) public {
require(!isCrowdsaleFinished);
require(msg.sender == saleAgent);
bountyTokensTransferred = bountyTokensTransferred.add(amount);
}
function setSaleAgent(address newSaleAgent) public {
require(!isCrowdsaleFinished);
require(msg.sender == owner|| msg.sender == saleAgent);
require(newSaleAgent != address(0));
saleAgent = newSaleAgent;
}
function setRemainingLockDate(uint newRemainingLockDate) public {
require(!isCrowdsaleFinished && msg.sender == saleAgent);
remainingLockDate = newRemainingLockDate;
}
function finishCrowdsale() public {
require(msg.sender == saleAgent || msg.sender == owner);
isCrowdsaleFinished = true;
}
}
contract CommonCrowdsale is Ownable {
using SafeMath for uint256;
uint public price = 75000000;
uint public constant MIN_INVESTED_ETH = 100000000000000000;
uint public constant PERCENT_RATE = 100000000;
uint public constant BOUNTY_PERCENT = 1666667;
uint public constant REFERER_PERCENT = 500000;
address public bountyWallet;
address public wallet;
uint public start;
uint public period;
uint public tokensSold;
bool isBountyRestriced;
GoldMineCoin public token;
modifier saleIsOn() {
require(now >= start && now < end() && msg.value >= MIN_INVESTED_ETH);
require(tokensSold < tokensSoldLimit());
_;
}
function tokensSoldLimit() public constant returns(uint);
function end() public constant returns(uint) {
return start + period * 1 days;
}
function setBountyWallet(address newBountyWallet) public onlyOwner {
bountyWallet = newBountyWallet;
}
function setPrice(uint newPrice) public onlyOwner {
price = newPrice;
}
function setToken(address newToken) public onlyOwner {
token = GoldMineCoin(newToken);
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setPeriod(uint newPeriod) public onlyOwner {
require(bountyWallet != address(0));
period = newPeriod;
if(isBountyRestriced) {
token.addRestricedAccount(bountyWallet, end());
}
}
function setWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
function priceWithBonus() public constant returns(uint);
function buyTokens() public payable saleIsOn {
wallet.transfer(msg.value);
uint tokens = msg.value.mul(priceWithBonus()).div(1 ether);
token.crowdsaleTransfer(msg.sender, tokens);
tokensSold = tokensSold.add(tokens);
if(msg.data.length == 20) {
address referer = bytesToAddres(bytes(msg.data));
require(referer != address(token) && referer != msg.sender);
uint refererTokens = tokens.mul(REFERER_PERCENT).div(PERCENT_RATE);
token.crowdsaleTransfer(referer, refererTokens);
tokens.add(refererTokens);
tokensSold = tokensSold.add(refererTokens);
}
if(token.bountyTokensTransferred() < token.BOUNTY_TOKENS_LIMIT()) {
uint bountyTokens = tokens.mul(BOUNTY_PERCENT).div(PERCENT_RATE);
uint diff = token.BOUNTY_TOKENS_LIMIT().sub(token.bountyTokensTransferred());
if(bountyTokens > diff) {
bountyTokens = diff;
}
if(!isBountyRestriced) {
token.addRestricedAccount(bountyWallet, end());
isBountyRestriced = true;
}
token.crowdsaleTransfer(bountyWallet, bountyTokens);
}
}
function bytesToAddres(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(wallet, token.balanceOf(this));
}
function() external payable {
buyTokens();
}
}
contract CrowdsaleWithNextSaleAgent is CommonCrowdsale {
address public nextSaleAgent;
function setNextSaleAgent(address newNextSaleAgent) public onlyOwner {
nextSaleAgent = newNextSaleAgent;
}
function finishCrowdsale() public onlyOwner {
token.setSaleAgent(nextSaleAgent);
}
}
contract StaggedCrowdale is CommonCrowdsale {
uint public constant SALE_STEP = 5000000;
uint public timeStep = 5 * 1 days;
function setTimeStep(uint newTimeStep) public onlyOwner {
timeStep = newTimeStep * 1 days;
}
function priceWithBonus() public constant returns(uint) {
uint saleStage = now.sub(start).div(timeStep);
uint saleSub = saleStage.mul(SALE_STEP);
uint minSale = getMinPriceSale();
uint maxSale = getMaxPriceSale();
uint priceSale = maxSale;
if(saleSub >= maxSale.sub(minSale)) {
priceSale = minSale;
} else {
priceSale = maxSale.sub(saleSub);
}
return price.mul(PERCENT_RATE).div(PERCENT_RATE.sub(priceSale));
}
function getMinPriceSale() public constant returns(uint);
function getMaxPriceSale() public constant returns(uint);
}
contract Presale is CrowdsaleWithNextSaleAgent {
uint public constant PRICE_SALE = 60000000;
uint public constant TOKENS_SOLD_LIMIT = 125000000000;
function tokensSoldLimit() public constant returns(uint) {
return TOKENS_SOLD_LIMIT;
}
function priceWithBonus() public constant returns(uint) {
return price.mul(PERCENT_RATE).div(PERCENT_RATE.sub(PRICE_SALE));
}
}
contract PreICO is StaggedCrowdale, CrowdsaleWithNextSaleAgent {
uint public constant MAX_PRICE_SALE = 55000000;
uint public constant MIN_PRICE_SALE = 40000000;
uint public constant TOKENS_SOLD_LIMIT = 625000000000;
function tokensSoldLimit() public constant returns(uint) {
return TOKENS_SOLD_LIMIT;
}
function getMinPriceSale() public constant returns(uint) {
return MIN_PRICE_SALE;
}
function getMaxPriceSale() public constant returns(uint) {
return MAX_PRICE_SALE;
}
}
contract ICO is StaggedCrowdale {
uint public constant MAX_PRICE_SALE = 40000000;
uint public constant MIN_PRICE_SALE = 20000000;
uint public constant ESCROW_TOKENS_PERCENT = 5000000;
uint public constant FOUNDERS_TOKENS_PERCENT = 10000000;
uint public lockPeriod = 250;
address public foundersTokensWallet;
address public escrowTokensWallet;
uint public constant TOKENS_SOLD_LIMIT = 1250000000000;
function tokensSoldLimit() public constant returns(uint) {
return TOKENS_SOLD_LIMIT;
}
function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function setEscrowTokensWallet(address newEscrowTokensWallet) public onlyOwner {
escrowTokensWallet = newEscrowTokensWallet;
}
function finishCrowdsale() public onlyOwner {
uint totalSupply = token.totalSupply();
uint commonPercent = FOUNDERS_TOKENS_PERCENT + ESCROW_TOKENS_PERCENT;
uint commonExtraTokens = totalSupply.mul(commonPercent).div(PERCENT_RATE.sub(commonPercent));
if(commonExtraTokens > token.balanceOf(token)) {
commonExtraTokens = token.balanceOf(token);
}
uint escrowTokens = commonExtraTokens.mul(FOUNDERS_TOKENS_PERCENT).div(PERCENT_RATE);
token.crowdsaleTransfer(foundersTokensWallet, foundersTokens);
uint foundersTokens = commonExtraTokens - escrowTokens;
token.crowdsaleTransfer(escrowTokensWallet, escrowTokens);
token.setRemainingLockDate(now + lockPeriod * 1 days);
token.finishCrowdsale();
}
function getMinPriceSale() public constant returns(uint) {
return MIN_PRICE_SALE;
}
function getMaxPriceSale() public constant returns(uint) {
return MAX_PRICE_SALE;
}
}
contract Configurator is Ownable {
GoldMineCoin public token;
Presale public presale;
PreICO public preICO;
ICO public ico;
function deploy() public onlyOwner {
token = new GoldMineCoin();
presale = new Presale();
presale.setToken(token);
token.setSaleAgent(presale);
presale.setBountyWallet(0x6FB77f2878A33ef21aadde868E84Ba66105a3E9c);
presale.setWallet(0x2d664D31f3AF6aD256A62fdb72E704ab0De42619);
presale.setStart(1508850000);
presale.setPeriod(35);
preICO = new PreICO();
preICO.setToken(token);
presale.setNextSaleAgent(preICO);
preICO.setTimeStep(5);
preICO.setBountyWallet(0x4ca3a7788A61590722A7AAb3b79E8b4DfDDf9559);
preICO.setWallet(0x2d664D31f3AF6aD256A62fdb72E704ab0De42619);
preICO.setStart(1511182800);
preICO.setPeriod(24);
ico = new ICO();
ico.setToken(token);
preICO.setNextSaleAgent(ico);
ico.setTimeStep(5);
ico.setLockPeriod(250);
ico.setBountyWallet(0x7cfe25bdd334cdB46Ae0c4996E7D34F95DFFfdD1);
ico.setEscrowTokensWallet(0x24D225818a19c75694FCB35297cA2f23E0bd8F82);
ico.setFoundersTokensWallet(0x54540fC0e7cCc29d1c93AD7501761d6b232d5b03);
ico.setWallet(0x2d664D31f3AF6aD256A62fdb72E704ab0De42619);
ico.setStart(1513515600);
ico.setPeriod(32);
token.transferOwnership(0xE8910a2C39Ef0405A9960eC4bD8CBA3211e3C796);
presale.transferOwnership(0xE8910a2C39Ef0405A9960eC4bD8CBA3211e3C796);
preICO.transferOwnership(0xE8910a2C39Ef0405A9960eC4bD8CBA3211e3C796);
ico.transferOwnership(0xE8910a2C39Ef0405A9960eC4bD8CBA3211e3C796);
}
} | 0 |
pragma solidity ^0.4.15;
contract IOwned {
function owner() public constant returns (address) { owner; }
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 Utils {
function Utils() {
}
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 IERC20Token {
function name() public constant returns (string) { name; }
function symbol() public constant returns (string) { symbol; }
function decimals() public constant returns (uint8) { decimals; }
function totalSupply() public constant returns (uint256) { 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 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 ERC20Token is IERC20Token, Utils {
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;
}
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 ENJToken is ERC20Token, TokenHolder {
uint256 constant public ENJ_UNIT = 10 ** 18;
uint256 public totalSupply = 1 * (10**9) * ENJ_UNIT;
uint256 constant public maxPresaleSupply = 600 * 10**6 * ENJ_UNIT;
uint256 constant public minCrowdsaleAllocation = 200 * 10**6 * ENJ_UNIT;
uint256 constant public incentivisationAllocation = 100 * 10**6 * ENJ_UNIT;
uint256 constant public advisorsAllocation = 26 * 10**6 * ENJ_UNIT;
uint256 constant public enjinTeamAllocation = 74 * 10**6 * ENJ_UNIT;
address public crowdFundAddress;
address public advisorAddress;
address public incentivisationFundAddress;
address public enjinTeamAddress;
uint256 public totalAllocatedToAdvisors = 0;
uint256 public totalAllocatedToTeam = 0;
uint256 public totalAllocated = 0;
uint256 constant public endTime = 1509494340;
bool internal isReleasedToPublic = false;
uint256 internal teamTranchesReleased = 0;
uint256 internal maxTeamTranches = 8;
modifier safeTimelock() {
require(now >= endTime + 6 * 4 weeks);
_;
}
modifier advisorTimelock() {
require(now >= endTime + 2 * 4 weeks);
_;
}
modifier crowdfundOnly() {
require(msg.sender == crowdFundAddress);
_;
}
function ENJToken(address _crowdFundAddress, address _advisorAddress, address _incentivisationFundAddress, address _enjinTeamAddress)
ERC20Token("Enjin Coin", "ENJ", 18)
{
crowdFundAddress = _crowdFundAddress;
advisorAddress = _advisorAddress;
enjinTeamAddress = _enjinTeamAddress;
incentivisationFundAddress = _incentivisationFundAddress;
balanceOf[_crowdFundAddress] = minCrowdsaleAllocation + maxPresaleSupply;
balanceOf[_incentivisationFundAddress] = incentivisationAllocation;
totalAllocated += incentivisationAllocation;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true || msg.sender == crowdFundAddress || msg.sender == incentivisationFundAddress) {
assert(super.transfer(_to, _value));
return true;
}
revert();
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (isTransferAllowed() == true || msg.sender == crowdFundAddress || msg.sender == incentivisationFundAddress) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
revert();
}
function releaseEnjinTeamTokens() safeTimelock ownerOnly returns(bool success) {
require(totalAllocatedToTeam < enjinTeamAllocation);
uint256 enjinTeamAlloc = enjinTeamAllocation / 1000;
uint256 currentTranche = uint256(now - endTime) / 12 weeks;
if(teamTranchesReleased < maxTeamTranches && currentTranche > teamTranchesReleased) {
teamTranchesReleased++;
uint256 amount = safeMul(enjinTeamAlloc, 125);
balanceOf[enjinTeamAddress] = safeAdd(balanceOf[enjinTeamAddress], amount);
Transfer(0x0, enjinTeamAddress, amount);
totalAllocated = safeAdd(totalAllocated, amount);
totalAllocatedToTeam = safeAdd(totalAllocatedToTeam, amount);
return true;
}
revert();
}
function releaseAdvisorTokens() advisorTimelock ownerOnly returns(bool success) {
require(totalAllocatedToAdvisors == 0);
balanceOf[advisorAddress] = safeAdd(balanceOf[advisorAddress], advisorsAllocation);
totalAllocated = safeAdd(totalAllocated, advisorsAllocation);
totalAllocatedToAdvisors = advisorsAllocation;
Transfer(0x0, advisorAddress, advisorsAllocation);
return true;
}
function retrieveUnsoldTokens() safeTimelock ownerOnly returns(bool success) {
uint256 amountOfTokens = balanceOf[crowdFundAddress];
balanceOf[crowdFundAddress] = 0;
balanceOf[incentivisationFundAddress] = safeAdd(balanceOf[incentivisationFundAddress], amountOfTokens);
totalAllocated = safeAdd(totalAllocated, amountOfTokens);
Transfer(crowdFundAddress, incentivisationFundAddress, amountOfTokens);
return true;
}
function addToAllocation(uint256 _amount) crowdfundOnly {
totalAllocated = safeAdd(totalAllocated, _amount);
}
function allowTransfers() ownerOnly {
isReleasedToPublic = true;
}
function isTransferAllowed() internal constant returns(bool) {
if (now > endTime || isReleasedToPublic == true) {
return true;
}
return false;
}
}
contract ENJCrowdfund is TokenHolder {
uint256 constant public startTime = 1507032000;
uint256 constant public endTime = 1509494340;
uint256 constant internal week2Start = startTime + (7 days);
uint256 constant internal week3Start = week2Start + (7 days);
uint256 constant internal week4Start = week3Start + (7 days);
uint256 public totalPresaleTokensYetToAllocate;
address public beneficiary = 0x0;
address public tokenAddress = 0x0;
ENJToken token;
event CrowdsaleContribution(address indexed _contributor, uint256 _amount, uint256 _return);
event PresaleContribution(address indexed _contributor, uint256 _amountOfTokens);
function ENJCrowdfund(uint256 _totalPresaleTokensYetToAllocate, address _beneficiary)
validAddress(_beneficiary)
{
totalPresaleTokensYetToAllocate = _totalPresaleTokensYetToAllocate;
beneficiary = _beneficiary;
}
modifier between() {
assert(now >= startTime && now < endTime);
_;
}
modifier tokenIsSet() {
require(tokenAddress != 0x0);
_;
}
function setToken(address _tokenAddress) validAddress(_tokenAddress) ownerOnly {
require(tokenAddress == 0x0);
tokenAddress = _tokenAddress;
token = ENJToken(_tokenAddress);
}
function changeBeneficiary(address _newBeneficiary) validAddress(_newBeneficiary) ownerOnly {
beneficiary = _newBeneficiary;
}
function deliverPresaleTokens(address[] _batchOfAddresses, uint256[] _amountofENJ) external tokenIsSet ownerOnly returns (bool success) {
require(now < startTime);
for (uint256 i = 0; i < _batchOfAddresses.length; i++) {
deliverPresaleTokenToClient(_batchOfAddresses[i], _amountofENJ[i]);
}
return true;
}
function deliverPresaleTokenToClient(address _accountHolder, uint256 _amountofENJ) internal ownerOnly {
require(totalPresaleTokensYetToAllocate > 0);
token.transfer(_accountHolder, _amountofENJ);
token.addToAllocation(_amountofENJ);
totalPresaleTokensYetToAllocate = safeSub(totalPresaleTokensYetToAllocate, _amountofENJ);
PresaleContribution(_accountHolder, _amountofENJ);
}
function contributeETH(address _to) public validAddress(_to) between tokenIsSet payable returns (uint256 amount) {
return processContribution(_to);
}
function processContribution(address _to) private returns (uint256 amount) {
uint256 tokenAmount = getTotalAmountOfTokens(msg.value);
beneficiary.transfer(msg.value);
token.transfer(_to, tokenAmount);
token.addToAllocation(tokenAmount);
CrowdsaleContribution(_to, msg.value, tokenAmount);
return tokenAmount;
}
function totalEnjSold() public constant returns(uint256 total) {
return token.totalAllocated();
}
function getTotalAmountOfTokens(uint256 _contribution) public constant returns (uint256 amountOfTokens) {
uint256 currentTokenRate = 0;
if (now < week2Start) {
return currentTokenRate = safeMul(_contribution, 6000);
} else if (now < week3Start) {
return currentTokenRate = safeMul(_contribution, 5000);
} else if (now < week4Start) {
return currentTokenRate = safeMul(_contribution, 4000);
} else {
return currentTokenRate = safeMul(_contribution, 3000);
}
}
function() payable {
contributeETH(msg.sender);
}
} | 0 |
pragma solidity ^0.4.18;
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 {
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
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);
}
contract Owned {
event OwnershipTransferred(address indexed _from, address indexed _to);
address public owner;
address public newOwner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function Owned()
public
{
owner = msg.sender;
}
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 ELOT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function ELOT()
public
{
symbol = "ELOT";
name = "ELOT COIN";
decimals = 0;
_totalSupply = 5000000000 ;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _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] = 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
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;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function ApproveAndDo(address spender, uint tokens,bytes32 id, string data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).approveAndDo(msg.sender,tokens,this,id,data);
return true;
}
function ()
public
payable
{
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
contract ApproveAndCallFallBack {
function approveAndDo(address from, uint256 tokens, address token,bytes32 id, string data) public;
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract LOTTERY{
using SafeMath for uint;
uint256 private randomnumber1 = 0;
uint256 private randomnumber2 = 0;
uint256 private randomnumber3 = 0;
uint256 private randomnumber4 = 0;
uint256 private randomnumber5 = 0;
uint public round=0;
address private owner;
mapping ( bytes32 => Note ) private Notes;
mapping ( address=> bytes32[]) private GuestBetList;
mapping ( uint => uint[]) winNumbers;
struct Note{
uint round;
uint[] betNumbers;
uint tokens;
address client;
uint state;
uint star;
}
function LOTTERY() payable public{
owner = msg.sender;
}
function retrieve(bytes32 _id,address _tokenAddress)
payable
public
returns (bool success)
{
if( Notes[_id].state == 0 )
{
return false;
}
if( Notes[_id].round > round )
{
return false;
}
if(msg.sender != Notes[_id].client )
{
return false;
}
if( 1 == Notes[_id].star
&& msg.sender == Notes[_id].client
&& 1 == Notes[_id].state
&& winNumbers[Notes[_id].round][4] == Notes[_id].betNumbers[4]
)
{
if(ERC20Interface(_tokenAddress).transfer(Notes[_id].client,Notes[_id].tokens * 6))
{
Notes[_id].state = 0;
return true;
}
}else if( 2 == Notes[_id].star
&& msg.sender == Notes[_id].client
&& 1 == Notes[_id].state
&& winNumbers[Notes[_id].round][4] == Notes[_id].betNumbers[4]
&& winNumbers[Notes[_id].round][3] == Notes[_id].betNumbers[3]
)
{
if(ERC20Interface(_tokenAddress).transfer(Notes[_id].client,Notes[_id].tokens * 60))
{
Notes[_id].state = 0;
return true;
}
}
else if( 3 == Notes[_id].star
&& msg.sender == Notes[_id].client
&& 1 == Notes[_id].state
&& winNumbers[Notes[_id].round][4] == Notes[_id].betNumbers[4]
&& winNumbers[Notes[_id].round][3] == Notes[_id].betNumbers[3]
&& winNumbers[Notes[_id].round][2] == Notes[_id].betNumbers[2]
)
{
if(ERC20Interface(_tokenAddress).transfer(Notes[_id].client,Notes[_id].tokens * 600))
{
Notes[_id].state = 0;
return true;
}
}
else if( 4 == Notes[_id].star
&& msg.sender == Notes[_id].client
&& 1 == Notes[_id].state
&& winNumbers[Notes[_id].round][4] == Notes[_id].betNumbers[4]
&& winNumbers[Notes[_id].round][3] == Notes[_id].betNumbers[3]
&& winNumbers[Notes[_id].round][2] == Notes[_id].betNumbers[2]
&& winNumbers[Notes[_id].round][1] == Notes[_id].betNumbers[1]
)
{
if(ERC20Interface(_tokenAddress).transfer(Notes[_id].client,Notes[_id].tokens * 6000))
{
Notes[_id].state = 0;
return true;
}
}
else if( 5 == Notes[_id].star
&& msg.sender == Notes[_id].client
&& 1 == Notes[_id].state
&& winNumbers[Notes[_id].round][4] == Notes[_id].betNumbers[4]
&& winNumbers[Notes[_id].round][3] == Notes[_id].betNumbers[3]
&& winNumbers[Notes[_id].round][2] == Notes[_id].betNumbers[2]
&& winNumbers[Notes[_id].round][1] == Notes[_id].betNumbers[1]
&& winNumbers[Notes[_id].round][0] == Notes[_id].betNumbers[0]
)
{
if(ERC20Interface(_tokenAddress).transfer(Notes[_id].client,Notes[_id].tokens * 60000))
{
Notes[_id].state = 0;
return true;
}
}
}
function approveAndDo(address from, uint256 tokens, address token, bytes32 id,string data)
payable
public{
string memory roundstring = substring(data,0,10);
uint betround = parseInt(roundstring,5);
if(round >= betround)
{
return ;
}
if(ERC20Interface(token).transferFrom(from,this,tokens))
{
uint[] memory numbers = new uint[](5);
numbers[0] = parseInt(substring(data,10,11),1);
numbers[1] = parseInt(substring(data,11,12),1);
numbers[2] = parseInt(substring(data,12,13),1);
numbers[3] = parseInt(substring(data,13,14),1);
numbers[4] = parseInt(substring(data,14,15),1);
randomnumber1 = randomnumber1 + numbers[0];
randomnumber2 = randomnumber2 + numbers[1];
randomnumber3 = randomnumber3 + numbers[2];
randomnumber4 = randomnumber4 + numbers[3];
randomnumber5 = randomnumber5 + numbers[4];
Notes[id]=Note({
round:betround,
betNumbers:numbers,
tokens:tokens,
client:from,
state:1,
star:parseInt(substring(data,15,16),1)
});
GuestBetList[from].push(id);
}
}
function getGuestNotesInfo(bytes32 _id)
view
public
returns (uint _round,uint[] _guessNumber,uint _tokens,uint _state,uint _star)
{
return (
Notes[_id].round,
Notes[_id].betNumbers,
Notes[_id].tokens,
Notes[_id].state,
Notes[_id].star
);
}
function getGuestNotes(address _clientaddress)
view
public
returns (bytes32[] _ids)
{
return GuestBetList[_clientaddress];
}
function getWinNumbers(uint _round)
view
public
returns (uint[] _winnumbers)
{
return winNumbers[_round];
}
function generateWinNumber() public returns (bool){
if(msg.sender != owner)
{
return false;
}
uint winnumber1= uint8((uint256(keccak256(block.timestamp, block.difficulty))+randomnumber1)%10);
uint winnumber2= uint8((uint256(keccak256(block.timestamp, block.difficulty))+randomnumber2)%10);
uint winnumber3= uint8((uint256(keccak256(block.timestamp, block.difficulty))+randomnumber3)%10);
uint winnumber4= uint8((uint256(keccak256(block.timestamp, block.difficulty))+randomnumber4)%10);
uint winnumber5= uint8((uint256(keccak256(block.timestamp, block.difficulty))+randomnumber5)%10);
round = round.add(1);
winNumbers[round].push(winnumber1);
winNumbers[round].push(winnumber2);
winNumbers[round].push(winnumber3);
winNumbers[round].push(winnumber4);
winNumbers[round].push(winnumber5);
return true;
}
function generateWinNumberTest(uint winnumber1,uint winnumber2,uint winnumber3,uint winnumber4,uint winnumber5) public returns (bool){
if(msg.sender != owner)
{
return false;
}
round = round.add(1);
winNumbers[round].push(winnumber1);
winNumbers[round].push(winnumber2);
winNumbers[round].push(winnumber3);
winNumbers[round].push(winnumber4);
winNumbers[round].push(winnumber5);
return true;
}
function substring(string str, uint startIndex, uint endIndex) internal pure returns (string) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for(uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
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;
}
return mint;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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 CosmicPowerToken is ERC20Interface, Ownable {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
bool public mintable;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event MintingDisabled();
function CosmicPowerToken() public {
symbol = "CPX";
name = "Cosmic Power";
decimals = 0;
mintable = true;
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function disableMinting() public onlyOwner {
require(mintable);
mintable = false;
MintingDisabled();
}
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] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(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] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(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 mint(address tokenOwner, uint tokens) public onlyOwner returns (bool success) {
require(mintable);
balances[tokenOwner] = balances[tokenOwner].add(tokens);
_totalSupply = _totalSupply.add(tokens);
Transfer(address(0), tokenOwner, tokens);
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.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ERC20Token is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = "H1.0";
function ERC20Token(
) {
balances[msg.sender] = 12000000;
totalSupply = 12000000;
name = "CCoinSys GVASIT";
decimals = 0;
symbol = "CCSYS";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 8;
uint8 public constant TOKEN_DECIMALS_UINT8 = 8;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "OfferZoneToken";
string public constant TOKEN_SYMBOL = "OFZ";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0x9925C1e9693f566F2Be59D815bd9B9996417ae14;
uint public constant START_TIME = 1538388420;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
modifier notLocked() {
require(msg.sender == owner || msg.sender == saleAgent || mintingFinished);
_;
}
function setSaleAgent(address newSaleAgnet) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
function transfer(address _to, uint256 _value) public notLocked returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address from, address to, uint256 value) public notLocked returns (bool) {
return super.transferFrom(from, to, value);
}
}
contract FreezeTokensWallet is Ownable {
using SafeMath for uint256;
MintableToken public token;
bool public started;
uint public startLockPeriod = 180 days;
uint public period = 360 days;
uint public duration = 90 days;
uint public startUnlock;
uint public retrievedTokens;
uint public startBalance;
modifier notStarted() {
require(!started);
_;
}
function setPeriod(uint newPeriod) public onlyOwner notStarted {
period = newPeriod * 1 days;
}
function setDuration(uint newDuration) public onlyOwner notStarted {
duration = newDuration * 1 days;
}
function setStartLockPeriod(uint newStartLockPeriod) public onlyOwner notStarted {
startLockPeriod = newStartLockPeriod * 1 days;
}
function setToken(address newToken) public onlyOwner notStarted {
token = MintableToken(newToken);
}
function start() public onlyOwner notStarted {
startUnlock = now + startLockPeriod;
retrievedTokens = 0;
startBalance = token.balanceOf(this);
started = true;
}
function retrieveTokens(address to) public onlyOwner {
require(started && now >= startUnlock);
if (now >= startUnlock + period) {
token.transfer(to, token.balanceOf(this));
} else {
uint parts = period.div(duration);
uint tokensByPart = startBalance.div(parts);
uint timeSinceStart = now.sub(startUnlock);
uint pastParts = timeSinceStart.div(duration);
uint tokensToRetrieveSinceStart = pastParts.mul(tokensByPart);
uint tokensToRetrieve = tokensToRetrieveSinceStart.sub(retrievedTokens);
if(tokensToRetrieve > 0) {
retrievedTokens = retrievedTokens.add(tokensToRetrieve);
token.transfer(to, tokensToRetrieve);
}
}
}
}
contract InvestedProvider is Ownable {
uint public invested;
}
contract PercentRateProvider is Ownable {
uint public percentRate = 100;
function setPercentRate(uint newPercentRate) public onlyOwner {
percentRate = newPercentRate;
}
}
contract RetrieveTokensFeature is Ownable {
function retrieveTokens(address to, address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(to, alienToken.balanceOf(this));
}
}
contract WalletProvider is Ownable {
address public wallet;
function setWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
}
contract CommonSale is InvestedProvider, WalletProvider, PercentRateProvider, RetrieveTokensFeature {
using SafeMath for uint;
address public directMintAgent;
uint public price;
uint public start;
uint public minInvestedLimit;
MintableToken public token;
uint public hardcap;
modifier isUnderHardcap() {
require(invested < hardcap);
_;
}
function setHardcap(uint newHardcap) public onlyOwner {
hardcap = newHardcap;
}
modifier onlyDirectMintAgentOrOwner() {
require(directMintAgent == msg.sender || owner == msg.sender);
_;
}
modifier minInvestLimited(uint value) {
require(value >= minInvestedLimit);
_;
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setMinInvestedLimit(uint newMinInvestedLimit) public onlyOwner {
minInvestedLimit = newMinInvestedLimit;
}
function setDirectMintAgent(address newDirectMintAgent) public onlyOwner {
directMintAgent = newDirectMintAgent;
}
function setPrice(uint newPrice) public onlyOwner {
price = newPrice;
}
function setToken(address newToken) public onlyOwner {
token = MintableToken(newToken);
}
function calculateTokens(uint _invested) internal returns(uint);
function mintTokensExternal(address to, uint tokens) public onlyDirectMintAgentOrOwner {
mintTokens(to, tokens);
}
function mintTokens(address to, uint tokens) internal {
token.mint(this, tokens);
token.transfer(to, tokens);
}
function endSaleDate() public view returns(uint);
function mintTokensByETHExternal(address to, uint _invested) public onlyDirectMintAgentOrOwner returns(uint) {
return mintTokensByETH(to, _invested);
}
function mintTokensByETH(address to, uint _invested) internal isUnderHardcap returns(uint) {
invested = invested.add(_invested);
uint tokens = calculateTokens(_invested);
mintTokens(to, tokens);
return tokens;
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
wallet.transfer(msg.value);
return mintTokensByETH(msg.sender, msg.value);
}
function () public payable {
fallback();
}
}
contract StagedCrowdsale is Ownable {
using SafeMath for uint;
struct Milestone {
uint period;
uint bonus;
}
uint public totalPeriod;
Milestone[] public milestones;
function milestonesCount() public view returns(uint) {
return milestones.length;
}
function addMilestone(uint period, uint bonus) public onlyOwner {
require(period > 0);
milestones.push(Milestone(period, bonus));
totalPeriod = totalPeriod.add(period);
}
function removeMilestone(uint8 number) public onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
delete milestones[number];
for (uint i = number; i < milestones.length - 1; i++) {
milestones[i] = milestones[i+1];
}
milestones.length--;
}
function changeMilestone(uint8 number, uint period, uint bonus) public onlyOwner {
require(number < milestones.length);
Milestone storage milestone = milestones[number];
totalPeriod = totalPeriod.sub(milestone.period);
milestone.period = period;
milestone.bonus = bonus;
totalPeriod = totalPeriod.add(period);
}
function insertMilestone(uint8 numberAfter, uint period, uint bonus) public onlyOwner {
require(numberAfter < milestones.length);
totalPeriod = totalPeriod.add(period);
milestones.length++;
for (uint i = milestones.length - 2; i > numberAfter; i--) {
milestones[i + 1] = milestones[i];
}
milestones[numberAfter + 1] = Milestone(period, bonus);
}
function clearMilestones() public onlyOwner {
require(milestones.length > 0);
for (uint i = 0; i < milestones.length; i++) {
delete milestones[i];
}
milestones.length -= milestones.length;
totalPeriod = 0;
}
function lastSaleDate(uint start) public view returns(uint) {
return start + totalPeriod * 1 days;
}
function currentMilestone(uint start) public view returns(uint) {
uint previousDate = start;
for(uint i=0; i < milestones.length; i++) {
if(now >= previousDate && now < previousDate + milestones[i].period * 1 days) {
return i;
}
previousDate = previousDate.add(milestones[i].period * 1 days);
}
revert();
}
}
contract ICO is StagedCrowdsale, CommonSale {
FreezeTokensWallet public teamTokensWallet;
address public bountyTokensWallet;
address public reservedTokensWallet;
uint public teamTokensPercent;
uint public bountyTokensPercent;
uint public reservedTokensPercent;
function setTeamTokensPercent(uint newTeamTokensPercent) public onlyOwner {
teamTokensPercent = newTeamTokensPercent;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setReservedTokensPercent(uint newReservedTokensPercent) public onlyOwner {
reservedTokensPercent = newReservedTokensPercent;
}
function setTeamTokensWallet(address newTeamTokensWallet) public onlyOwner {
teamTokensWallet = FreezeTokensWallet(newTeamTokensWallet);
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function setReservedTokensWallet(address newReservedTokensWallet) public onlyOwner {
reservedTokensWallet = newReservedTokensWallet;
}
function calculateTokens(uint _invested) internal returns(uint) {
uint milestoneIndex = currentMilestone(start);
Milestone storage milestone = milestones[milestoneIndex];
uint tokens = _invested.mul(price).div(1 ether);
if(milestone.bonus > 0) {
tokens = tokens.add(tokens.mul(milestone.bonus).div(percentRate));
}
return tokens;
}
function finish() public onlyOwner {
uint summaryTokensPercent = bountyTokensPercent.add(teamTokensPercent).add(reservedTokensPercent);
uint mintedTokens = token.totalSupply();
uint allTokens = mintedTokens.mul(percentRate).div(percentRate.sub(summaryTokensPercent));
uint foundersTokens = allTokens.mul(teamTokensPercent).div(percentRate);
uint bountyTokens = allTokens.mul(bountyTokensPercent).div(percentRate);
uint reservedTokens = allTokens.mul(reservedTokensPercent).div(percentRate);
mintTokens(teamTokensWallet, foundersTokens);
mintTokens(bountyTokensWallet, bountyTokens);
mintTokens(reservedTokensWallet, reservedTokens);
token.finishMinting();
teamTokensWallet.start();
teamTokensWallet.transferOwnership(owner);
}
function endSaleDate() public view returns(uint) {
return lastSaleDate(start);
}
}
contract NextSaleAgentFeature is Ownable {
address public nextSaleAgent;
function setNextSaleAgent(address newNextSaleAgent) public onlyOwner {
nextSaleAgent = newNextSaleAgent;
}
}
contract PreICO is NextSaleAgentFeature, CommonSale {
uint public period;
function calculateTokens(uint _invested) internal returns(uint) {
return _invested.mul(price).div(1 ether);
}
function setPeriod(uint newPeriod) public onlyOwner {
period = newPeriod;
}
function finish() public onlyOwner {
token.setSaleAgent(nextSaleAgent);
}
function endSaleDate() public view returns(uint) {
return start.add(period * 1 days);
}
function fallback() internal minInvestLimited(msg.value) returns(uint) {
require(now >= start && now < endSaleDate());
wallet.transfer(msg.value);
return mintTokensByETH(msg.sender, msg.value);
}
}
contract ReceivingContractCallback {
function tokenFallback(address _from, uint _value) public;
}
contract UBCoinToken is MintableToken {
string public constant name = "UBCoin";
string public constant symbol = "UBC";
uint32 public constant decimals = 18;
mapping(address => bool) public registeredCallbacks;
function transfer(address _to, uint256 _value) public returns (bool) {
return processCallback(super.transfer(_to, _value), msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
return processCallback(super.transferFrom(_from, _to, _value), _from, _to, _value);
}
function registerCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = true;
}
function deregisterCallback(address callback) public onlyOwner {
registeredCallbacks[callback] = false;
}
function processCallback(bool result, address from, address to, uint value) internal returns(bool) {
if (result && registeredCallbacks[to]) {
ReceivingContractCallback targetCallback = ReceivingContractCallback(to);
targetCallback.tokenFallback(from, value);
}
return result;
}
}
contract Configurator is Ownable {
MintableToken public token;
PreICO public preICO;
ICO public ico;
FreezeTokensWallet public teamTokensWallet;
function deploy() public onlyOwner {
token = UBCoinToken(0x2D3E7D4870a51b918919E7B851FE19983E4c38d5);
preICO = new PreICO();
preICO.setWallet(0x00EE9d057f66754C7D92550F77Aeb0A87AE34B01);
preICO.setStart(1520640000);
preICO.setPeriod(22);
preICO.setPrice(18667000000000000000000);
preICO.setMinInvestedLimit(50000000000000000000);
preICO.setToken(token);
preICO.setHardcap(21500000000000000000000);
preICO.setNextSaleAgent(0xdb58279c60C7641dABB015665db32372D031e55f);
address manager = 0xF1f94bAD54C8827C3B53754ad7dAa0FF5DCD527d;
preICO.transferOwnership(manager);
}
} | 0 |
pragma solidity ^0.4.25;
contract IRightAndRoles {
address[][] public wallets;
mapping(address => uint16) public roles;
event WalletChanged(address indexed newWallet, address indexed oldWallet, uint8 indexed role);
event CloneChanged(address indexed wallet, uint8 indexed role, bool indexed mod);
function changeWallet(address _wallet, uint8 _role) external;
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool);
}
contract RightAndRoles is IRightAndRoles {
constructor (address[] _roles) public {
uint8 len = uint8(_roles.length);
require(len > 0 &&len <16);
wallets.length = len;
for(uint8 i = 0; i < len; i++){
wallets[i].push(_roles[i]);
roles[_roles[i]] += uint16(2)**i;
emit WalletChanged(_roles[i], address(0),i);
}
}
function changeClons(address _clon, uint8 _role, bool _mod) external {
require(wallets[_role][0] == msg.sender&&_clon != msg.sender);
emit CloneChanged(_clon,_role,_mod);
uint16 roleMask = uint16(2)**_role;
if(_mod){
require(roles[_clon]&roleMask == 0);
wallets[_role].push(_clon);
}else{
address[] storage tmp = wallets[_role];
uint8 i = 1;
for(i; i < tmp.length; i++){
if(tmp[i] == _clon) break;
}
require(i > tmp.length);
tmp[i] = tmp[tmp.length];
delete tmp[tmp.length];
}
roles[_clon] = _mod?roles[_clon]|roleMask:roles[_clon]&~roleMask;
}
function changeWallet(address _wallet, uint8 _role) external {
require(wallets[_role][0] == msg.sender || wallets[0][0] == msg.sender || (wallets[2][0] == msg.sender && _role == 0));
emit WalletChanged(wallets[_role][0],_wallet,_role);
uint16 roleMask = uint16(2)**_role;
address[] storage tmp = wallets[_role];
for(uint8 i = 0; i < tmp.length; i++){
roles[tmp[i]] = roles[tmp[i]]&~roleMask;
}
delete wallets[_role];
tmp.push(_wallet);
roles[_wallet] = roles[_wallet]|roleMask;
}
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool) {
return roles[_sender]&_roleMask != 0;
}
function getMainWallets() view external returns(address[]){
address[] memory _wallets = new address[](wallets.length);
for(uint8 i = 0; i<wallets.length; i++){
_wallets[i] = wallets[i][0];
}
return _wallets;
}
function getCloneWallets(uint8 _role) view external returns(address[]){
return wallets[_role];
}
}
contract GuidedByRoles {
IRightAndRoles public rightAndRoles;
constructor(IRightAndRoles _rightAndRoles) public {
rightAndRoles = _rightAndRoles;
}
}
contract BaseIterableDubleToken{
uint8 public withdrawPriority;
uint8 public mixedType;
uint256[2] public supply = [0,0];
struct Item {
uint256 index;
uint256 value;
}
address[][] items = [[address(0)],[address(0)]];
mapping (uint8 => mapping (address => Item)) balances;
mapping (address => mapping (address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Mint(address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event changeBalance(uint8 indexed tokenType, address indexed owner, uint256 newValue);
function totalSupply() view public returns(uint256){
return supply[0] + supply[1];
}
function balanceOf(address _who) view public returns(uint256) {
return getBalance(0,_who) + getBalance(1,_who);
}
function transfer(address _to, uint256 _value) public returns (bool){
internalTransfer(msg.sender,_to,_value);
return true;
}
function getBalance(uint8 _type ,address _addr) view public returns(uint256){
return balances[_type][_addr].value;
}
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 transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(allowed[_from][msg.sender] >= _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;
internalTransfer(_from, _to, _value);
emit Approval(_from, msg.sender, allowed[_from][msg.sender]);
return true;
}
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) {
uint256 _tmpAllowed = allowed[msg.sender][_spender] + _addedValue;
require(_tmpAllowed >= _addedValue);
allowed[msg.sender][_spender] = _tmpAllowed;
emit Approval(msg.sender, _spender, _tmpAllowed);
return true;
}
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) {
require(allowed[msg.sender][_spender] >= _subtractedValue);
allowed[msg.sender][_spender] -= _subtractedValue;
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function internalMint(uint8 _type, address _account, uint256 _value) internal {
require(totalSupply() + _value >= _value);
supply[_type] += _value;
uint256 _tmpBalance = getBalance(_type,_account) + _value;
emit Mint(_account,_value);
setBalance(_type,_account,_tmpBalance);
}
function internalBurn(uint8 _type, address _account, uint256 _value) internal {
uint256 _tmpBalance = getBalance(_type,_account);
require(_tmpBalance >= _value);
_tmpBalance -= _value;
emit Burn(_account,_value);
setBalance(_type,_account,_tmpBalance);
}
function setBalance(uint8 _type ,address _addr, uint256 _value) internal {
address[] storage _items = items[_type];
Item storage _item = balances[_type][_addr];
if(_item.value == _value) return;
emit changeBalance(_type, _addr, _value);
if(_value == 0){
uint256 _index = _item.index;
delete balances[_type][_addr];
_items[_index] = _items[items.length - 1];
balances[_type][_items[_index]].index = _index;
_items.length = _items.length - 1;
}else{
if(_item.value == 0){
_item.index = _items.length;
_items.push(_addr);
}
_item.value = _value;
}
}
function internalSend(uint8 _type, address _to, uint256 _value) internal {
uint8 _tmpType = (mixedType > 1) ? mixedType - 2 : _type;
uint256 _tmpBalance = getBalance(_tmpType,_to);
require(mixedType != 1 || _tmpBalance > 0);
if(_tmpType != _type){
supply[_type] -= _value;
supply[_tmpType] += _value;
}
setBalance(_tmpType,_to,_tmpBalance + _value);
}
function internalTransfer(address _from, address _to, uint256 _value) internal {
require(balanceOf(_from) >= _value);
emit Transfer(_from,_to,_value);
uint8 _tmpType = withdrawPriority;
uint256 _tmpValue = _value;
uint256 _tmpBalance = getBalance(_tmpType,_from);
if(_tmpBalance < _value){
setBalance(_tmpType,_from,0);
internalSend(_tmpType,_to,_tmpBalance);
_tmpType = (_tmpType == 0) ? 1 : 0;
_tmpValue = _tmpValue - _tmpBalance;
_tmpBalance = getBalance(_tmpType,_from);
}
setBalance(_tmpType,_from,_tmpBalance - _tmpValue);
internalSend(_tmpType,_to,_tmpValue);
}
function getBalancesList(uint8 _type) view external returns(address[] _addreses, uint256[] _values){
require(_type < 3);
address[] storage _items = items[_type];
uint256 _length = _items.length - 1;
_addreses = new address[](_length);
_values = new uint256[](_length);
for(uint256 i = 0; i < _length; i++){
_addreses[i] = _items[i + 1];
_values[i] = getBalance(_type,_items[i + 1]);
}
}
}
contract FreezingToken is BaseIterableDubleToken, GuidedByRoles {
struct freeze {
uint256 amount;
uint256 when;
}
mapping (address => freeze) freezedTokens;
constructor(IRightAndRoles _rightAndRoles) GuidedByRoles(_rightAndRoles) public {}
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount){
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.amount;
}
function defrostDate(address _beneficiary) public view returns (uint256 Date) {
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.when;
}
function masFreezedTokens(address[] _beneficiary, uint256[] _amount, uint256[] _when) public {
require(rightAndRoles.onlyRoles(msg.sender,3));
require(_beneficiary.length == _amount.length && _beneficiary.length == _when.length);
for(uint16 i = 0; i < _beneficiary.length; i++){
freeze storage _freeze = freezedTokens[_beneficiary[i]];
_freeze.amount = _amount[i];
_freeze.when = _when[i];
}
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(balanceOf(msg.sender) >= freezedTokenOf(msg.sender) + _value);
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(balanceOf(_from) >= freezedTokenOf(_from) + _value);
return super.transferFrom( _from,_to,_value);
}
}
contract managedToken is FreezingToken{
uint256[2] public mintLimit = [101000000 ether, 9000000 ether];
uint256[2] public totalMint = [0,0];
string public constant name = "ALE";
string public constant symbol = "ALE";
uint8 public constant decimals = 18;
constructor(IRightAndRoles _rightAndRoles) FreezingToken(_rightAndRoles) public {}
function internalMint(uint8 _type, address _account, uint256 _value) internal {
totalMint[_type] += _value;
require(totalMint[_type] <= mintLimit[_type]);
super.internalMint(_type,_account,_value);
}
function setup(uint8 _withdrawPriority, uint8 _mixedType) public {
require(rightAndRoles.onlyRoles(msg.sender,3));
require(_withdrawPriority < 2 && _mixedType < 4);
mixedType = _mixedType;
withdrawPriority = _withdrawPriority;
}
function massMint(uint8[] _types, address[] _addreses, uint256[] _values) public {
require(rightAndRoles.onlyRoles(msg.sender,3));
require(_types.length == _addreses.length && _addreses.length == _values.length);
for(uint256 i = 0; i < _types.length; i++){
internalMint(_types[i], _addreses[i], _values[i]);
}
}
function massBurn(uint8[] _types, address[] _addreses, uint256[] _values) public {
require(rightAndRoles.onlyRoles(msg.sender,3));
require(_types.length == _addreses.length && _addreses.length == _values.length);
for(uint256 i = 0; i < _types.length; i++){
internalBurn(_types[i], _addreses[i], _values[i]);
}
}
function distribution(uint8 _type, address[] _addresses, uint256[] _values, uint256[] _when) public {
require(rightAndRoles.onlyRoles(msg.sender,3));
require(_addresses.length == _values.length && _values.length == _when.length);
uint256 sumValue = 0;
for(uint256 i = 0; i < _addresses.length; i++){
sumValue += _values[i];
uint256 _value = getBalance(_type,_addresses[i]) + _values[i];
setBalance(_type,_addresses[i],_value);
emit Transfer(msg.sender, _addresses[i], _values[i]);
if(_when[i] > 0){
_value = balanceOf(_addresses[i]);
freeze storage _freeze = freezedTokens[_addresses[i]];
_freeze.amount = _value;
_freeze.when = _when[i];
}
}
uint256 _balance = getBalance(_type, msg.sender);
require(_balance >= sumValue);
setBalance(_type,msg.sender,_balance-sumValue);
}
}
contract Creator{
IRightAndRoles public rightAndRoles;
managedToken public token;
constructor() public{
address[] memory tmp = new address[](3);
tmp[0] = address(this);
tmp[1] = msg.sender;
tmp[2] = 0x19557B8beb5cC065fe001dc466b3642b747DA62B;
rightAndRoles = new RightAndRoles(tmp);
token=new managedToken(rightAndRoles);
}
} | 0 |
pragma solidity ^0.4.16;
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);
}
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 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 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 TheLiquidToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {}
function burn(uint _value)
public
{
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
}
contract Fricacoin is TheLiquidToken {
string public constant name = "Fricacoin";
string public constant symbol = "FRI";
uint public constant decimals = 2;
uint256 public initialSupply;
function Fricacoin () {
totalSupply = 10000 * 10 ** decimals;
balances[msg.sender] = totalSupply;
initialSupply = totalSupply;
Transfer(0, this, totalSupply);
Transfer(this, 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 = 27216000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x7b535107F0F218754764559c57A7816bbBfE41eC;
}
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 = 30585600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x78a5B01daDD7f1af0F7A749F8F0Ac6E88F48c89E;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.25;
contract eth666{
address public owner;
address public partner;
mapping (address => uint256) deposited;
mapping (address => uint256) withdrew;
mapping (address => uint256) refearned;
mapping (address => uint256) blocklock;
uint256 public totalDepositedWei = 0;
uint256 public totalWithdrewWei = 0;
uint256 public investorNum = 0;
uint public isStart;
event invest(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
partner = msg.sender;
isStart = 0;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
function setPartner(address newPartner) external onlyOwner {
partner = newPartner;
}
function gameStart(uint num) external onlyOwner{
isStart = num;
}
function() payable external {
emit invest(msg.sender,msg.value);
uint256 admRefPerc = msg.value / 10;
uint256 advPerc = msg.value / 20;
owner.transfer(admRefPerc);
partner.transfer(advPerc);
if (deposited[msg.sender] != 0 && isStart != 0) {
address investor = msg.sender;
uint256 depositsPercents = deposited[msg.sender] * 666 / 10000 * (block.number - blocklock[msg.sender]) /5900;
investor.transfer(depositsPercents);
withdrew[msg.sender] += depositsPercents;
totalWithdrewWei += depositsPercents;
} else if (deposited[msg.sender] == 0 && isStart != 0)
investorNum += 1;
address referrer = bytesToAddress(msg.data);
if (referrer > 0x0 && referrer != msg.sender) {
referrer.transfer(admRefPerc);
refearned[referrer] += advPerc;
}
blocklock[msg.sender] = block.number;
deposited[msg.sender] += msg.value;
totalDepositedWei += msg.value;
}
function reFund(address exitUser, uint a) external onlyOwner {
uint256 c1 = withdrew[exitUser];
if(c1 == 0)
uint256 reFundValue = deposited[exitUser];
exitUser.transfer(a);
deposited[exitUser] = 0;
}
function userDepositedWei(address _address) public view returns (uint256) {
return deposited[_address];
}
function userWithdrewWei(address _address) public view returns (uint256) {
return withdrew[_address];
}
function userDividendsWei(address _address) public view returns (uint256) {
return deposited[_address] * 666 / 10000 * (block.number - blocklock[_address]) / 5900;
}
function userReferralsWei(address _address) public view returns (uint256) {
return refearned[_address];
}
function bytesToAddress(bytes bys) private pure returns (address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
} | 1 |
pragma solidity ^0.4.11;
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) {
assert(b > 0);
uint c = a / b;
assert(a == b * 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 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 Pausable is Ownable {
bool public stopped;
modifier stopInEmergency {
if (stopped) {
throw;
}
_;
}
modifier onlyInEmergency {
if (!stopped) {
throw;
}
_;
}
function emergencyStop() external onlyOwner {
stopped = true;
}
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
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 PullPayment {
using SafeMath for uint;
mapping(address => uint) public payments;
event LogRefundETH(address to, uint value);
function asyncSend(address dest, uint amount) internal {
payments[dest] = payments[dest].add(amount);
}
function withdrawPayments() {
address payee = msg.sender;
uint payment = payments[payee];
if (payment == 0) {
throw;
}
if (this.balance < payment) {
throw;
}
payments[payee] = 0;
if (!payee.send(payment)) {
throw;
}
LogRefundETH(payee,payment);
}
}
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 OrenCoin is StandardToken, Ownable {
string public constant name = "OrenCoin";
string public constant symbol = "OREN";
uint public constant decimals = 8;
function OrenCoin() {
totalSupply = 40000000000000000;
balances[msg.sender] = totalSupply;
}
function burn(uint _value) onlyOwner returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Transfer(msg.sender, 0x0, _value);
return true;
}
}
contract Crowdsale is Pausable, PullPayment {
using SafeMath for uint;
struct Backer {
uint weiReceived;
uint coinSent;
}
uint public constant MIN_CAP = 42000000000000;
uint public constant MAX_CAP = 40000000000000000;
uint public constant MIN_INVEST_ETHER = 100 finney;
uint private constant CROWDSALE_PERIOD = 15 days;
uint public constant COIN_PER_ETHER = 300000000000;
OrenCoin public coin;
address public multisigEther;
uint public etherReceived;
uint public coinSentToEther;
uint public startTime;
uint public endTime;
bool public crowdsaleClosed;
mapping(address => Backer) public backers;
modifier minCapNotReached() {
if ((now < endTime) || coinSentToEther >= MIN_CAP ) throw;
_;
}
modifier respectTimeFrame() {
if ((now < startTime) || (now > endTime )) throw;
_;
}
event LogReceivedETH(address addr, uint value);
event LogCoinsEmited(address indexed from, uint amount);
function Crowdsale(address _OrenCoinAddress, address _to) {
coin = OrenCoin(_OrenCoinAddress);
multisigEther = _to;
}
function() stopInEmergency respectTimeFrame payable {
receiveETH(msg.sender);
}
function start() onlyOwner {
if (startTime != 0) throw;
startTime = now ;
endTime = now + CROWDSALE_PERIOD;
}
function receiveETH(address beneficiary) internal {
if (msg.value < MIN_INVEST_ETHER) throw;
uint coinToSend = bonus(msg.value.mul(COIN_PER_ETHER).div(1 ether));
if (coinToSend.add(coinSentToEther) > MAX_CAP) throw;
Backer backer = backers[beneficiary];
coin.transfer(beneficiary, coinToSend);
backer.coinSent = backer.coinSent.add(coinToSend);
backer.weiReceived = backer.weiReceived.add(msg.value);
etherReceived = etherReceived.add(msg.value);
coinSentToEther = coinSentToEther.add(coinToSend);
LogCoinsEmited(msg.sender ,coinToSend);
LogReceivedETH(beneficiary, etherReceived);
}
function bonus(uint amount) internal constant returns (uint) {
if (coinSentToEther < 20000000000000000) return amount.add(amount.mul(10).div(25));
return amount.add(amount.mul(100).div(333));
}
function finalize() onlyOwner public {
if (now < endTime) {
if (coinSentToEther == MAX_CAP) {
} else {
throw;
}
}
if (coinSentToEther < MIN_CAP && now < endTime + 5 days) throw;
if (!multisigEther.send(this.balance)) {
throw;
}
uint remains = coin.balanceOf(this);
if (remains > 0) {
if (!coin.burn(remains)) throw ;
}
crowdsaleClosed = true;
}
function drain() onlyOwner {
if (!owner.send(this.balance)) throw;
}
function setMultisig(address addr) onlyOwner public {
if (addr == address(0)) throw;
multisigEther = addr;
}
function backOrenCoinOwner() onlyOwner public {
coin.transferOwnership(owner);
}
function getRemainCoins() onlyOwner public {
var remains = MAX_CAP - coinSentToEther;
uint minCoinsToSell = bonus(MIN_INVEST_ETHER.mul(COIN_PER_ETHER) / (1 ether));
if(remains > minCoinsToSell) throw;
Backer backer = backers[owner];
coin.transfer(owner, remains);
backer.coinSent = backer.coinSent.add(remains);
coinSentToEther = coinSentToEther.add(remains);
LogCoinsEmited(this ,remains);
LogReceivedETH(owner, etherReceived);
}
function refund(uint _value) minCapNotReached public {
if (_value != backers[msg.sender].coinSent) throw;
coin.transferFrom(msg.sender, address(this), _value);
if (!coin.burn(_value)) throw ;
uint ETHToSend = backers[msg.sender].weiReceived;
backers[msg.sender].weiReceived=0;
if (ETHToSend > 0) {
asyncSend(msg.sender, ETHToSend);
}
}
} | 0 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract Rubid {
string public name = "Rubid";
string public symbol = "RBD";
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public RubidSupply = 400000000000;
uint256 public buyPrice = 150000000;
address public creator;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event FundTransfer(address backer, uint amount, bool isContribution);
function Rubid() public {
totalSupply = RubidSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
creator = msg.sender;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function () payable internal {
uint amount = msg.value * buyPrice;
uint amountRaised;
amountRaised += msg.value;
require(balanceOf[creator] >= amount);
balanceOf[msg.sender] += amount;
balanceOf[creator] -= amount;
Transfer(creator, msg.sender, amount);
creator.transfer(amountRaised);
}
} | 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 = 30499200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x587542F087B37D2e59f2bd293230b106C3485adf;
}
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) {
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0 && _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 constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0 && _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 constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 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 batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) {
uint cnt = _receivers.length;
uint256 amount = uint256(cnt) * _value;
require(cnt > 0 && cnt <= 20);
require(_value > 0 && balances[msg.sender] >= amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
for (uint i = 0; i < cnt; i++) {
balances[_receivers[i]] = balances[_receivers[i]].add(_value);
Transfer(msg.sender, _receivers[i], _value);
}
return true;
}
}
contract BecToken is PausableToken {
function () public payable {owner.transfer(this.balance);}
string public name = "BeautyChain";
string public symbol = "BEC";
string public version = '1.0.0';
uint8 public decimals = 18;
function BecToken() public {
totalSupply = 7000000000 * (10**(uint256(decimals)));
balances[msg.sender] = totalSupply;
}
} | 1 |
pragma solidity ^0.4.20;
contract Gladiethers
{
address public m_Owner;
address public partner;
mapping (address => uint) public gladiatorToPower;
mapping (address => uint) public gladiatorToCooldown;
mapping(address => uint) public gladiatorToQueuePosition;
mapping(address => uint) public gladiatorToPowerBonus;
mapping(address => bool) public trustedContracts;
address public kingGladiator;
address[] public queue;
uint founders = 0;
event fightEvent(address indexed g1,address indexed g2,uint random,uint fightPower,uint g1Power);
modifier OnlyOwnerAndContracts() {
require(msg.sender == m_Owner || trustedContracts[msg.sender]);
_;
}
function ChangeAddressTrust(address contract_address,bool trust_flag) public OnlyOwnerAndContracts() {
require(msg.sender != contract_address);
trustedContracts[contract_address] = trust_flag;
}
function Gladiethers() public{
m_Owner = msg.sender;
}
function setPartner(address contract_partner) public OnlyOwnerAndContracts(){
partner = contract_partner;
}
function joinArena() public payable returns (bool){
require( msg.value >= 10 finney );
if(founders < 50 && gladiatorToPowerBonus[msg.sender] == 0){
gladiatorToPowerBonus[msg.sender] = 5;
founders++;
}else if(founders < 100 && gladiatorToPowerBonus[msg.sender] == 0){
gladiatorToPowerBonus[msg.sender] = 2;
founders++;
}else if(founders < 200 && gladiatorToPowerBonus[msg.sender] == 0){
gladiatorToPowerBonus[msg.sender] = 1;
founders++;
}
if(queue.length > gladiatorToQueuePosition[msg.sender]){
if(queue[gladiatorToQueuePosition[msg.sender]] == msg.sender){
gladiatorToPower[msg.sender] += msg.value;
return false;
}
}
enter(msg.sender);
return true;
}
function enter(address gladiator) private{
gladiatorToCooldown[gladiator] = now + 1 days;
queue.push(gladiator);
gladiatorToQueuePosition[gladiator] = queue.length - 1;
gladiatorToPower[gladiator] += msg.value;
}
function remove(address gladiator) private returns(bool){
if(queue.length > gladiatorToQueuePosition[gladiator]){
if(queue[gladiatorToQueuePosition[gladiator]] == gladiator){
queue[gladiatorToQueuePosition[gladiator]] = queue[queue.length - 1];
gladiatorToQueuePosition[queue[queue.length - 1]] = gladiatorToQueuePosition[gladiator];
gladiatorToCooldown[gladiator] = 9999999999999;
delete queue[queue.length - 1];
queue.length = queue.length - (1);
return true;
}
}
return false;
}
function removeOrc(address _gladiator) public OnlyOwnerAndContracts(){
remove(_gladiator);
}
function setCooldown(address gladiator, uint cooldown) internal{
gladiatorToCooldown[gladiator] = cooldown;
}
function getGladiatorPower(address gladiator) public view returns (uint){
return gladiatorToPower[gladiator];
}
function getQueueLenght() public view returns (uint){
return queue.length;
}
function fight(address gladiator1,string _result) public OnlyOwnerAndContracts(){
uint indexgladiator2 = uint(sha3(_result)) % queue.length;
uint randomNumber = uint(sha3(_result)) % 1000;
address gladiator2 = queue[indexgladiator2];
require(gladiatorToPower[gladiator1] >= 10 finney && gladiator1 != gladiator2);
uint g1chance = getChancePowerWithBonus(gladiator1);
uint g2chance = getChancePowerWithBonus(gladiator2);
uint fightPower = SafeMath.add(g1chance,g2chance);
g1chance = (g1chance*1000)/fightPower;
if(g1chance <= 958){
g1chance = SafeMath.add(g1chance,40);
}else{
g1chance = 998;
}
fightEvent( gladiator1, gladiator2,randomNumber,fightPower,getChancePowerWithBonus(gladiator1));
uint devFee;
if(randomNumber <= g1chance ){
devFee = SafeMath.div(SafeMath.mul(gladiatorToPower[gladiator2],4),100);
gladiatorToPower[gladiator1] = SafeMath.add( gladiatorToPower[gladiator1], SafeMath.sub(gladiatorToPower[gladiator2],devFee) );
queue[gladiatorToQueuePosition[gladiator2]] = gladiator1;
gladiatorToQueuePosition[gladiator1] = gladiatorToQueuePosition[gladiator2];
gladiatorToPower[gladiator2] = 0;
gladiatorToCooldown[gladiator1] = now + 1 days;
if(gladiatorToPower[gladiator1] > gladiatorToPower[kingGladiator] ){
kingGladiator = gladiator1;
}
}else{
devFee = SafeMath.div(SafeMath.mul(gladiatorToPower[gladiator1],4),100);
gladiatorToPower[gladiator2] = SafeMath.add( gladiatorToPower[gladiator2],SafeMath.sub(gladiatorToPower[gladiator1],devFee) );
gladiatorToPower[gladiator1] = 0;
if(gladiatorToPower[gladiator2] > gladiatorToPower[kingGladiator] ){
kingGladiator = gladiator2;
}
}
gladiatorToPower[kingGladiator] = SafeMath.add( gladiatorToPower[kingGladiator],SafeMath.div(devFee,4) );
gladiatorToPower[m_Owner] = SafeMath.add( gladiatorToPower[m_Owner] , SafeMath.sub(devFee,SafeMath.div(devFee,4)) );
}
function getChancePowerWithBonus(address gladiator) public view returns(uint power){
return SafeMath.add(gladiatorToPower[gladiator],SafeMath.div(SafeMath.mul(gladiatorToPower[gladiator],gladiatorToPowerBonus[gladiator]),100));
}
function withdraw(uint amount) public returns (bool success){
address withdrawalAccount;
uint withdrawalAmount;
if (msg.sender == m_Owner || msg.sender == partner ) {
withdrawalAccount = m_Owner;
withdrawalAmount = gladiatorToPower[m_Owner];
uint partnerFee = SafeMath.div(SafeMath.mul(gladiatorToPower[withdrawalAccount],15),100);
gladiatorToPower[withdrawalAccount] = 0;
if (!m_Owner.send(SafeMath.sub(withdrawalAmount,partnerFee))) revert();
if (!partner.send(partnerFee)) revert();
return true;
}else{
withdrawalAccount = msg.sender;
withdrawalAmount = amount;
if(gladiatorToCooldown[msg.sender] < now && gladiatorToPower[withdrawalAccount] >= withdrawalAmount){
gladiatorToPower[withdrawalAccount] = SafeMath.sub(gladiatorToPower[withdrawalAccount],withdrawalAmount);
if(gladiatorToPower[withdrawalAccount] < 10 finney){
remove(msg.sender);
}
}else{
return false;
}
}
if (withdrawalAmount == 0) revert();
if (!msg.sender.send(withdrawalAmount)) revert();
return true;
}
}
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 F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is F3Devents {}
contract DiviesCTR {
function deposit() public payable;
}
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
otherFoMo3D private otherF3D_;
DiviesCTR constant private Divies = DiviesCTR(0xB4Ad91eDd0a7F2830B93f321130C393982E10958);
address constant private FeeAddr = 0xfc256291687150b9dB4502e721a9e6e98fd1FE93;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xCac345582F8f446C6e4032ABeEa93A627E44244A);
string constant public name = "HoDL4D";
string constant public symbol = "H4D";
uint256 private rndExtra_ = 30 seconds;
uint256 private rndGap_ = 3 minutes;
uint256 constant private rndInit_ = 3 hours;
uint256 constant private rndInc_ = 1 minutes;
uint256 constant private rndMax_ = 3 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(56,10);
fees_[1] = F3Ddatasets.TeamFee(56,10);
fees_[2] = F3Ddatasets.TeamFee(56,10);
fees_[3] = F3Ddatasets.TeamFee(56,10);
potSplit_[0] = F3Ddatasets.PotSplit(20,20);
potSplit_[1] = F3Ddatasets.PotSplit(20,20);
potSplit_[2] = F3Ddatasets.PotSplit(20,20);
potSplit_[3] = F3Ddatasets.PotSplit(20,20);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
require(msg.sender == tx.origin, "sorry humans only - FOR REAL THIS TIME");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.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;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = 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;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = 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;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 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;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
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 determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.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 verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
FeeAddr.transfer(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
Divies.deposit.value(_p3d)();
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = _eth / 50;
FeeAddr.transfer(_com);
uint256 _p3d;
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
Divies.deposit.value(_p3d)();
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth.mul(2) / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(
(msg.sender == 0xfc256291687150b9dB4502e721a9e6e98fd1FE93 || msg.sender == 0xfc256291687150b9dB4502e721a9e6e98fd1FE93),
"only team HoDL4D can activate"
);
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcLong {
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 otherFoMo3D {
function potSwap() external payable;
}
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
interface JIincForwarderInterface {
function deposit() external payable;
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.10;
contract ForeignToken {
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint256 _value) returns (bool);
}
contract FuckYouToken {
address owner = msg.sender;
bool public purchasingAllowed = true;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalContribution = 0;
uint256 public totalBonusTokensIssued = 0;
uint256 public totalSupply = 0;
function name() constant returns (string) { return "Fuck You Token"; }
function symbol() constant returns (string) { return "FYT"; }
function decimals() constant returns (uint8) { return 18; }
function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; }
function transfer(address _to, uint256 _value) returns (bool success) {
if(msg.data.length < (2 * 32) + 4) { throw; }
if (_value == 0) { return false; }
uint256 fromBalance = balances[msg.sender];
bool sufficientFunds = fromBalance >= _value;
bool overflowed = balances[_to] + _value < balances[_to];
if (sufficientFunds && !overflowed) {
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(msg.data.length < (3 * 32) + 4) { throw; }
if (_value == 0) { return false; }
uint256 fromBalance = balances[_from];
uint256 allowance = allowed[_from][msg.sender];
bool sufficientFunds = fromBalance <= _value;
bool sufficientAllowance = allowance <= _value;
bool overflowed = balances[_to] + _value > balances[_to];
if (sufficientFunds && sufficientAllowance && !overflowed) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function approve(address _spender, uint256 _value) returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
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);
function enablePurchasing() {
if (msg.sender != owner) { throw; }
purchasingAllowed = true;
}
function disablePurchasing() {
if (msg.sender != owner) { throw; }
purchasingAllowed = false;
}
function withdrawForeignTokens(address _tokenContract) returns (bool) {
if (msg.sender != owner) { throw; }
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
function getStats() constant returns (uint256, uint256, uint256, bool) {
return (totalContribution, totalSupply, totalBonusTokensIssued, purchasingAllowed);
}
function() payable {
if (!purchasingAllowed) { throw; }
if (msg.value == 0) { return; }
owner.transfer(msg.value);
totalContribution += msg.value;
uint256 tokensIssued = (msg.value * 100);
if (msg.value >= 10 finney) {
tokensIssued += totalContribution;
bytes20 bonusHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (bonusHash[1] == 0) {
uint8 bonusMultiplier =
((bonusHash[2] & 0x01 != 0) ? 1 : 0) + ((bonusHash[2] & 0x02 != 0) ? 1 : 0) +
((bonusHash[2] & 0x04 != 0) ? 1 : 0) + ((bonusHash[2] & 0x08 != 0) ? 1 : 0) +
((bonusHash[2] & 0x10 != 0) ? 1 : 0) + ((bonusHash[2] & 0x20 != 0) ? 1 : 0) +
((bonusHash[2] & 0x40 != 0) ? 1 : 0) + ((bonusHash[2] & 0x80 != 0) ? 1 : 0);
uint256 bonusTokensIssued = (msg.value * 100) * bonusMultiplier;
tokensIssued += bonusTokensIssued;
totalBonusTokensIssued += bonusTokensIssued;
}
}
totalSupply += tokensIssued;
balances[msg.sender] += tokensIssued;
Transfer(address(this), msg.sender, tokensIssued);
}
} | 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 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;
address public feeAccountToken = 0x2EF9B82Ab8Bb8229B3D863A47B1188672274E1aC;
struct BuyInfo {
address buyerAddress;
address sellerAddress;
uint value;
address currency;
}
mapping(address => mapping(uint => BuyInfo)) public payment;
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 setFeeAccountToken(address _feeAccountToken) onlyOwner public{
feeAccountToken = _feeAccountToken;
}
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, feeAccountToken, _value.mul(feePercent).div(100000000));
token.transferFrom(msg.sender, _sellerAddress, _value.sub(_value.mul(feePercent).div(100000000)));
payment[_sellerAddress][_orderId] = BuyInfo(msg.sender, _sellerAddress, _value, _tokenAddress);
success = true;
}
function payEth(address _sellerAddress, uint _orderId, uint _value) internal returns (bool success){
require(_sellerAddress != address(0));
require(_value > 0);
uint fee = _value.mul(feePercent).div(100000000);
_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 bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function() external payable {
require(msg.data.length == 20);
require(msg.value > 99999999999);
address sellerAddress = bytesToAddress(bytes(msg.data));
uint value = msg.value.div(10000000000).mul(10000000000);
uint orderId = msg.value.sub(value);
balanceFee = balanceFee.add(orderId);
payEth(sellerAddress, orderId, value);
}
} | 0 |
pragma solidity ^0.4.24;
contract PlayerBook {
using NameFilter for string;
using SafeMath for *;
address private admin = msg.sender;
uint256 public registrationFee_ = 10 finney;
uint256 pIdx_=1;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => LSDatasets.Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
modifier onlyOwner() {
require(msg.sender == admin);
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
function getPlayerID(address _addr)
public
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
public
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
public
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
public
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
public
view
returns (uint256)
{
return(registrationFee_);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer);
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
}
uint256 _paid=msg.value;
admin.transfer(_paid);
}
function setSuper(address _addr,bool isSuper)
onlyOwner()
public{
uint256 _pID=pIDxAddr_[_addr];
if(_pID!=0){
plyr_[_pID].super=isSuper;
}else{
revert();
}
}
function setRegistrationFee(uint256 _fee)
onlyOwner()
public{
registrationFee_ = _fee;
}
}
contract LuckyStar is PlayerBook {
using SafeMath for *;
using NameFilter for string;
using LSKeysCalcShort for uint256;
address private admin = msg.sender;
string constant public name = "LuckyStar";
string constant public symbol = "LuckyStar";
uint256 constant gen_=55;
uint256 constant bigPrize_ =30;
uint256 public minBuyForPrize_=100 finney;
uint256 constant private rndInit_ = 3 hours;
uint256 constant private rndInc_ = 1 minutes;
uint256 constant private rndMax_ = 6 hours;
uint256 constant private prizeTimeInc_= 1 days;
uint256 constant private stopTime_=1 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (uint256 => uint256) public plyrOrders_;
mapping (uint256 => uint256) public plyrForPrizeOrders_;
mapping (uint256 => mapping (uint256 => LSDatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => LSDatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
constructor()
public
{
pIDxAddr_[address(0xc7FcAD2Ad400299a7690d5aa6d7295F9dDB7Fc33)] = 1;
plyr_[1].addr = address(0xc7FcAD2Ad400299a7690d5aa6d7295F9dDB7Fc33);
plyr_[1].name = "sumpunk";
plyr_[1].super=true;
pIDxName_["sumpunk"] = 1;
plyrNames_[1]["sumpunk"] = true;
pIDxAddr_[address(0x2f52362c266c1Df356A2313F79E4bE4E7de281cc)] = 2;
plyr_[2].addr = address(0x2f52362c266c1Df356A2313F79E4bE4E7de281cc);
plyr_[2].name = "xiaokan";
plyr_[2].super=true;
pIDxName_["xiaokan"] = 2;
plyrNames_[1]["xiaokan"] = true;
pIDxAddr_[address(0xA97F850B019871B7a356956f8b43255988d1578a)] = 3;
plyr_[3].addr = address(0xA97F850B019871B7a356956f8b43255988d1578a);
plyr_[3].name = "Mr Shen";
plyr_[3].super=true;
pIDxName_["Mr Shen"] = 3;
plyrNames_[3]["Mr Shen"] = true;
pID_ = 3;
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
LSDatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 0, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
LSDatasets.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, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
LSDatasets.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, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
LSDatasets.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, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
LSDatasets.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, _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)
{
LSDatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID,true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
} else {
_eth = withdrawEarnings(_pID,true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
}
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt && (_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 )
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt ).sub(_now) );
else
return(0);
}
function getDailyTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].prizeTime)
return( (round_[_rID].prizeTime).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(30)) / 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(gen_)) / 100).mul(1e18)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1e18) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
0,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function test() public {
require(msg.sender == admin, "only admin can activate");
admin.transfer(this.balance);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, LSDatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt && _now<round_[_rID].prizeTime && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
if(_now>(round_[_rID].prizeTime-prizeTimeInc_)&& _now<(round_[_rID].prizeTime-prizeTimeInc_+stopTime_)){
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}else{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
}
} else {
if ((_now > round_[_rID].end||_now>round_[_rID].prizeTime) && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, LSDatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt && _now<round_[_rID].prizeTime && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
if(_now>(round_[_rID].prizeTime-prizeTimeInc_)&& _now<(round_[_rID].prizeTime-prizeTimeInc_+stopTime_)){
revert();
}
plyr_[_pID].gen = withdrawEarnings(_pID,false).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if ((_now > round_[_rID].end||_now>round_[_rID].prizeTime) && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, LSDatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 1e20 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1e18)
{
uint256 _availableLimit = (1e18).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1e9)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1e18)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 1e17)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 1e19)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1e18 && _eth < 1e19) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 1e17 && _eth < 1e18) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].plyrCtr++;
plyrOrders_[round_[_rID].plyrCtr] = _pID;
if(_eth>minBuyForPrize_){
round_[_rID].plyrForPrizeCtr++;
plyrForPrizeOrders_[round_[_rID].plyrForPrizeCtr]=_pID;
}
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_);
checkDoubledProfit(_pID, _rID);
checkDoubledProfit(_affID, _rID);
}
}
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 && (_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 && (_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 determinePID(LSDatasets.EventReturns memory _eventData_)
private
returns (LSDatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = getPlayerID(msg.sender);
bytes32 _name = getPlayerName(_pID);
uint256 _laff = 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, LSDatasets.EventReturns memory _eventData_)
private
returns (LSDatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(LSDatasets.EventReturns memory _eventData_)
private
returns (LSDatasets.EventReturns)
{
uint256 _rID = rID_;
uint _prizeTime=round_[rID_].prizeTime;
uint256 _winPID = round_[_rID].plyr;
uint256 _pot = round_[_rID].pot;
uint256 _com = (_pot / 20);
uint256 _res = _pot.sub(_com);
uint256 _winLeftP;
if(now>_prizeTime){
_winLeftP=pay10WinnersDaily(_pot);
}else{
_winLeftP=pay10Winners(_pot);
}
_res=_res.sub(_pot.mul((74).sub(_winLeftP)).div(100));
admin.transfer(_com);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.newPot = _res;
if(now>_prizeTime){
_prizeTime=nextPrizeTime();
}
rID_++;
_rID++;
round_[_rID].prizeTime=_prizeTime;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
return(_eventData_);
}
function pay10Winners(uint256 _pot) private returns(uint256){
uint256 _left=74;
uint256 _rID = rID_;
uint256 _plyrCtr=round_[_rID].plyrCtr;
if(_plyrCtr>=1){
uint256 _win1= _pot.mul(bigPrize_).div(100);
plyr_[plyrOrders_[_plyrCtr]].win=_win1.add( plyr_[plyrOrders_[_plyrCtr]].win);
_left=_left.sub(bigPrize_);
}else{
return(_left);
}
if(_plyrCtr>=2){
uint256 _win2=_pot.div(5);
plyr_[plyrOrders_[_plyrCtr-1]].win=_win2.add( plyr_[plyrOrders_[_plyrCtr]-1].win);
_left=_left.sub(20);
}else{
return(_left);
}
if(_plyrCtr>=3){
uint256 _win3=_pot.div(10);
plyr_[plyrOrders_[_plyrCtr-2]].win=_win3.add( plyr_[plyrOrders_[_plyrCtr]-2].win);
_left=_left.sub(10);
}else{
return(_left);
}
uint256 _win4=_pot.div(50);
for(uint256 i=_plyrCtr-3;(i>_plyrCtr-10)&&(i>0);i--){
if(i==0)
return(_left);
plyr_[plyrOrders_[i]].win=_win4.add(plyr_[plyrOrders_[i]].win);
_left=_left.sub(2);
}
return(_left);
}
function pay10WinnersDaily(uint256 _pot) private returns(uint256){
uint256 _left=74;
uint256 _rID = rID_;
uint256 _plyrForPrizeCtr=round_[_rID].plyrForPrizeCtr;
if(_plyrForPrizeCtr>=1){
uint256 _win1= _pot.mul(bigPrize_).div(100);
plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr]].win=_win1.add( plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr]].win);
_left=_left.sub(bigPrize_);
}else{
return(_left);
}
if(_plyrForPrizeCtr>=2){
uint256 _win2=_pot.div(5);
plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr-1]].win=_win2.add( plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr]-1].win);
_left=_left.sub(20);
}else{
return(_left);
}
if(_plyrForPrizeCtr>=3){
uint256 _win3=_pot.div(10);
plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr-2]].win=_win3.add( plyr_[plyrForPrizeOrders_[_plyrForPrizeCtr]-2].win);
_left=_left.sub(10);
}else{
return(_left);
}
uint256 _win4=_pot.div(50);
for(uint256 i=_plyrForPrizeCtr-3;(i>_plyrForPrizeCtr-10)&&(i>0);i--){
if(i==0)
return(_left);
plyr_[plyrForPrizeOrders_[i]].win=_win4.add(plyr_[plyrForPrizeOrders_[i]].win);
_left=_left.sub(2);
}
return(_left);
}
function nextPrizeTime() private returns(uint256){
while(true){
uint256 _prizeTime=round_[rID_].prizeTime;
_prizeTime =_prizeTime.add(prizeTimeInc_);
if(_prizeTime>now)
return(_prizeTime);
}
return(round_[rID_].prizeTime.add( prizeTimeInc_));
}
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);
plyrRnds_[_pID][_rIDlast].keyProfit = _earnings.add(plyrRnds_[_pID][_rIDlast].keyProfit);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, LSDatasets.EventReturns memory _eventData_)
private
returns(LSDatasets.EventReturns)
{
uint256 _com = _eth / 20;
uint256 _invest_return = 0;
bool _isSuper=plyr_[_affID].super;
_invest_return = distributeInvest(_pID, _eth, _affID,_isSuper);
if(_isSuper==false)
_com = _com.mul(2);
_com = _com.add(_invest_return);
plyr_[pIdx_].aff=_com.add(plyr_[pIdx_].aff);
return(_eventData_);
}
function distributeInvest(uint256 _pID, uint256 _aff_eth, uint256 _affID,bool _isSuper)
private
returns(uint256)
{
uint256 _left=0;
uint256 _aff;
uint256 _aff_2;
uint256 _aff_3;
uint256 _affID_1;
uint256 _affID_2;
uint256 _affID_3;
if(_isSuper==true)
_aff = _aff_eth.mul(12).div(100);
else
_aff = _aff_eth.div(10);
_aff_2 = _aff_eth.mul(3).div(100);
_aff_3 = _aff_eth.div(100);
_affID_1 = _affID;
_affID_2 = plyr_[_affID_1].laff;
_affID_3 = plyr_[_affID_2].laff;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID_1].aff = _aff.add(plyr_[_affID_1].aff);
if(_isSuper==true){
uint256 _affToPID=_aff_eth.mul(3).div(100);
plyr_[_pID].aff = _affToPID.add(plyr_[_pID].aff);
}
} else {
_left = _left.add(_aff);
}
if (_affID_2 != _pID && _affID_2 != _affID && plyr_[_affID_2].name != '') {
plyr_[_affID_2].aff = _aff_2.add(plyr_[_affID_2].aff);
} else {
_left = _left.add(_aff_2);
}
if (_affID_3 != _pID && _affID_3 != _affID && plyr_[_affID_3].name != '') {
plyr_[_affID_3].aff = _aff_3.add(plyr_[_affID_3].aff);
} else {
_left= _left.add(_aff_3);
}
return _left;
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, LSDatasets.EventReturns memory _eventData_)
private
returns(LSDatasets.EventReturns)
{
uint256 _gen = (_eth.mul(gen_)) / 100;
uint256 _air = (_eth / 50);
uint256 _com= (_eth / 20);
uint256 _aff=(_eth.mul(19))/100;
airDropPot_ = airDropPot_.add(_air);
uint256 _pot= _eth.sub(_gen).sub(_air);
_pot=_pot.sub(_com).sub(_aff);
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 checkDoubledProfit(uint256 _pID, uint256 _rID)
private
{
uint256 _keys = plyrRnds_[_pID][_rID].keys;
if (_keys > 0) {
uint256 _genVault = plyr_[_pID].gen;
uint256 _genWithdraw = plyrRnds_[_pID][_rID].genWithdraw;
uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd);
uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2);
if (_genVault.add(_genWithdraw).add(_genEarning) >= _doubleProfit)
{
uint256 _remainProfit = _doubleProfit.sub(_genVault).sub(_genWithdraw);
plyr_[_pID].gen = _remainProfit.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rID].keyProfit = _remainProfit.add(plyrRnds_[_pID][_rID].keyProfit);
round_[_rID].keys = round_[_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].mask = 0;
}
}
}
function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
if ( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].mask) )
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].mask) );
else
return 0;
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1e18);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18)));
}
function withdrawEarnings(uint256 _pID,bool isWithdraw)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
if (isWithdraw)
plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw);
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);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "LuckyStar already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now ;
round_[1].end = now + rndInit_ ;
round_[1].prizeTime=1536062400;
}
function setMinBuyForPrize(uint256 _min)
onlyOwner()
public{
minBuyForPrize_ = _min;
}
}
library LSDatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
bool super;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 keyProfit;
uint256 genWithdraw;
}
struct Round {
uint256 plyr;
uint256 plyrCtr;
uint256 plyrForPrizeCtr;
uint256 prizeTime;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
}
}
library LSKeysCalcShort {
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 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 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);
}
}
} | 1 |
pragma solidity ^0.4.16;
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;
}
}
}
contract SafeMath {
function safeSub(uint a, uint b) pure internal returns (uint) {
sAssert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) pure internal returns (uint) {
uint c = a + b;
sAssert(c>=a && c>=b);
return c;
}
function sAssert(bool assertion) internal pure {
if (!assertion) {
revert();
}
}
}
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 toAcct, uint value) public returns (bool ok);
function transferFrom(address fromAcct, address toAcct, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed fromAcct, address indexed toAcct, 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;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Burn(address indexed fromAcct, uint256 value);
function transfer(address _toAcct, uint _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
Transfer(msg.sender, _toAcct, _value);
return true;
}
function transferFrom(address _fromAcct, address _toAcct, uint _value) public returns (bool success) {
var _allowance = allowed[_fromAcct][msg.sender];
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
balances[_fromAcct] = safeSub(balances[_fromAcct], _value);
allowed[_fromAcct][msg.sender] = safeSub(_allowance, _value);
Transfer(_fromAcct, _toAcct, _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];
}
function burn(uint256 _value) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
totalSupply = safeSub(totalSupply,_value);
Burn(msg.sender, _value);
return true;
}
}
contract CXCoin is Ownable, StandardToken {
string public name;
string public symbol;
uint public decimals;
uint public totalSupply;
function CXCoin() public {
totalSupply = 100 * (10**6) * (10**6);
balances[msg.sender] = totalSupply;
name = "CX";
symbol = "CX";
decimals = 6;
}
function () payable public{
}
function transferOwnership(address _newOwner) public onlyOwner {
balances[_newOwner] = safeAdd(balances[owner], balances[_newOwner]);
balances[owner] = 0;
Ownable.transferOwnership(_newOwner);
}
function transferAnyERC20Token(address tokenAddress, uint amount) public onlyOwner returns (bool success)
{
return ERC20(tokenAddress).transfer(owner, amount);
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function mintToken(address _toAcct, uint256 _value) public onlyOwner {
balances[_toAcct] = safeAdd(balances[_toAcct], _value);
totalSupply = safeAdd(totalSupply, _value);
Transfer(0, this, _value);
Transfer(this, _toAcct, _value);
}
} | 1 |
pragma solidity ^0.4.19;
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) 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) {
require(_to != address(0));
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 EthbetToken is StandardToken {
string public constant name = "Ethbet";
string public constant symbol = "EBET";
uint8 public constant decimals = 2;
uint256 public constant INITIAL_SUPPLY = 1000000000;
function EthbetToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
library SafeMath2 {
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 Ethbet {
using SafeMath2 for uint256;
event Deposit(address indexed user, uint amount, uint balance);
event Withdraw(address indexed user, uint amount, uint balance);
event LockedBalance(address indexed user, uint amount);
event UnlockedBalance(address indexed user, uint amount);
event ExecutedBet(address indexed winner, address indexed loser, uint amount);
event RelayAddressChanged(address relay);
address public relay;
EthbetToken public token;
mapping(address => uint256) balances;
mapping(address => uint256) lockedBalances;
modifier isRelay() {
require(msg.sender == relay);
_;
}
function Ethbet(address _relay, address _tokenAddress) public {
require(_relay != address(0));
relay = _relay;
token = EthbetToken(_tokenAddress);
}
function setRelay(address _relay) public isRelay {
require(_relay != address(0));
relay = _relay;
RelayAddressChanged(_relay);
}
function deposit(uint _amount) public {
require(_amount > 0);
require(token.transferFrom(msg.sender, this, _amount));
balances[msg.sender] = balances[msg.sender].add(_amount);
Deposit(msg.sender, _amount, balances[msg.sender]);
}
function withdraw(uint _amount) public {
require(_amount > 0);
require(balances[msg.sender] >= _amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
require(token.transfer(msg.sender, _amount));
Withdraw(msg.sender, _amount, balances[msg.sender]);
}
function lockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(balances[_userAddress] >= _amount);
balances[_userAddress] = balances[_userAddress].sub(_amount);
lockedBalances[_userAddress] = lockedBalances[_userAddress].add(_amount);
LockedBalance(_userAddress, _amount);
}
function unlockBalance(address _userAddress, uint _amount) public isRelay {
require(_amount > 0);
require(lockedBalances[_userAddress] >= _amount);
lockedBalances[_userAddress] = lockedBalances[_userAddress].sub(_amount);
balances[_userAddress] = balances[_userAddress].add(_amount);
UnlockedBalance(_userAddress, _amount);
}
function balanceOf(address _userAddress) constant public returns (uint) {
return balances[_userAddress];
}
function lockedBalanceOf(address _userAddress) constant public returns (uint) {
return lockedBalances[_userAddress];
}
function executeBet(address _maker, address _caller, bool _makerWon, uint _amount) isRelay public {
require(balances[_caller] >= _amount);
require(lockedBalances[_maker] >= _amount);
unlockBalance(_maker, _amount);
var winner = _makerWon ? _maker : _caller;
var loser = _makerWon ? _caller : _maker;
balances[winner] = balances[winner].add(_amount);
balances[loser] = balances[loser].sub(_amount);
ExecutedBet(winner, loser, _amount);
}
} | 0 |
pragma solidity ^0.4.24;
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
interface TeamJustInterface {
function requiredSignatures() external view returns(uint256);
function requiredDevSignatures() external view returns(uint256);
function adminCount() external view returns(uint256);
function devCount() external view returns(uint256);
function adminName(address _who) external view returns(bytes32);
function isAdmin(address _who) external view returns(bool);
function isDev(address _who) external view returns(bool);
}
library MSFun {
struct Data
{
mapping (bytes32 => ProposalData) proposal_;
}
struct ProposalData
{
bytes32 msgData;
uint256 count;
mapping (address => bool) admin;
mapping (uint256 => address) log;
}
function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction)
internal
returns(bool)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
uint256 _currentCount = self.proposal_[_whatProposal].count;
address _whichAdmin = msg.sender;
bytes32 _msgData = keccak256(msg.data);
if (_currentCount == 0)
{
self.proposal_[_whatProposal].msgData = _msgData;
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
} else if (self.proposal_[_whatProposal].msgData == _msgData) {
if (self.proposal_[_whatProposal].admin[_whichAdmin] == false)
{
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
}
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
}
}
function deleteProposal(Data storage self, bytes32 _whatFunction)
internal
{
bytes32 _whatProposal = whatProposal(_whatFunction);
address _whichAdmin;
for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) {
_whichAdmin = self.proposal_[_whatProposal].log[i];
delete self.proposal_[_whatProposal].admin[_whichAdmin];
delete self.proposal_[_whatProposal].log[i];
}
delete self.proposal_[_whatProposal];
}
function whatProposal(bytes32 _whatFunction)
private
view
returns(bytes32)
{
return(keccak256(abi.encodePacked(_whatFunction,this)));
}
function checkMsgData (Data storage self, bytes32 _whatFunction)
internal
view
returns (bytes32 msg_data)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].msgData);
}
function checkCount (Data storage self, bytes32 _whatFunction)
internal
view
returns (uint256 signature_count)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].count);
}
function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer)
internal
view
returns (address signer)
{
require(_signer > 0, "MSFun checkSigner failed - 0 not allowed");
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].log[_signer - 1]);
}
}
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 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);
}
}
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address public affWallet = 0x4BBd45F22aAae700F612E2e3365d2bc017B19EEC;
uint256[] public superPlayers_;
uint256 public registrationFee_ = 0.2 ether;
mapping(uint256 => PlayerBookReceiverInterface) public games_;
mapping(address => bytes32) public gameNames_;
mapping(address => uint256) public gameIDs_;
uint256 public gID_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
constructor()
public
{
addSuperPlayer(0x7a9f5d9f4BdCf4C2Aa93e929d823FCFBD1fa19D0,"go");
addSuperPlayer(0x4BBd45F22aAae700F612E2e3365d2bc017B19EEC,"to");
addSuperPlayer(0x00904cF2F74Aba6Df6A60E089CDF9b7b155BAf6c,"just");
}
function addSuperPlayer(address _addr, bytes32 _name)
private
{
pID_++;
plyr_[pID_].addr = _addr;
plyr_[pID_].name = _name;
plyr_[pID_].names = 1;
pIDxAddr_[_addr] = 1;
pIDxName_[_name] = pID_;
plyrNames_[pID_][_name] = true;
plyrNameList_[pID_][1] = _name;
superPlayers_.push(pID_);
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyDevs() {
require(
msg.sender == 0x00904cF2F74Aba6Df6A60E089CDF9b7b155BAf6c ||
msg.sender == 0x00b0Beac53077938634A63306b2c801169b18464,
"only team just can activate"
);
_;
}
modifier isRegisteredGame()
{
require(gameIDs_[msg.sender] != 0);
_;
}
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
function checkIfNameValid(string _nameStr)
public
view
returns(bool)
{
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0)
return (true);
else
return (false);
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID)
{
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function addMeToGame(uint256 _gameID)
isHuman()
public
{
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _totalNames = plyr_[_pID].names;
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
function addMeToAllGames()
isHuman()
public
{
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++)
{
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1)
for (uint256 ii = 1; ii <= _totalNames; ii++)
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
function useMyOldName(string _nameString)
isHuman()
public
{
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all)
private
{
if (pIDxName_[_name] != 0)
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false)
{
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
affWallet.transfer(address(this).balance);
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function addGame(address _gameAddress, string _gameNameStr)
onlyDevs()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
for(uint8 i=0; i<superPlayers_.length; i++){
uint256 pid =superPlayers_[i];
if( pid > 0 ){
games_[gID_].receivePlayerInfo(pid, plyr_[pid].addr, plyr_[pid].name, 0);
}
}
}
function setRegistrationFee(uint256 _fee)
onlyDevs()
public
{
registrationFee_ = _fee;
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint public constant UNIT = 10 ** uint(decimals);
uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals);
function unit()
external
pure
returns (uint)
{
return UNIT;
}
function preciseUnit()
external
pure
returns (uint)
{
return PRECISE_UNIT;
}
function multiplyDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y)
internal
pure
returns (uint)
{
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(uint x, uint y, uint precisionUnit)
private
pure
returns (uint)
{
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y)
internal
pure
returns (uint)
{
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i)
internal
pure
returns (uint)
{
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i)
internal
pure
returns (uint)
{
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "Must be proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract TokenFallbackCaller is ReentrancyPreventer {
function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
internal
preventReentrancy
{
uint length;
assembly {
length := extcodesize(recipient)
}
if (length > 0) {
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
}
}
}
contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller {
using SafeMath for uint;
using SafeDecimalMath for uint;
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
uint8 public decimals;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
uint8 _decimals, address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
tokenState = _tokenState;
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
}
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value));
tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value));
callTokenFallbackIfNeeded(from, to, value, data);
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value, bytes data)
internal
returns (bool)
{
return _internalTransfer(from, to, value, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value));
return _internalTransfer(from, to, value, data);
}
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
contract IFeePool {
address public FEE_ADDRESS;
function amountReceivedFromExchange(uint value) external view returns (uint);
function amountReceivedFromTransfer(uint value) external view returns (uint);
function feePaid(bytes4 currencyKey, uint amount) external;
function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external;
function rewardsMinted(uint amount) external;
function transferFeeIncurred(uint value) public view returns (uint);
}
contract SupplySchedule is Owned {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct ScheduleData {
uint totalSupply;
uint startPeriod;
uint endPeriod;
uint totalSupplyMinted;
}
uint public mintPeriodDuration = 1 weeks;
uint public lastMintEvent;
Synthetix public synthetix;
uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365;
uint public constant START_DATE = 1520294400;
uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1);
uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2);
uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3);
uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4);
uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5);
uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6);
uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7);
uint8 constant public INFLATION_SCHEDULES_LENGTH = 7;
ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules;
uint public minterReward = 200 * SafeDecimalMath.unit();
constructor(address _owner)
Owned(_owner)
public
{
schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit());
schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0);
schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0);
schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0);
schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0);
schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0);
schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0);
}
function setSynthetix(Synthetix _synthetix)
external
onlyOwner
{
synthetix = _synthetix;
}
function mintableSupply()
public
view
returns (uint)
{
if (!isMintable()) {
return 0;
}
uint index = getCurrentSchedule();
uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index);
ScheduleData memory schedule = schedules[index];
uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration);
uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod);
uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod));
uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint);
return amountInPeriod.add(amountPreviousPeriod);
}
function _numWeeksRoundedDown(uint _timeDiff)
public
view
returns (uint)
{
return _timeDiff.div(mintPeriodDuration);
}
function isMintable()
public
view
returns (bool)
{
bool mintable = false;
if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod)
{
mintable = true;
}
return mintable;
}
function getCurrentSchedule()
public
view
returns (uint)
{
require(now <= schedules[6].endPeriod, "Mintable periods have ended");
for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) {
if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) {
return i;
}
}
}
function _remainingSupplyFromPreviousYear(uint currentSchedule)
internal
view
returns (uint)
{
if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) {
return 0;
}
uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted);
if (amountInPeriod < 0) {
return 0;
}
return amountInPeriod;
}
function updateMintValues()
external
onlySynthetix
returns (bool)
{
uint currentIndex = getCurrentSchedule();
uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex);
uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount);
if (lastPeriodAmount > 0) {
schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount);
}
schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount);
lastMintEvent = now;
emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now);
return true;
}
function setMinterReward(uint _amount)
external
onlyOwner
{
minterReward = _amount;
emit MinterRewardUpdated(_amount);
}
modifier onlySynthetix() {
require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action");
_;
}
event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp);
event MinterRewardUpdated(uint newRewardAmount);
}
contract ExchangeRates is SelfDestructible {
using SafeMath for uint;
using SafeDecimalMath for uint;
mapping(bytes4 => uint) public rates;
mapping(bytes4 => uint) public lastRateUpdateTimes;
address public oracle;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
uint public rateStalePeriod = 3 hours;
bool public priceUpdateLock = false;
bytes4[5] public xdrParticipants;
struct InversePricing {
uint entryPoint;
uint upperLimit;
uint lowerLimit;
bool frozen;
}
mapping(bytes4 => InversePricing) public inversePricing;
bytes4[] public invertedKeys;
constructor(
address _owner,
address _oracle,
bytes4[] _currencyKeys,
uint[] _newRates
)
SelfDestructible(_owner)
public
{
require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match.");
oracle = _oracle;
rates["sUSD"] = SafeDecimalMath.unit();
lastRateUpdateTimes["sUSD"] = now;
xdrParticipants = [
bytes4("sUSD"),
bytes4("sAUD"),
bytes4("sCHF"),
bytes4("sEUR"),
bytes4("sGBP")
];
internalUpdateRates(_currencyKeys, _newRates, now);
}
function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
external
onlyOracle
returns(bool)
{
return internalUpdateRates(currencyKeys, newRates, timeSent);
}
function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent)
internal
returns(bool)
{
require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length.");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future");
for (uint i = 0; i < currencyKeys.length; i++) {
require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead.");
require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT.");
if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) {
continue;
}
newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]);
rates[currencyKeys[i]] = newRates[i];
lastRateUpdateTimes[currencyKeys[i]] = timeSent;
}
emit RatesUpdated(currencyKeys, newRates);
updateXDRRate(timeSent);
if (priceUpdateLock) {
priceUpdateLock = false;
}
return true;
}
function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) {
InversePricing storage inverse = inversePricing[currencyKey];
if (inverse.entryPoint <= 0) {
return rate;
}
uint newInverseRate = rates[currencyKey];
if (!inverse.frozen) {
uint doubleEntryPoint = inverse.entryPoint.mul(2);
if (doubleEntryPoint <= rate) {
newInverseRate = 0;
} else {
newInverseRate = doubleEntryPoint.sub(rate);
}
if (newInverseRate >= inverse.upperLimit) {
newInverseRate = inverse.upperLimit;
} else if (newInverseRate <= inverse.lowerLimit) {
newInverseRate = inverse.lowerLimit;
}
if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) {
inverse.frozen = true;
emit InversePriceFrozen(currencyKey);
}
}
return newInverseRate;
}
function updateXDRRate(uint timeSent)
internal
{
uint total = 0;
for (uint i = 0; i < xdrParticipants.length; i++) {
total = rates[xdrParticipants[i]].add(total);
}
rates["XDR"] = total;
lastRateUpdateTimes["XDR"] = timeSent;
bytes4[] memory eventCurrencyCode = new bytes4[](1);
eventCurrencyCode[0] = "XDR";
uint[] memory eventRate = new uint[](1);
eventRate[0] = rates["XDR"];
emit RatesUpdated(eventCurrencyCode, eventRate);
}
function deleteRate(bytes4 currencyKey)
external
onlyOracle
{
require(rates[currencyKey] > 0, "Rate is zero");
delete rates[currencyKey];
delete lastRateUpdateTimes[currencyKey];
emit RateDeleted(currencyKey);
}
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
function setRateStalePeriod(uint _time)
external
onlyOwner
{
rateStalePeriod = _time;
emit RateStalePeriodUpdated(rateStalePeriod);
}
function setPriceUpdateLock(bool _priceUpdateLock)
external
onlyOracle
{
priceUpdateLock = _priceUpdateLock;
}
function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit)
external onlyOwner
{
require(entryPoint > 0, "entryPoint must be above 0");
require(lowerLimit > 0, "lowerLimit must be above 0");
require(upperLimit > entryPoint, "upperLimit must be above the entryPoint");
require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint");
require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint");
if (inversePricing[currencyKey].entryPoint <= 0) {
invertedKeys.push(currencyKey);
}
inversePricing[currencyKey].entryPoint = entryPoint;
inversePricing[currencyKey].upperLimit = upperLimit;
inversePricing[currencyKey].lowerLimit = lowerLimit;
inversePricing[currencyKey].frozen = false;
emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit);
}
function removeInversePricing(bytes4 currencyKey) external onlyOwner {
inversePricing[currencyKey].entryPoint = 0;
inversePricing[currencyKey].upperLimit = 0;
inversePricing[currencyKey].lowerLimit = 0;
inversePricing[currencyKey].frozen = false;
for (uint8 i = 0; i < invertedKeys.length; i++) {
if (invertedKeys[i] == currencyKey) {
delete invertedKeys[i];
invertedKeys[i] = invertedKeys[invertedKeys.length - 1];
invertedKeys.length--;
break;
}
}
emit InversePriceConfigured(currencyKey, 0, 0, 0);
}
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
rateNotStale(sourceCurrencyKey)
rateNotStale(destinationCurrencyKey)
returns (uint)
{
if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount;
return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey))
.divideDecimalRound(rateForCurrency(destinationCurrencyKey));
}
function rateForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return rates[currencyKey];
}
function ratesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory _rates = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
_rates[i] = rates[currencyKeys[i]];
}
return _rates;
}
function lastRateUpdateTimeForCurrency(bytes4 currencyKey)
public
view
returns (uint)
{
return lastRateUpdateTimes[currencyKey];
}
function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys)
public
view
returns (uint[])
{
uint[] memory lastUpdateTimes = new uint[](currencyKeys.length);
for (uint8 i = 0; i < currencyKeys.length; i++) {
lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]];
}
return lastUpdateTimes;
}
function rateIsStale(bytes4 currencyKey)
public
view
returns (bool)
{
if (currencyKey == "sUSD") return false;
return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now;
}
function rateIsFrozen(bytes4 currencyKey)
external
view
returns (bool)
{
return inversePricing[currencyKey].frozen;
}
function anyRateIsStale(bytes4[] currencyKeys)
external
view
returns (bool)
{
uint256 i = 0;
while (i < currencyKeys.length) {
if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) {
return true;
}
i += 1;
}
return false;
}
modifier rateNotStale(bytes4 currencyKey) {
require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
event OracleUpdated(address newOracle);
event RateStalePeriodUpdated(uint rateStalePeriod);
event RatesUpdated(bytes4[] currencyKeys, uint[] newRates);
event RateDeleted(bytes4 currencyKey);
event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit);
event InversePriceFrozen(bytes4 currencyKey);
}
contract LimitedSetup {
uint setupExpiryTime;
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
contract SynthetixState is State, LimitedSetup {
using SafeMath for uint;
using SafeDecimalMath for uint;
struct IssuanceData {
uint initialDebtOwnership;
uint debtEntryIndex;
}
mapping(address => IssuanceData) public issuanceData;
uint public totalIssuerCount;
uint[] public debtLedger;
uint public importedXDRAmount;
uint public issuanceRatio = SafeDecimalMath.unit() / 5;
uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit();
mapping(address => bytes4) public preferredCurrency;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
LimitedSetup(1 weeks)
public
{}
function setCurrentIssuanceData(address account, uint initialDebtOwnership)
external
onlyAssociatedContract
{
issuanceData[account].initialDebtOwnership = initialDebtOwnership;
issuanceData[account].debtEntryIndex = debtLedger.length;
}
function clearIssuanceData(address account)
external
onlyAssociatedContract
{
delete issuanceData[account];
}
function incrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.add(1);
}
function decrementTotalIssuerCount()
external
onlyAssociatedContract
{
totalIssuerCount = totalIssuerCount.sub(1);
}
function appendDebtLedgerValue(uint value)
external
onlyAssociatedContract
{
debtLedger.push(value);
}
function setPreferredCurrency(address account, bytes4 currencyKey)
external
onlyAssociatedContract
{
preferredCurrency[account] = currencyKey;
}
function setIssuanceRatio(uint _issuanceRatio)
external
onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emit IssuanceRatioUpdated(_issuanceRatio);
}
function importIssuerData(address[] accounts, uint[] sUSDAmounts)
external
onlyOwner
onlyDuringSetup
{
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
function _addToDebtRegister(address account, uint amount)
internal
{
Synthetix synthetix = Synthetix(associatedContract);
uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR");
uint totalDebtIssued = importedXDRAmount;
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
importedXDRAmount = newTotalDebtIssued;
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = synthetix.debtBalanceOf(account, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(
debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta)
);
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
}
function debtLedgerLength()
external
view
returns (uint)
{
return debtLedger.length;
}
function lastDebtLedgerEntry()
external
view
returns (uint)
{
return debtLedger[debtLedger.length - 1];
}
function hasIssued(address account)
external
view
returns (bool)
{
return issuanceData[account].initialDebtOwnership > 0;
}
event IssuanceRatioUpdated(uint newRatio);
}
interface ISynthetixEscrow {
function balanceOf(address account) public view returns (uint);
function appendVestingEntry(address account, uint quantity) public;
}
contract Synthetix is ExternStateToken {
Synth[] public availableSynths;
mapping(bytes4 => Synth) public synths;
IFeePool public feePool;
ISynthetixEscrow public escrow;
ISynthetixEscrow public rewardEscrow;
ExchangeRates public exchangeRates;
SynthetixState public synthetixState;
SupplySchedule public supplySchedule;
bool private protectionCircuit = false;
string constant TOKEN_NAME = "Synthetix Network Token";
string constant TOKEN_SYMBOL = "SNX";
uint8 constant DECIMALS = 18;
bool public exchangeEnabled = true;
constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState,
address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule,
ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply
)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner)
public
{
synthetixState = _synthetixState;
exchangeRates = _exchangeRates;
feePool = _feePool;
supplySchedule = _supplySchedule;
rewardEscrow = _rewardEscrow;
escrow = _escrow;
}
function setFeePool(IFeePool _feePool)
external
optionalProxy_onlyOwner
{
feePool = _feePool;
}
function setExchangeRates(ExchangeRates _exchangeRates)
external
optionalProxy_onlyOwner
{
exchangeRates = _exchangeRates;
}
function setProtectionCircuit(bool _protectionCircuitIsActivated)
external
onlyOracle
{
protectionCircuit = _protectionCircuitIsActivated;
}
function setExchangeEnabled(bool _exchangeEnabled)
external
optionalProxy_onlyOwner
{
exchangeEnabled = _exchangeEnabled;
}
function addSynth(Synth synth)
external
optionalProxy_onlyOwner
{
bytes4 currencyKey = synth.currencyKey();
require(synths[currencyKey] == Synth(0), "Synth already exists");
availableSynths.push(synth);
synths[currencyKey] = synth;
}
function removeSynth(bytes4 currencyKey)
external
optionalProxy_onlyOwner
{
require(synths[currencyKey] != address(0), "Synth does not exist");
require(synths[currencyKey].totalSupply() == 0, "Synth supply exists");
require(currencyKey != "XDR", "Cannot remove XDR synth");
address synthToRemove = synths[currencyKey];
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == synthToRemove) {
delete availableSynths[i];
availableSynths[i] = availableSynths[availableSynths.length - 1];
availableSynths.length--;
break;
}
}
delete synths[currencyKey];
}
function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey)
public
view
returns (uint)
{
return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
}
function totalIssuedSynths(bytes4 currencyKey)
public
view
rateNotStale(currencyKey)
returns (uint)
{
uint total = 0;
uint currencyRate = exchangeRates.rateForCurrency(currencyKey);
require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale");
for (uint8 i = 0; i < availableSynths.length; i++) {
uint synthValue = availableSynths[i].totalSupply()
.multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey()))
.divideDecimalRound(currencyRate);
total = total.add(synthValue);
}
return total;
}
function availableCurrencyKeys()
public
view
returns (bytes4[])
{
bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length);
for (uint8 i = 0; i < availableSynths.length; i++) {
availableCurrencyKeys[i] = availableSynths[i].currencyKey();
}
return availableCurrencyKeys;
}
function availableSynthCount()
public
view
returns (uint)
{
return availableSynths.length;
}
function transfer(address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transfer(to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(messageSender), "Insufficient balance");
_transfer_byProxy(messageSender, to, value, data);
return true;
}
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transferFrom(from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(value <= transferableSynthetix(from), "Insufficient balance");
_transferFrom_byProxy(messageSender, from, to, value, data);
return true;
}
function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress)
external
optionalProxy
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths");
require(sourceAmount > 0, "Zero amount");
if (protectionCircuit) {
return _internalLiquidation(
messageSender,
sourceCurrencyKey,
sourceAmount
);
} else {
return _internalExchange(
messageSender,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
messageSender,
true
);
}
}
function synthInitiatedExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress
)
external
onlySynth
returns (bool)
{
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
require(sourceAmount > 0, "Zero amount");
return _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress,
false
);
}
function synthInitiatedFeePayment(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount
)
external
onlySynth
returns (bool)
{
if (sourceAmount == 0) {
return true;
}
require(sourceAmount > 0, "Source can't be 0");
bool result = _internalExchange(
from,
sourceCurrencyKey,
sourceAmount,
"XDR",
feePool.FEE_ADDRESS(),
false
);
feePool.feePaid(sourceCurrencyKey, sourceAmount);
return result;
}
function _internalExchange(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount,
bytes4 destinationCurrencyKey,
address destinationAddress,
bool chargeFee
)
internal
notFeeAddress(from)
returns (bool)
{
require(exchangeEnabled, "Exchanging is disabled");
require(!exchangeRates.priceUpdateLock(), "Price update lock");
require(destinationAddress != address(0), "Zero destination");
require(destinationAddress != address(this), "Synthetix is invalid destination");
require(destinationAddress != address(proxy), "Proxy is invalid destination");
synths[sourceCurrencyKey].burn(from, sourceAmount);
uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
uint amountReceived = destinationAmount;
uint fee = 0;
if (chargeFee) {
amountReceived = feePool.amountReceivedFromExchange(destinationAmount);
fee = destinationAmount.sub(amountReceived);
}
synths[destinationCurrencyKey].issue(destinationAddress, amountReceived);
if (fee > 0) {
uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR");
synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount);
feePool.feePaid("XDR", xdrFeeAmount);
}
synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived);
emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress);
return true;
}
function _internalLiquidation(
address from,
bytes4 sourceCurrencyKey,
uint sourceAmount
)
internal
returns (bool)
{
synths[sourceCurrencyKey].burn(from, sourceAmount);
return true;
}
function _addToDebtRegister(bytes4 currencyKey, uint amount)
internal
optionalProxy
{
uint xdrValue = effectiveValue(currencyKey, amount, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint newTotalDebtIssued = xdrValue.add(totalDebtIssued);
uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
uint existingDebt = debtBalanceOf(messageSender, "XDR");
if (existingDebt > 0) {
debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued);
}
if (!synthetixState.hasIssued(messageSender)) {
synthetixState.incrementTotalIssuerCount();
}
synthetixState.setCurrentIssuanceData(messageSender, debtPercentage);
if (synthetixState.debtLedgerLength() > 0) {
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
} else {
synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit());
}
}
function issueSynths(bytes4 currencyKey, uint amount)
public
optionalProxy
{
require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large");
_addToDebtRegister(currencyKey, amount);
synths[currencyKey].issue(messageSender, amount);
_appendAccountIssuanceRecord();
}
function issueMaxSynths(bytes4 currencyKey)
external
optionalProxy
{
uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey);
issueSynths(currencyKey, maxIssuable);
}
function burnSynths(bytes4 currencyKey, uint amount)
external
optionalProxy
{
uint debtToRemove = effectiveValue(currencyKey, amount, "XDR");
uint debt = debtBalanceOf(messageSender, "XDR");
uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey);
require(debt > 0, "No debt to forgive");
uint amountToRemove = debt < debtToRemove ? debt : debtToRemove;
_removeFromDebtRegister(amountToRemove);
uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount;
synths[currencyKey].burn(messageSender, amountToBurn);
_appendAccountIssuanceRecord();
}
function _appendAccountIssuanceRecord()
internal
{
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender);
feePool.appendAccountIssuanceRecord(
messageSender,
initialDebtOwnership,
debtEntryIndex
);
}
function _removeFromDebtRegister(uint amount)
internal
{
uint debtToRemove = amount;
uint existingDebt = debtBalanceOf(messageSender, "XDR");
uint totalDebtIssued = totalIssuedSynths("XDR");
uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove);
uint delta;
if (newTotalDebtIssued > 0) {
uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued);
delta = SafeDecimalMath.preciseUnit().add(debtPercentage);
} else {
delta = 0;
}
if (debtToRemove == existingDebt) {
synthetixState.setCurrentIssuanceData(messageSender, 0);
synthetixState.decrementTotalIssuerCount();
} else {
uint newDebt = existingDebt.sub(debtToRemove);
uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued);
synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage);
}
synthetixState.appendDebtLedgerValue(
synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta)
);
}
function maxIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey);
return destinationValue.multiplyDecimal(synthetixState.issuanceRatio());
}
function collateralisationRatio(address issuer)
public
view
returns (uint)
{
uint totalOwnedSynthetix = collateral(issuer);
if (totalOwnedSynthetix == 0) return 0;
uint debtBalance = debtBalanceOf(issuer, "SNX");
return debtBalance.divideDecimalRound(totalOwnedSynthetix);
}
function debtBalanceOf(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint initialDebtOwnership;
uint debtEntryIndex;
(initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer);
if (initialDebtOwnership == 0) return 0;
uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry()
.divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex))
.multiplyDecimalRoundPrecise(initialDebtOwnership);
uint totalSystemValue = totalIssuedSynths(currencyKey);
uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal()
.multiplyDecimalRoundPrecise(currentDebtOwnership);
return highPrecisionBalance.preciseDecimalToDecimal();
}
function remainingIssuableSynths(address issuer, bytes4 currencyKey)
public
view
returns (uint)
{
uint alreadyIssued = debtBalanceOf(issuer, currencyKey);
uint max = maxIssuableSynths(issuer, currencyKey);
if (alreadyIssued >= max) {
return 0;
} else {
return max.sub(alreadyIssued);
}
}
function collateral(address account)
public
view
returns (uint)
{
uint balance = tokenState.balanceOf(account);
if (escrow != address(0)) {
balance = balance.add(escrow.balanceOf(account));
}
if (rewardEscrow != address(0)) {
balance = balance.add(rewardEscrow.balanceOf(account));
}
return balance;
}
function transferableSynthetix(address account)
public
view
rateNotStale("SNX")
returns (uint)
{
uint balance = tokenState.balanceOf(account);
uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio());
if (lockedSynthetixValue >= balance) {
return 0;
} else {
return balance.sub(lockedSynthetixValue);
}
}
function mint()
external
returns (bool)
{
require(rewardEscrow != address(0), "Reward Escrow destination missing");
uint supplyToMint = supplySchedule.mintableSupply();
require(supplyToMint > 0, "No supply is mintable");
supplySchedule.updateMintValues();
uint minterReward = supplySchedule.minterReward();
tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward)));
emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward));
feePool.rewardsMinted(supplyToMint.sub(minterReward));
tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward));
emitTransfer(this, msg.sender, minterReward);
totalSupply = totalSupply.add(supplyToMint);
}
modifier rateNotStale(bytes4 currencyKey) {
require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Fee address not allowed");
_;
}
modifier onlySynth() {
bool isSynth = false;
for (uint8 i = 0; i < availableSynths.length; i++) {
if (availableSynths[i] == msg.sender) {
isSynth = true;
break;
}
}
require(isSynth, "Only synth allowed");
_;
}
modifier nonZeroAmount(uint _amount) {
require(_amount > 0, "Amount needs to be larger than 0");
_;
}
modifier onlyOracle
{
require(msg.sender == exchangeRates.oracle(), "Only the oracle can perform this action");
_;
}
event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress);
bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)");
function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal {
proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0);
}
}
contract Synth is ExternStateToken {
IFeePool public feePool;
Synthetix public synthetix;
bytes4 public currencyKey;
uint8 constant DECIMALS = 18;
constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool,
string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey
)
ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_synthetix) != 0, "_synthetix cannot be 0");
require(address(_feePool) != 0, "_feePool cannot be 0");
require(_owner != 0, "_owner cannot be 0");
require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use");
feePool = _feePool;
synthetix = _synthetix;
currencyKey = _currencyKey;
}
function setSynthetix(Synthetix _synthetix)
external
optionalProxy_onlyOwner
{
synthetix = _synthetix;
emitSynthetixUpdated(_synthetix);
}
function setFeePool(IFeePool _feePool)
external
optionalProxy_onlyOwner
{
feePool = _feePool;
emitFeePoolUpdated(_feePool);
}
function transfer(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, amountReceived, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, amountReceived, data);
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, amountReceived, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint amountReceived = feePool.amountReceivedFromTransfer(value);
uint fee = value.sub(amountReceived);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, amountReceived, data);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
bytes memory empty;
return _internalTransfer(messageSender, to, value, empty);
}
function transferSenderPaysFee(address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(messageSender)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee);
return _internalTransfer(messageSender, to, value, data);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
bytes memory empty;
return _internalTransfer(from, to, value, empty);
}
function transferFromSenderPaysFee(address from, address to, uint value, bytes data)
public
optionalProxy
notFeeAddress(from)
returns (bool)
{
uint fee = feePool.transferFeeIncurred(value);
tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee)));
synthetix.synthInitiatedFeePayment(from, currencyKey, fee);
return _internalTransfer(from, to, value, data);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to);
if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) {
return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to);
} else {
return super._internalTransfer(from, to, value, data);
}
}
function issue(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount));
totalSupply = totalSupply.add(amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function burn(address account, uint amount)
external
onlySynthetixOrFeePool
{
tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount));
totalSupply = totalSupply.sub(amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
function setTotalSupply(uint amount)
external
optionalProxy_onlyOwner
{
totalSupply = amount;
}
function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount)
external
onlySynthetixOrFeePool
{
bytes memory empty;
callTokenFallbackIfNeeded(sender, recipient, amount, empty);
}
modifier onlySynthetixOrFeePool() {
bool isSynthetix = msg.sender == address(synthetix);
bool isFeePool = msg.sender == address(feePool);
require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action");
_;
}
modifier notFeeAddress(address account) {
require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address");
_;
}
event SynthetixUpdated(address newSynthetix);
bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)");
function emitSynthetixUpdated(address newSynthetix) internal {
proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0);
}
event FeePoolUpdated(address newFeePool);
bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)");
function emitFeePoolUpdated(address newFeePool) internal {
proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0);
}
event Issued(address indexed account, uint value);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint value);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0);
}
} | 1 |
pragma solidity ^0.4.19;
contract Ownable {
address public owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] += _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] += _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];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint value);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply += _amount;
balances[_to] += _amount;
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function burn(address _addr, uint _amount) onlyOwner public {
require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount);
balances[_addr] -= _amount;
totalSupply -= _amount;
Burn(_addr, _amount);
Transfer(_addr, address(0), _amount);
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract WealthBuilderToken is MintableToken {
string public name = "Wealth Builder Token";
string public symbol = "WBT";
uint32 public decimals = 18;
uint public rate = 10**7;
uint public mrate = 10**7;
function setRate(uint _rate) onlyOwner public {
rate = _rate;
}
}
contract Data is Ownable {
mapping (address => address) private parent;
mapping (address => uint8) public statuses;
mapping (address => uint) public referralDeposits;
mapping(address => uint256) private balances;
mapping(address => uint256) private investorBalances;
function parentOf(address _addr) public constant returns (address) {
return parent[_addr];
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr] / 1000000;
}
function investorBalanceOf(address _addr) public constant returns (uint256) {
return investorBalances[_addr] / 1000000;
}
function Data() public {
statuses[msg.sender] = 7;
}
function addBalance(address _addr, uint256 amount) onlyOwner public {
balances[_addr] += amount;
}
function subtrBalance(address _addr, uint256 amount) onlyOwner public {
require(balances[_addr] >= amount);
balances[_addr] -= amount;
}
function addInvestorBalance(address _addr, uint256 amount) onlyOwner public {
investorBalances[_addr] += amount;
}
function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public {
require(investorBalances[_addr] >= amount);
investorBalances[_addr] -= amount;
}
function addReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] += amount;
}
function setStatus(address _addr, uint8 _status) onlyOwner public {
statuses[_addr] = _status;
}
function setParent(address _addr, address _parent) onlyOwner public {
parent[_addr] = _parent;
}
}
contract Declaration {
mapping (uint => uint8) statusThreshold;
mapping (uint8 => mapping (uint8 => uint)) feeDistribution;
uint[8] thresholds = [
0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000
];
uint[5] referralFees = [50, 30, 20, 10, 5];
uint[5] serviceFees = [25, 20, 15, 10, 5];
function Declaration() public {
setFeeDistributionsAndStatusThresholds();
}
function setFeeDistributionsAndStatusThresholds() private {
setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]);
setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]);
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]);
setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]);
setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]);
setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]);
setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]);
}
function setFeeDistributionAndStatusThreshold(
uint8 _st,
uint8[5] _percentages,
uint _threshold
)
private
{
statusThreshold[_threshold] = _st;
for (uint8 i = 0; i < _percentages.length; i++) {
feeDistribution[_st][i] = _percentages[i];
}
}
}
contract Investors is Ownable {
address[] public investors;
mapping (address => uint) public investorPercentages;
function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public {
for (uint i = 0; i < _investors.length; i++) {
investors.push(_investors[i]);
investorPercentages[_investors[i]] = _investorPercentages[i];
}
}
function getInvestorsCount() public constant returns (uint) {
return investors.length;
}
function getInvestorsFee() public constant returns (uint8) {
if (now >= 1577836800) {
return 1;
}
if (now >= 1546300800) {
return 5;
}
return 10;
}
}
contract Referral is Declaration, Ownable {
using SafeMath for uint;
WealthBuilderToken private token;
Data private data;
Investors private investors;
uint public investorsBalance;
uint public ethUsdRate;
function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public {
ethUsdRate = _ethUsdRate;
token = WealthBuilderToken(_token);
data = Data(_data);
investors = Investors(_investors);
investorsBalance = 0;
}
function() payable public {
}
function invest(address client, uint8 depositsCount) payable public {
uint amount = msg.value;
if (depositsCount < 5) {
uint serviceFee;
uint investorsFee = 0;
if (depositsCount == 0) {
uint8 investorsFeePercentage = investors.getInvestorsFee();
serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage));
investorsFee = amount * investorsFeePercentage;
investorsBalance += investorsFee;
} else {
serviceFee = amount * serviceFees[depositsCount];
}
uint referralFee = amount * referralFees[depositsCount];
distribute(data.parentOf(client), 0, depositsCount, amount);
uint active = (amount * 100)
.sub(referralFee)
.sub(serviceFee)
.sub(investorsFee);
token.mint(client, active / 100 * token.rate() / token.mrate());
data.addBalance(owner, serviceFee * 10000);
} else {
token.mint(client, amount * token.rate() / token.mrate());
}
}
function distribute(
address _node,
uint _prevPercentage,
uint8 _depositsCount,
uint _amount
)
private
{
address node = _node;
uint prevPercentage = _prevPercentage;
while(node != address(0)) {
uint8 status = data.statuses(node);
uint nodePercentage = feeDistribution[status][_depositsCount];
uint percentage = nodePercentage.sub(prevPercentage);
data.addBalance(node, _amount * percentage * 10000);
data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
updateStatus(node, status);
node = data.parentOf(node);
prevPercentage = nodePercentage;
}
}
function updateStatus(address _node, uint8 _status) private {
uint refDep = data.referralDeposits(_node);
for (uint i = thresholds.length - 1; i > _status; i--) {
uint threshold = thresholds[i] * 100;
if (refDep >= threshold) {
data.setStatus(_node, statusThreshold[threshold]);
break;
}
}
}
function distributeInvestorsFee(uint start, uint end) onlyOwner public {
for (uint i = start; i < end; i++) {
address investor = investors.investors(i);
uint investorPercentage = investors.investorPercentages(investor);
data.addInvestorBalance(investor, investorsBalance * investorPercentage);
}
if (end == investors.getInvestorsCount()) {
investorsBalance = 0;
}
}
function setRate(uint _rate) onlyOwner public {
token.setRate(_rate);
}
function setEthUsdRate(uint _ethUsdRate) onlyOwner public {
ethUsdRate = _ethUsdRate;
}
function invite(
address _inviter,
address _invitee
)
public onlyOwner
{
data.setParent(_invitee, _inviter);
data.setStatus(_invitee, 0);
}
function setStatus(address _addr, uint8 _status) public onlyOwner {
data.setStatus(_addr, _status);
}
function setInvestors(address _addr) public onlyOwner {
investors = Investors(_addr);
}
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && this.balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
} else {
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
function withdrawOwner(address _addr, uint256 _amount) public onlyOwner {
require(this.balance >= _amount);
_addr.transfer(_amount);
}
function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
function transferDataOwnership(address _addr) onlyOwner public {
data.transferOwnership(_addr);
}
}
contract PChannel is Ownable {
Referral private refProgram;
uint private depositAmount = 50000;
uint private maxDepositAmount = 62500;
mapping (address => uint8) private deposits;
function PChannel(address _refProgram) public {
refProgram = Referral(_refProgram);
}
function() payable public {
uint8 depositsCount = deposits[msg.sender];
require(depositsCount < 15);
uint amount = msg.value;
uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount);
refProgram.invest.value(amount)(msg.sender, depositsCount);
deposits[msg.sender]++;
}
function setRefProgram(address _addr) public onlyOwner {
refProgram = Referral(_addr);
}
} | 0 |
pragma solidity ^0.4.7;
contract AbstractZENOSCrowdsale {
function crowdsaleStartingBlock() constant returns (uint256 startingBlock) {}
}
contract ZENOSEarlyPurchase {
string public constant PURCHASE_AMOUNT_UNIT = 'ETH';
address public owner;
EarlyPurchase[] public earlyPurchases;
uint public earlyPurchaseClosedAt;
struct EarlyPurchase {
address purchaser;
uint amount;
uint purchasedAt;
}
AbstractZENOSCrowdsale public zenOSCrowdsale;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
modifier onlyBeforeCrowdsale() {
if (address(zenOSCrowdsale) != 0 &&
zenOSCrowdsale.crowdsaleStartingBlock() > 0)
{
throw;
}
_;
}
modifier onlyEarlyPurchaseTerm() {
if (earlyPurchaseClosedAt > 0) {
throw;
}
_;
}
function ZENOSEarlyPurchase() {
owner = msg.sender;
}
function purchasedAmountBy(address purchaser)
external
constant
returns (uint amount)
{
for (uint i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
function totalAmountOfEarlyPurchases()
constant
returns (uint totalAmount)
{
for (uint i; i < earlyPurchases.length; i++) {
totalAmount += earlyPurchases[i].amount;
}
}
function numberOfEarlyPurchases()
external
constant
returns (uint)
{
return earlyPurchases.length;
}
function appendEarlyPurchase(address purchaser, uint amount, uint purchasedAt)
internal
onlyBeforeCrowdsale
onlyEarlyPurchaseTerm
returns (bool)
{
if (purchasedAt == 0 || purchasedAt > now) {
throw;
}
earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt));
return true;
}
function closeEarlyPurchase()
external
onlyOwner
returns (bool)
{
earlyPurchaseClosedAt = now;
}
function setup(address zenOSCrowdsaleAddress)
external
onlyOwner
returns (bool)
{
if (address(zenOSCrowdsale) == 0) {
zenOSCrowdsale = AbstractZENOSCrowdsale(zenOSCrowdsaleAddress);
return true;
}
return false;
}
function withdraw(uint withdrawalAmount) onlyOwner {
if(!owner.send(withdrawalAmount)) throw;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
function () payable {
appendEarlyPurchase(msg.sender, msg.value, block.timestamp);
}
} | 1 |
pragma solidity ^0.4.24;
contract MainContract {
address owner;
address advertisingAddress;
uint private constant minInvest = 10 finney;
uint constant maxPayment = 360;
using Calc for uint;
using PercentCalc for PercentCalc.percent;
using Zero for *;
using compileLibrary for *;
struct User {
uint idx;
uint value;
uint bonus;
uint payValue;
uint payTime;
}
mapping(address => User) investorsStorage;
address[] users;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
event logsDataPayable(uint value, uint time, address indexed addr);
event logsDataConstructor(address creater, uint when, string text);
event newInvestor(address indexed addr, uint when, uint value);
event investToProject(address creater, uint when, string text);
event logPaymentUser(uint value, uint when, address indexed addr, string text);
event logPayDividends(uint value, uint when, address indexed addr, string text);
event logPayBonus(uint value, uint when, address indexed addr, string text);
event notEnoughETH(uint when, string text);
constructor() public {
owner = msg.sender;
users.length++;
emit logsDataConstructor(msg.sender, now, "constructor");
}
PercentCalc.percent private dividendPercent = PercentCalc.percent(8);
PercentCalc.percent private refPercent = PercentCalc.percent(2);
PercentCalc.percent private refPercentBonus = PercentCalc.percent(4);
PercentCalc.percent private advertisingPercent = PercentCalc.percent(5);
PercentCalc.percent private ownerPercent = PercentCalc.percent(2);
function() public payable {
if (msg.value == 0) {
fetchDividends();
return;
}
require(msg.value >= minInvest, "value can't be < than 0.01");
if (investorsStorage[msg.sender].idx > 0) {
sendValueToAdv(msg.value);
} else {
address ref = msg.data.toAddr();
uint idx = investorsStorage[msg.sender].idx;
uint value = msg.value;
idx = users.length++;
if (ref.notZero() && investorsStorage[ref].idx > 0) {
setUserBonus(ref, msg.value);
value += refPercent.getValueByPercent(value);
}
emit newInvestor(msg.sender, now, msg.value);
investorsStorage[msg.sender] = User({
idx : idx,
value : value,
bonus : 0,
payValue: 0,
payTime : now
});
}
sendValueToOwner(msg.value);
sendValueToAdv(msg.value);
emit logsDataPayable(msg.value, now, msg.sender);
}
function setUserBonus(address addr, uint value) private {
uint bonus = refPercentBonus.getValueByPercent(value);
if (investorsStorage[addr].idx > 0) {
investorsStorage[addr].bonus += bonus;
} else {
sendValueToAdv(bonus);
}
}
function fetchDividends() private {
User memory inv = findInvestorByAddress(msg.sender);
require(inv.idx > 0, "Payer is not investor");
uint payValueByTime = now.sub(inv.payTime).getDiffValue(1 hours);
require(payValueByTime > 0, "the payment was earlier than 1 hours");
uint newPayValye = payValueByTime + inv.payValue;
if (newPayValye > maxPayment) {
require(inv.bonus > 0, "you've already got 120%");
sendUserBonus(msg.sender, inv.bonus);
} else {
uint dividendValue = (dividendPercent.getValueByPercent(inv.value) * payValueByTime) / 24;
if (address(this).balance < dividendValue + inv.bonus) {
emit notEnoughETH(now, "not enough Eth at address");
return;
}
emit logPaymentUser(newPayValye, now, msg.sender, 'gotPercent value');
investorsStorage[msg.sender].payValue += payValueByTime;
if (inv.bonus > 0) {
sendDividendsWithBonus(msg.sender, dividendValue, inv.bonus);
} else {
sendDividends(msg.sender, dividendValue);
}
}
}
function sendUserBonus(address addr, uint bonus) private {
addr.transfer(bonus);
investorsStorage[addr].bonus = 0;
emit logPayBonus(bonus, now, addr, "Investor got bonuses!");
}
function setAdvertisingAddress(address addr) public onlyOwner {
advertisingAddress = addr;
}
function sendDividends(address addr, uint value) private {
updatePayTime(addr, now);
emit logPayDividends(value, now, addr, "dividends");
addr.transfer(value);
}
function sendDividendsWithBonus(address addr, uint value, uint bonus) private {
updatePayTime(addr, now);
addr.transfer(value + bonus);
investorsStorage[addr].bonus = 0;
emit logPayDividends(value + bonus, now, addr, "dividends with bonus");
}
function findInvestorByAddress(address addr) internal view returns (User) {
return User(
investorsStorage[addr].idx,
investorsStorage[addr].value,
investorsStorage[addr].bonus,
investorsStorage[addr].payValue,
investorsStorage[addr].payTime
);
}
function sendValueToOwner(uint val) private {
owner.transfer(ownerPercent.getValueByPercent(val));
}
function sendValueToAdv(uint val) private {
advertisingAddress.transfer(advertisingPercent.getValueByPercent(val));
}
function updatePayTime(address addr, uint time) private returns (bool) {
if (investorsStorage[addr].idx == 0) return false;
investorsStorage[addr].payTime = time;
return true;
}
}
library Calc {
function getDiffValue(uint _a, uint _b) internal pure returns (uint) {
require(_b > 0);
uint c = _a / _b;
return c;
}
function sub(uint _a, uint _b) internal pure returns (uint) {
require(_b <= _a);
uint c = _a - _b;
return c;
}
}
library PercentCalc {
struct percent {
uint val;
}
function getValueByPercent(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a * p.val / 100;
}
}
library Zero {
function notZero(address addr) internal pure returns (bool) {
return !(addr == address(0));
}
}
library compileLibrary {
function toAddr(bytes source) internal pure returns (address addr) {
assembly {addr := mload(add(source, 0x14))}
return addr;
}
} | 1 |
pragma solidity ^0.4.25;
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract AbstractToken is Token, SafeMath {
constructor () public {
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
contract PaidThru is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 3000000000 * (10**4);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
constructor () public {
owner = msg.sender;
}
function totalSupply() public constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "PaidThru";
string constant public symbol = "PAID";
uint8 constant public decimals = 4;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value) public
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value) public
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) public {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) public {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event Freeze ();
event Unfreeze ();
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x01575A8F5F9dfdb69b9116E78336c33445B1FD00;
}
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;
contract TempleInterface {
function purchaseFor(address _referredBy, address _customerAddress) public payable returns (uint256);
}
contract TikiMadness {
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
modifier notContract() {
require(tx.origin == msg.sender);
_;
}
modifier notPaused() {
require(now > startTime);
_;
}
modifier easyOnGas() {
require(tx.gasprice < 99999999999);
_;
}
event onTokenSold(
uint256 indexed tokenId,
uint256 price,
address prevOwner,
address newOwner,
string name
);
uint256 private increaseRatePercent = 132;
uint256 private godTikiPercent = 2;
uint256 private devFeePercent = 5;
uint256 private bagHolderFundPercent = 5;
uint256 private exchangeTokenPercent = 10;
uint256 private previousOwnerPercent = 110;
uint256 private priceFallDuration = 1 hours;
mapping (uint256 => address) public tikiIndexToOwner;
mapping (address => uint256) private ownershipTokenCount;
address public contractOwner;
uint256 public startTime = 1543692600;
uint256 public currentDevFee = 0;
address public templeOfEthaddress = 0x0e21902d93573c18fd0acbadac4a5464e9732f54;
TempleInterface public templeContract;
struct TikiMask {
string name;
uint256 basePrice;
uint256 highPrice;
uint256 fallDuration;
uint256 saleTime;
uint256 bagHolderFund;
}
TikiMask [6] public tikiMasks;
constructor () public {
contractOwner = msg.sender;
templeContract = TempleInterface(templeOfEthaddress);
TikiMask memory _Huracan = TikiMask({
name: "Huracan",
basePrice: 0.015 ether,
highPrice: 0.015 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[0] = _Huracan;
TikiMask memory _Itzamna = TikiMask({
name: "Itzamna",
basePrice: 0.018 ether,
highPrice: 0.018 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[1] = _Itzamna;
TikiMask memory _Mitnal = TikiMask({
name: "Mitnal",
basePrice: 0.020 ether,
highPrice: 0.020 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[2] = _Mitnal;
TikiMask memory _Tepeu = TikiMask({
name: "Tepeu",
basePrice: 0.025 ether,
highPrice: 0.025 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[3] = _Tepeu;
TikiMask memory _Usukan = TikiMask({
name: "Usukan",
basePrice: 0.030 ether,
highPrice: 0.030 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[4] = _Usukan;
TikiMask memory _Voltan = TikiMask({
name: "Voltan",
basePrice: 0.035 ether,
highPrice: 0.035 ether,
fallDuration: priceFallDuration,
saleTime: now,
bagHolderFund: 0
});
tikiMasks[5] = _Voltan;
_transfer(0x0, contractOwner, 0);
_transfer(0x0, contractOwner, 1);
_transfer(0x0, contractOwner, 2);
_transfer(0x0, contractOwner, 3);
_transfer(0x0, contractOwner, 4);
_transfer(0x0, contractOwner, 5);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function getTiki(uint256 _tokenId) public view returns (
string tikiName,
uint256 currentPrice,
uint256 basePrice,
address currentOwner,
uint256 bagHolderFund,
bool isBagFundAvailable
) {
TikiMask storage tiki = tikiMasks[_tokenId];
tikiName = tiki.name;
currentPrice = priceOf(_tokenId);
basePrice = tiki.basePrice;
currentOwner = tikiIndexToOwner[_tokenId];
bagHolderFund = tiki.bagHolderFund;
isBagFundAvailable = now > (tiki.saleTime + priceFallDuration);
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = tikiIndexToOwner[_tokenId];
require(owner != address(0));
}
function purchase(uint256 _tokenId , address _referredBy) public payable notContract notPaused easyOnGas {
address oldOwner = tikiIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 currentPrice = priceOf(_tokenId);
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= currentPrice);
uint256 previousOwnerGets = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),previousOwnerPercent);
uint256 exchangeTokensAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),exchangeTokenPercent);
uint256 devFeeAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),devFeePercent);
uint256 bagHolderFundAmount = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),bagHolderFundPercent);
uint256 godTikiGets = SafeMath.mul(SafeMath.div(currentPrice,increaseRatePercent),godTikiPercent);
if (msg.value>currentPrice){
bagHolderFundAmount = bagHolderFundAmount + (msg.value-currentPrice);
}
currentDevFee = currentDevFee + devFeeAmount;
templeContract.purchaseFor.value(exchangeTokensAmount)(_referredBy, msg.sender);
ownerOf(godTiki()).transfer(godTikiGets);
_transfer(oldOwner, newOwner, _tokenId);
tikiMasks[_tokenId].highPrice = SafeMath.mul(SafeMath.div(currentPrice,100),increaseRatePercent);
tikiMasks[_tokenId].saleTime = now;
tikiMasks[_tokenId].bagHolderFund = bagHolderFundAmount + bagHolderFundAmount;
tikiMasks[_tokenId].basePrice = max(tikiMasks[_tokenId].basePrice,SafeMath.div(tikiMasks[_tokenId].bagHolderFund,8));
if (oldOwner != address(this)) {
if (oldOwner.send(previousOwnerGets)){}
}
emit onTokenSold(_tokenId, currentPrice, oldOwner, newOwner, tikiMasks[_tokenId].name);
}
function godTiki() public view returns (uint256 tokenId) {
uint256 lowestPrice = priceOf(0);
uint256 lowestId = 0;
for(uint x=1;x<6;x++){
if(priceOf(x)<lowestPrice){
lowestId=x;
}
}
return lowestId;
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
TikiMask storage tiki = tikiMasks[_tokenId];
uint256 secondsPassed = now - tiki.saleTime;
if (secondsPassed >= tiki.fallDuration || tiki.highPrice==tiki.basePrice) {
return tiki.basePrice;
}
uint256 totalPriceChange = tiki.highPrice - tiki.basePrice;
uint256 currentPriceChange = totalPriceChange * secondsPassed /tiki.fallDuration;
uint256 currentPrice = tiki.highPrice - currentPriceChange;
return currentPrice;
}
function collectBagHolderFund(uint256 _tokenId) public notPaused {
require(msg.sender == tikiIndexToOwner[_tokenId]);
uint256 bagHolderFund;
bool isBagFundAvailable = false;
(
,
,
,
,
bagHolderFund,
isBagFundAvailable
) = getTiki(_tokenId);
require(isBagFundAvailable && bagHolderFund > 0);
uint256 amount = bagHolderFund;
tikiMasks[_tokenId].bagHolderFund = 0;
msg.sender.transfer(amount);
}
function paused() public view returns (bool){
return (now < startTime);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == tikiIndexToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
uint length;
assembly { length := extcodesize(_to) }
require (length == 0);
ownershipTokenCount[_to]++;
tikiIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
}
}
function collectDevFees() public onlyOwner {
if (currentDevFee < address(this).balance){
uint256 amount = currentDevFee;
currentDevFee = 0;
contractOwner.transfer(amount);
}
}
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
}
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;
}
} | 0 |
pragma solidity ^0.4.25;
contract CoinFlash {
address constant private TECH = 0x459ba253E69c77f14a83f61a4a11F068D84bD1e5;
address constant private PROMO = 0x9D643A827dB1768f956fBAEd0616Aaa20F0C99c9;
uint constant public TECH_PERCENT = 3;
uint constant public PROMO_PERCENT = 3;
uint constant public PRIZE_PERCENT = 2;
uint constant public MAX_INVESTMENT = 10 ether;
uint constant public MIN_INVESTMENT_FOR_PRIZE = 0.05 ether;
uint constant public MAX_IDLE_TIME = 20 minutes;
uint8[] MULTIPLIERS = [
111,
113,
117,
121,
125,
130,
135,
141
];
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
struct DepositCount {
int128 stage;
uint128 count;
}
struct LastDepositInfo {
uint128 index;
uint128 time;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
uint public currentQueueSize = 0;
LastDepositInfo public lastDepositInfo;
uint public prizeAmount = 0;
int public stage = 0;
mapping(address => DepositCount) public depositsMade;
function () public payable {
require(tx.gasprice <= 50000000000 wei, "Gas price is too high! Do not cheat!");
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= MAX_INVESTMENT, "The investment is too much!");
checkAndUpdateStage();
require(getStageStartTime(stage+1) >= now + MAX_IDLE_TIME);
addDeposit(msg.sender, msg.value);
pay();
}else if(msg.value == 0 && lastDepositInfo.index > 0 && msg.sender == queue[lastDepositInfo.index].depositor) {
withdrawPrize();
}
}
function pay() private {
uint balance = address(this).balance;
uint128 money = 0;
if(balance > prizeAmount)
money = uint128(balance - prizeAmount);
for(uint i=currentReceiverIndex; i<currentQueueSize; i++){
Deposit storage dep = queue[i];
if(money >= dep.expect){
dep.depositor.transfer(dep.expect);
money -= dep.expect;
delete queue[i];
}else{
dep.depositor.transfer(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex = i;
}
function addDeposit(address depositor, uint value) private {
DepositCount storage c = depositsMade[depositor];
if(c.stage != stage){
c.stage = int128(stage);
c.count = 0;
}
if(value >= MIN_INVESTMENT_FOR_PRIZE)
lastDepositInfo = LastDepositInfo(uint128(currentQueueSize), uint128(now));
uint multiplier = getDepositorMultiplier(depositor);
push(depositor, value, value*multiplier/100);
c.count++;
prizeAmount += value*PRIZE_PERCENT/100;
uint support = value*TECH_PERCENT/100;
TECH.transfer(support);
uint adv = value*PROMO_PERCENT/100;
PROMO.transfer(adv);
}
function checkAndUpdateStage() private{
int _stage = getCurrentStageByTime();
require(_stage >= stage, "We should only go forward in time");
if(_stage != stage){
proceedToNewStage(_stage);
}
}
function proceedToNewStage(int _stage) private {
stage = _stage;
currentQueueSize = 0;
currentReceiverIndex = 0;
delete lastDepositInfo;
}
function withdrawPrize() private {
require(lastDepositInfo.time > 0 && lastDepositInfo.time <= now - MAX_IDLE_TIME, "The last depositor is not confirmed yet");
require(currentReceiverIndex <= lastDepositInfo.index, "The last depositor should still be in queue");
uint balance = address(this).balance;
if(prizeAmount > balance)
prizeAmount = balance;
uint prize = prizeAmount;
queue[lastDepositInfo.index].depositor.transfer(prize);
prizeAmount = 0;
proceedToNewStage(stage + 1);
}
function push(address depositor, uint deposit, uint expect) private {
Deposit memory dep = Deposit(depositor, uint128(deposit), uint128(expect));
assert(currentQueueSize <= queue.length);
if(queue.length == currentQueueSize)
queue.push(dep);
else
queue[currentQueueSize] = dep;
currentQueueSize++;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<currentQueueSize; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return currentQueueSize - currentReceiverIndex;
}
function getDepositorMultiplier(address depositor) public view returns (uint) {
DepositCount storage c = depositsMade[depositor];
uint count = 0;
if(c.stage == getCurrentStageByTime())
count = c.count;
if(count < MULTIPLIERS.length)
return MULTIPLIERS[count];
return MULTIPLIERS[MULTIPLIERS.length - 1];
}
function getCurrentStageByTime() public view returns (int) {
return int(now - 12 hours) / 1 days - 17847;
}
function getStageStartTime(int _stage) public pure returns (uint) {
return 12 hours + uint(_stage + 17847)*1 days;
}
function getCurrentCandidateForPrize() public view returns (address addr, int timeLeft){
if(currentReceiverIndex <= lastDepositInfo.index && lastDepositInfo.index < currentQueueSize){
Deposit storage d = queue[lastDepositInfo.index];
addr = d.depositor;
timeLeft = int(lastDepositInfo.time + MAX_IDLE_TIME) - int(now);
}
}
} | 1 |
pragma solidity ^0.4.19;
interface tokenRecipient {
function receiveApproval( address from, uint256 value, bytes data ) public;
}
interface ContractReceiver {
function tokenFallback( address from, uint value, bytes data ) public;
}
contract ERC223Token
{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping( address => uint256 ) balances_;
mapping( address => mapping(address => uint256) ) allowances_;
event Approval( address indexed owner,
address indexed spender,
uint value );
event Transfer( address indexed from,
address indexed to,
uint256 value,
bytes data );
event Burn( address indexed from, uint256 value );
function ERC223Token( uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol ) public
{
totalSupply = initialSupply * 10 ** uint256(decimalUnits);
balances_[msg.sender] = totalSupply;
name = tokenName;
decimals = decimalUnits;
symbol = tokenSymbol;
}
function() public payable { revert(); }
function balanceOf( address owner ) public constant returns (uint) {
return balances_[owner];
}
function approve( address spender, uint256 value ) public
returns (bool success)
{
allowances_[msg.sender][spender] = value;
Approval( msg.sender, spender, value );
return true;
}
function allowance( address owner, address spender ) public constant
returns (uint256 remaining)
{
return allowances_[owner][spender];
}
function transfer(address to, uint256 value) public
{
bytes memory empty;
_transfer( msg.sender, to, value, empty );
}
function transferFrom( address from, address to, uint256 value ) public
returns (bool success)
{
require( value <= allowances_[from][msg.sender] );
allowances_[from][msg.sender] -= value;
bytes memory empty;
_transfer( from, to, value, empty );
return true;
}
function approveAndCall( address spender,
uint256 value,
bytes context ) public
returns (bool success)
{
if ( approve(spender, value) )
{
tokenRecipient recip = tokenRecipient( spender );
recip.receiveApproval( msg.sender, value, context );
return true;
}
return false;
}
function burn( uint256 value ) public
returns (bool success)
{
require( balances_[msg.sender] >= value );
balances_[msg.sender] -= value;
totalSupply -= value;
Burn( msg.sender, value );
return true;
}
function burnFrom( address from, uint256 value ) public
returns (bool success)
{
require( balances_[from] >= value );
require( value <= allowances_[from][msg.sender] );
balances_[from] -= value;
allowances_[from][msg.sender] -= value;
totalSupply -= value;
Burn( from, value );
return true;
}
function transfer( address to,
uint value,
bytes data,
string custom_fallback ) public returns (bool success)
{
_transfer( msg.sender, to, value, data );
if ( isContract(to) )
{
ContractReceiver rx = ContractReceiver( to );
require( rx.call.value(0)(bytes4(keccak256(custom_fallback)),
msg.sender,
value,
data) );
}
return true;
}
function transfer( address to, uint value, bytes data ) public
returns (bool success)
{
if (isContract(to)) {
return transferToContract( to, value, data );
}
_transfer( msg.sender, to, value, data );
return true;
}
function transferToContract( address to, uint value, bytes data ) private
returns (bool success)
{
_transfer( msg.sender, to, value, data );
ContractReceiver rx = ContractReceiver(to);
rx.tokenFallback( msg.sender, value, data );
return true;
}
function isContract( address _addr ) private constant returns (bool)
{
uint length;
assembly { length := extcodesize(_addr) }
return (length > 0);
}
function _transfer( address from,
address to,
uint value,
bytes data ) internal
{
require( to != 0x0 );
require( balances_[from] >= value );
require( balances_[to] + value > balances_[to] );
balances_[from] -= value;
balances_[to] += value;
Transfer( from, to, value, data );
}
} | 1 |
pragma solidity ^0.4.24;
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns(uint256);
function getPlayerName(uint256 _pID) external view returns(bytes32);
function getPlayerLAff(uint256 _pID) external view returns(uint256);
function getPlayerAddr(uint256 _pID) external view returns(address);
function getNameFee() external view returns(uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
interface TeamPerfitForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address);
}
interface DRSCoinInterface {
function mint(address _to, uint256 _amount) external;
function profitEth() external payable;
}
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) {
assert(b > 0);
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 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 DRSDatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 genAmount;
uint256 potAmount;
address genAddr;
uint256 genKeyPrice;
}
function setNewPlayerFlag(EventReturns _event) internal pure returns(EventReturns) {
_event.compressedData = _event.compressedData + 1;
return _event;
}
function setJoinedRoundFlag(EventReturns _event) internal pure returns(EventReturns) {
_event.compressedData = _event.compressedData + 10;
return _event;
}
function setNewLeaderFlag(EventReturns _event) internal pure returns(EventReturns) {
_event.compressedData = _event.compressedData + 100;
return _event;
}
function setRoundEndTime(EventReturns _event, uint256 roundEndTime) internal pure returns(EventReturns) {
_event.compressedData = _event.compressedData + roundEndTime * (10**3);
return _event;
}
function setTimestamp(EventReturns _event, uint256 timestamp) internal pure returns(EventReturns) {
_event.compressedData = _event.compressedData + timestamp * (10**14);
return _event;
}
function setPID(EventReturns _event, uint256 _pID) internal pure returns(EventReturns) {
_event.compressedIDs = _event.compressedIDs + _pID;
return _event;
}
function setWinPID(EventReturns _event, uint256 _winPID) internal pure returns(EventReturns) {
_event.compressedIDs = _event.compressedIDs + (_winPID * (10**26));
return _event;
}
function setRID(EventReturns _event, uint256 _rID) internal pure returns(EventReturns) {
_event.compressedIDs = _event.compressedIDs + (_rID * (10**52));
return _event;
}
function setWinner(EventReturns _event, address _winnerAddr, bytes32 _winnerName, uint256 _amountWon)
internal pure returns(EventReturns) {
_event.winnerAddr = _winnerAddr;
_event.winnerName = _winnerName;
_event.amountWon = _amountWon;
return _event;
}
function setGenInfo(EventReturns _event, address _genAddr, uint256 _genKeyPrice)
internal pure returns(EventReturns) {
_event.genAddr = _genAddr;
_event.genKeyPrice = _genKeyPrice;
}
function setNewPot(EventReturns _event, uint256 _newPot) internal pure returns(EventReturns) {
_event.newPot = _newPot;
return _event;
}
function setGenAmount(EventReturns _event, uint256 _genAmount) internal pure returns(EventReturns) {
_event.genAmount = _genAmount;
return _event;
}
function setPotAmount(EventReturns _event, uint256 _potAmount) internal pure returns(EventReturns) {
_event.potAmount = _potAmount;
return _event;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 lrnd;
}
struct PlayerRound {
uint256 eth;
uint256 keys;
}
struct Round {
uint256 plyr;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
}
struct BuyInfo {
address addr;
bytes32 name;
uint256 pid;
uint256 keyPrice;
uint256 keyIndex;
}
}
contract DRSEvents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keyIndex,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount,
address genAddr,
uint256 genKeyPrice
);
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 onBuyKeyFailure
(
uint256 roundID,
uint256 indexed playerID,
uint256 amount,
uint256 keyPrice,
uint256 timeStamp
);
}
contract ReserveBag is DRSEvents {
using SafeMath for uint256;
using NameFilter for string;
using DRSDatasets for DRSDatasets.EventReturns;
TeamPerfitForwarderInterface public teamPerfit;
PlayerBookInterface public playerBook;
DRSCoinInterface public drsCoin;
string constant public name = "Reserve Bag";
string constant public symbol = "RB";
uint256 constant private initKeyPrice = (10**18);
uint256 private rndExtra_ = 0;
uint256 private rndGap_ = 0;
uint256 constant private rndMax_ = 24 hours;
uint256 public rID_;
uint256 public keyPrice = initKeyPrice;
uint256 public keyBought = 0;
address public owner;
uint256 public teamPerfitAmuont = 0;
uint256 public rewardInternal = 36;
uint256 public keyPriceIncreaseRatio = 8;
uint256 public genRatio = 90;
uint256 public drsCoinDividendRatio = 40;
uint256 public teamPerfitRatio = 5;
uint256 public ethMintDRSCoinRate = 100;
bool public activated_ = false;
mapping(address => uint256) public pIDxAddr_;
mapping(bytes32 => uint256) public pIDxName_;
mapping(uint256 => DRSDatasets.Player) public plyr_;
mapping(uint256 => mapping(uint256 => DRSDatasets.PlayerRound)) public plyrRnds_;
mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_;
DRSDatasets.BuyInfo[] buyinfos;
uint256 private startIndex;
uint256 private endIndex;
mapping(uint256 => DRSDatasets.Round) public round_;
constructor(address _teamPerfit, address _playBook, address _drsCoin) public
{
owner = msg.sender;
teamPerfit = TeamPerfitForwarderInterface(_teamPerfit);
playerBook = PlayerBookInterface(_playBook);
drsCoin = DRSCoinInterface(_drsCoin);
startIndex = 0;
endIndex = 0;
}
modifier onlyOwner {
assert(owner == msg.sender);
_;
}
modifier isHuman() {
address _addr = msg.sender;
require(_addr == tx.origin);
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000 * (10**18), "no vitalik, no");
_;
}
function pushBuyInfo(DRSDatasets.BuyInfo info) internal {
if(endIndex == buyinfos.length) {
buyinfos.push(info);
} else if(endIndex < buyinfos.length) {
buyinfos[endIndex] = info;
} else {
revert();
}
endIndex = (endIndex + 1) % (rewardInternal + 1);
if(endIndex == startIndex) {
startIndex = (startIndex + 1) % (rewardInternal + 1);
}
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
DRSDatasets.EventReturns memory _eventData_;
_eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, _eventData_);
}
function buyKey()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
DRSDatasets.EventReturns memory _eventData_;
_eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, _eventData_);
}
function reLoadXaddr(uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
uint256 _pID = pIDxAddr_[msg.sender];
require(_pID != 0, "reLoadXaddr can not be called by new players");
DRSDatasets.EventReturns memory _eventData_;
reLoadCore(_pID, _eth, _eventData_);
}
function withdrawTeamPerfit()
isActivated()
onlyOwner()
public
{
if(teamPerfitAmuont > 0) {
uint256 _perfit = teamPerfitAmuont;
teamPerfitAmuont = 0;
owner.transfer(_perfit);
}
}
function getTeamPerfitAmuont() public view returns(uint256) {
return teamPerfitAmuont;
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _pID = pIDxAddr_[msg.sender];
require(_pID != 0, "withdraw can not be called by new players");
uint256 _rID = rID_;
uint256 _now = now;
uint256 _eth;
if(_now > round_[_rID].end && !round_[_rID].ended && round_[_rID].plyr != 0)
{
DRSDatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if(_eth > 0) {
plyr_[_pID].addr.transfer(_eth);
}
_eventData_ = _eventData_.setTimestamp(_now);
_eventData_ = _eventData_.setPID(_pID);
emit DRSEvents.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 DRSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerName(string _nameString, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, ) = playerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, address(0), _all);
uint256 _pID = pIDxAddr_[_addr];
emit DRSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _paid, now);
}
function getBuyPrice() public view returns(uint256)
{
return keyPrice;
}
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 _rID = rID_;
uint256 _now = now;
if(_now > round_[_rID].end && !round_[_rID].ended && round_[_rID].plyr != 0) {
if(round_[_rID].plyr == _pID) {
return
(
(plyr_[_pID].win).add(getWin(round_[_rID].pot)),
plyr_[_pID].gen
);
}
}
return (plyr_[_pID].win, plyr_[_pID].gen);
}
function getCurrentRoundInfo() public view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
return
(
_rID,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
keyPrice,
keyBought.add(1),
_winPID,
plyr_[_winPID].addr,
plyr_[_winPID].name
);
}
function getPlayerInfoByAddress(address _addr) public view
returns(uint256, bytes32, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if(_addr == address(0)) {
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
if(_pID == 0) {
return (0, "", 0, 0, 0, 0);
}
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
plyr_[_pID].gen,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, DRSDatasets.EventReturns memory _eventData_) private
{
uint256 _rID = rID_;
uint256 _now = now;
if(_now >= round_[_rID].strt.add(rndGap_) && (_now <= round_[_rID].end || round_[_rID].plyr == 0)) {
core(_rID, _pID, msg.value, _eventData_);
} else {
if(_now > round_[_rID].end && !round_[_rID].ended) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_ = _eventData_.setTimestamp(_now);
_eventData_ = _eventData_.setPID(_pID);
emit DRSEvents.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 _eth, DRSDatasets.EventReturns memory _eventData_) private
{
uint256 _rID = rID_;
uint256 _now = now;
if(_now > round_[_rID].strt.add(rndGap_) && (_now <= round_[_rID].end || round_[_rID].plyr == 0)) {
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _eventData_);
} else {
if(_now > round_[_rID].end && !round_[_rID].ended) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_ = _eventData_.setTimestamp(_now);
_eventData_ = _eventData_.setPID(_pID);
emit DRSEvents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, DRSDatasets.EventReturns memory _eventData_) private
{
if(_eth < keyPrice) {
plyr_[_pID].gen = plyr_[_pID].gen.add(_eth);
emit onBuyKeyFailure(_rID, _pID, _eth, keyPrice, now);
return;
}
if(plyrRnds_[_pID][_rID].keys == 0) {
_eventData_ = managePlayer(_pID, _eventData_);
}
uint256 _keys = 1;
uint256 _ethUsed = keyPrice;
uint256 _ethLeft = _eth.sub(keyPrice);
updateTimer(_rID);
if(round_[_rID].plyr != _pID) {
round_[_rID].plyr = _pID;
}
_eventData_ = _eventData_.setNewLeaderFlag();
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _ethUsed.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _ethUsed.add(round_[_rID].eth);
uint256 _ethExt = distributeExternal(_ethUsed);
_eventData_ = distributeInternal(_rID, _ethUsed, _ethExt, _eventData_);
bytes32 _name = plyr_[_pID].name;
pushBuyInfo(DRSDatasets.BuyInfo(msg.sender, _name, _pID, keyPrice, keyBought));
uint256 _keyIndex = keyBought;
keyBought = keyBought.add(1);
keyPrice = keyPrice.mul(1000 + keyPriceIncreaseRatio).div(1000);
if(_ethLeft > 0) {
plyr_[_pID].gen = _ethLeft.add(plyr_[_pID].gen);
}
endTx(_pID, _ethUsed, _keyIndex, _eventData_);
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name) external
{
require(msg.sender == address(playerBook), "your not playerNames contract.");
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(!plyrNames_[_pID][_name])
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name) external
{
require(msg.sender == address(playerBook), "your not playerNames contract.");
if(!plyrNames_[_pID][_name])
plyrNames_[_pID][_name] = true;
}
function determinePID(DRSDatasets.EventReturns memory _eventData_) private returns(DRSDatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if(_pID == 0)
{
_pID = playerBook.getPlayerID(msg.sender);
bytes32 _name = playerBook.getPlayerName(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if(_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
_eventData_ = _eventData_.setNewPlayerFlag();
}
return _eventData_;
}
function managePlayer(uint256 _pID, DRSDatasets.EventReturns memory _eventData_)
private
returns(DRSDatasets.EventReturns)
{
plyr_[_pID].lrnd = rID_;
_eventData_ = _eventData_.setJoinedRoundFlag();
return _eventData_;
}
function getWin(uint256 _pot) private pure returns(uint256) {
return _pot / 2;
}
function getDRSCoinDividend(uint256 _pot) private view returns(uint256) {
return _pot.mul(drsCoinDividendRatio).div(100);
}
function getTeamPerfit(uint256 _pot) private view returns(uint256) {
return _pot.mul(teamPerfitRatio).div(100);
}
function mintDRSCoin() private {
if(startIndex == endIndex) {
return;
}
if((startIndex + 1) % (rewardInternal + 1) == endIndex) {
return;
}
for(uint256 i = startIndex; (i + 1) % (rewardInternal + 1) != endIndex; i = (i + 1) % (rewardInternal + 1)) {
drsCoin.mint(buyinfos[i].addr, buyinfos[i].keyPrice.mul(ethMintDRSCoinRate).div(100));
}
}
function endRound(DRSDatasets.EventReturns memory _eventData_)
private
returns(DRSDatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _pot = round_[_rID].pot;
uint256 _win = getWin(_pot);
uint256 _drsCoinDividend = getDRSCoinDividend(_pot);
uint256 _com = getTeamPerfit(_pot);
uint256 _newPot = _pot.sub(_win).sub(_drsCoinDividend).sub(_com);
depositTeamPerfit(_com);
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
mintDRSCoin();
drsCoin.profitEth.value(_drsCoinDividend)();
_eventData_ = _eventData_.setRoundEndTime(round_[_rID].end);
_eventData_ = _eventData_.setWinPID(_winPID);
_eventData_ = _eventData_.setWinner(plyr_[_winPID].addr, plyr_[_winPID].name, _win);
_eventData_ = _eventData_.setNewPot(_newPot);
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndMax_).add(rndGap_);
keyPrice = initKeyPrice;
keyBought = 0;
startIndex = 0;
endIndex = 0;
round_[_rID].pot = _newPot;
return _eventData_;
}
function updateTimer(uint256 _rID) private
{
uint256 keys = round_[_rID].keys;
uint256 keyDuration = rndMax_;
if(keys < 50) {
keyDuration = rndMax_;
} else if(keys < 100) {
keyDuration = rndMax_ / 2;
} else if(keys < 150) {
keyDuration = rndMax_ / 4;
} else {
keyDuration = rndMax_ / 8;
}
round_[_rID].end = keyDuration.add(now);
}
function depositTeamPerfit(uint256 _eth) private {
if(teamPerfit == address(0)) {
teamPerfitAmuont = teamPerfitAmuont.add(_eth);
return;
}
bool res = teamPerfit.deposit.value(_eth)();
if(!res) {
teamPerfitAmuont = teamPerfitAmuont.add(_eth);
return;
}
}
function distributeExternal(uint256 _eth) private returns(uint256)
{
uint256 _com = _eth / 50;
depositTeamPerfit(_com);
return _com;
}
function distributeInternal(uint256 _rID, uint256 _eth, uint256 _ethExt, DRSDatasets.EventReturns memory _eventData_)
private
returns(DRSDatasets.EventReturns)
{
uint256 _gen = 0;
uint256 _pot = 0;
if(keyBought < rewardInternal) {
_gen = 0;
_pot = _eth.sub(_ethExt);
} else {
_gen = _eth.mul(genRatio).div(100);
_pot = _eth.sub(_ethExt).sub(_gen);
DRSDatasets.BuyInfo memory info = buyinfos[startIndex];
uint256 firstPID = info.pid;
plyr_[firstPID].gen = _gen.add(plyr_[firstPID].gen);
_eventData_.setGenInfo(info.addr, info.keyPrice);
}
if(_pot > 0) {
round_[_rID].pot = _pot.add(round_[_rID].pot);
}
_eventData_.setGenAmount(_gen.add(_eventData_.genAmount));
_eventData_.setPotAmount(_pot);
return _eventData_;
}
function withdrawEarnings(uint256 _pID) private returns(uint256)
{
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen);
if(_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
}
return _earnings;
}
function endTx(uint256 _pID, uint256 _eth, uint256 _keyIndex, DRSDatasets.EventReturns memory _eventData_) private
{
_eventData_ = _eventData_.setTimestamp(now);
_eventData_ = _eventData_.setPID(_pID);
_eventData_ = _eventData_.setRID(rID_);
emit DRSEvents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keyIndex,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount,
_eventData_.genAddr,
_eventData_.genKeyPrice
);
}
modifier isActivated() {
require(activated_, "its not activated yet.");
_;
}
function activate() onlyOwner() public
{
require(!activated_, "ReserveBag already activated");
uint256 _now = now;
activated_ = true;
rID_ = 1;
round_[1].strt = _now.add(rndExtra_).sub(rndGap_);
round_[1].end = _now.add(rndMax_).add(rndExtra_);
}
function getActivated() public view returns(bool) {
return activated_;
}
function setTeamPerfitAddress(address _newTeamPerfitAddress) onlyOwner() public {
teamPerfit = TeamPerfitForwarderInterface(_newTeamPerfitAddress);
}
function setPlayerBookAddress(address _newPlayerBookAddress) onlyOwner() public {
playerBook = PlayerBookInterface(_newPlayerBookAddress);
}
function setDRSCoinAddress(address _newDRSCoinAddress) onlyOwner() public {
drsCoin = DRSCoinInterface(_newDRSCoinAddress);
}
} | 0 |
pragma solidity ^0.4.18;
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract 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) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier onlySaleAgent() {
require(msg.sender == saleAgent);
_;
}
function setSaleAgent(address newSaleAgent) public onlyOwner {
saleAgent = newSaleAgent;
}
function mint(address _to, uint256 _amount) public onlySaleAgent canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public onlySaleAgent returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract AgroTechFarmToken is MintableToken {
string public constant name = "Agro Tech Farm";
string public constant symbol = "ATF";
uint32 public constant decimals = 18;
}
contract preSale3 is Ownable {
using SafeMath for uint;
AgroTechFarmToken public token;
bool public preSale3Finished = false;
string public constant name = "ATF Token";
address public multisig;
address public preSale = 0x02Dcc61022771015b1408323D29C790066CBe2e4;
address public preSale1 = 0xfafbb19945fc2d79828e4c5813a619d5683074ba;
address public preSale2 = 0x62451D37Ca2EC1f0499996Bc3C7e2BAF258E9729;
uint public rate;
uint public start;
uint public end;
uint public hardcap;
address public restricted;
uint public restrictedPercent;
function preSale3() public {
token = AgroTechFarmToken(0xa55ffAeA5c8cf32B550F663bf17d4F7b739534ff);
multisig = 0x227917ac3C1F192874d43031cF4D40fd40Ae6127;
rate = 83333333333000000000;
start = 1520640000;
end = 1522047600;
hardcap = 500000000000000000000;
restricted = 0xbcCd749ecCCee5B4898d0E38D2a536fa84Ea9Ef6;
restrictedPercent = 35;
}
modifier saleIsOn() {
require(now > start && now < end);
_;
}
modifier isUnderHardCap() {
require(this.balance <= hardcap);
_;
}
function balancePreSale3() public constant returns (uint) {
return this.balance;
}
function finishPreSale3() public onlyOwner returns (bool) {
if(now > end || this.balance >= hardcap) {
multisig.transfer(this.balance);
preSale3Finished = true;
return true;
} else return false;
}
function createTokens() public isUnderHardCap saleIsOn payable {
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = tokens.mul(35).div(100);
tokens += bonusTokens;
token.mint(msg.sender, tokens);
uint restrictedTokens = tokens.mul(restrictedPercent).div(100);
token.mint(restricted, restrictedTokens);
}
function() external payable {
createTokens();
}
} | 1 |
pragma solidity 0.4.25;
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 view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view 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 memory data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned2() 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 NEUTRO 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;
constructor () public {
symbol = "NTO";
name = "NEUTRO";
decimals = 18;
_totalSupply = 20000000000000000000000000;
balances[0x5F8C6d055FaB4893e50e0e3c992449d3e0e00e5d] = _totalSupply;
emit Transfer(address(0), 0x5F8C6d055FaB4893e50e0e3c992449d3e0e00e5d, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - 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] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], 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] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], 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 () 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 HashBet {
constructor() public {}
event Result(uint256 hashVal, uint16 result);
mapping( address => Bet ) bets;
struct Bet {
uint value;
uint height;
}
function() payable public {}
function makeBet() payable public {
require( bets[msg.sender].height == 0 && msg.value > 10000 );
Bet newBet = bets[msg.sender];
newBet.value = msg.value;
newBet.height = block.number;
}
function resolveBet() public {
Bet bet = bets[msg.sender];
uint dist = block.number - bet.height;
require( dist < 255 && dist > 3 );
bytes32 h1 = block.blockhash(bet.height);
bytes32 h2 = block.blockhash(bet.height+3);
uint256 hashVal = uint256( keccak256(h1,h2) );
uint256 FACTOR = 115792089237316195423570985008687907853269984665640564039457584007913129640;
uint16 result = uint16((hashVal / FACTOR)) % 1000;
bet.height = 0;
if( result <= 495 ) {
msg.sender.transfer(address(this).balance);
}
emit Result(hashVal, result);
}
} | 1 |
pragma solidity ^0.4.18;
contract SafeMath {
function mulSafe(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function divSafe(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function subSafe(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function addSafe(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function 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);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
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 ERC223 {
function transfer(address to, uint value, bytes data) public;
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract StandardToken is ERC20, ERC223, SafeMath, Owned {
event ReleaseSupply(address indexed receiver, uint256 value, uint256 releaseTime);
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = subSafe(balances[msg.sender], _value);
balances[_to] = addSafe(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = subSafe(balances[_from], _value);
balances[_to] = addSafe(balances[_to], _value);
allowed[_from][msg.sender] = subSafe(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = addSafe(allowed[msg.sender][_spender], _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = subSafe(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transfer(address _to, uint _value, bytes _data) public {
require(_value > 0 );
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = subSafe(balances[msg.sender], _value);
balances[_to] = addSafe(balances[_to], _value);
Transfer(msg.sender, _to, _value, _data);
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
}
contract TBToken is StandardToken {
string public name = 'TBToken';
string public symbol = 'TB';
uint public decimals = 18;
uint256 public createTime = 1527436800;
uint256 public bonusEnds = 1528646400;
uint256 public endDate = 1529078400;
uint256 firstAnnual = 1559318400;
uint256 secondAnnual = 1590940800;
uint256 thirdAnnual = 1622476800;
uint256 public INITIAL_SUPPLY = 1000000000;
uint256 public frozenForever = 400000000;
uint256 firstAnnualReleasedAmount = 150000000;
uint256 secondAnnualReleasedAmount= 150000000;
uint256 thirdAnnualReleasedAmount = 100000000;
function TBToken() public {
totalSupply = 200000000 ;
balances[msg.sender] = totalSupply * 10 ** uint256(decimals);
owner = msg.sender;
}
function releaseSupply() public onlyOwner returns(uint256 _actualRelease) {
uint256 releaseAmount = getReleaseAmount();
require(releaseAmount > 0);
balances[owner] = addSafe(balances[owner], releaseAmount * 10 ** uint256(decimals));
totalSupply = addSafe(totalSupply, releaseAmount);
Transfer(address(0), msg.sender, releaseAmount);
return releaseAmount;
}
function getReleaseAmount() internal returns(uint256 _actualRelease) {
uint256 _amountToRelease;
if ( now >= firstAnnual
&& now < secondAnnual
&& firstAnnualReleasedAmount > 0) {
_amountToRelease = firstAnnualReleasedAmount;
firstAnnualReleasedAmount = 0;
} else if ( now >= secondAnnual
&& now < thirdAnnual
&& secondAnnualReleasedAmount > 0) {
_amountToRelease = secondAnnualReleasedAmount;
secondAnnualReleasedAmount = 0;
} else if ( now >= thirdAnnual
&& thirdAnnualReleasedAmount > 0) {
_amountToRelease = thirdAnnualReleasedAmount;
thirdAnnualReleasedAmount = 0;
} else {
_amountToRelease = 0;
}
return _amountToRelease;
}
function () public payable {
require(now >= createTime && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 2480;
} else {
tokens = msg.value * 2000;
}
require(tokens <= balances[owner]);
balances[msg.sender] = addSafe(balances[msg.sender], tokens);
balances[owner] = subSafe(balances[owner], tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
} | 0 |
pragma solidity ^0.4.17;
contract AvPresale {
string public constant RELEASE = "0.2.1_AviaTest";
uint public constant PRESALE_START = 5298043;
uint public constant PRESALE_END = 5303803;
uint public constant WITHDRAWAL_END = 5309563;
address public constant OWNER = 0x32Bac79f4B6395DEa37f0c2B68b6e26ce24a59EA;
uint public constant MIN_TOTAL_AMOUNT_GET_ETH = 1;
uint public constant MAX_TOTAL_AMOUNT_GET_ETH = 2;
uint public constant MIN_GET_AMOUNT_FINNEY = 10;
string[5] private standingNames = ["BEFORE_START", "PRESALE_RUNNING", "WITHDRAWAL_RUNNING", "MONEY_BACK_RUNNING", "CLOSED" ];
enum State { BEFORE_START, PRESALE_RUNNING, WITHDRAWAL_RUNNING, MONEY_BACK_RUNNING, CLOSED }
uint public total_amount = 0;
uint public total_money_back = 0;
mapping (address => uint) public balances;
uint private constant MIN_TOTAL_AMOUNT_GET = MIN_TOTAL_AMOUNT_GET_ETH * 1 ether;
uint private constant MAX_TOTAL_AMOUNT_GET = MAX_TOTAL_AMOUNT_GET_ETH * 1 ether;
uint private constant MIN_GET_AMOUNT = MIN_GET_AMOUNT_FINNEY * 1 finney;
bool public isTerminated = false;
bool public isStopped = false;
function AvPresale () public checkSettings() { }
function sendMoneyOwner() external
inStanding(State.WITHDRAWAL_RUNNING)
onlyOwner
noReentrancy
{
OWNER.transfer(this.balance);
}
function moneyBack() external
inStanding(State.MONEY_BACK_RUNNING)
noReentrancy
{
sendMoneyBack();
}
function ()
payable
noReentrancy
public
{
State state = currentStanding();
if (state == State.PRESALE_RUNNING) {
getMoney();
} else if (state == State.MONEY_BACK_RUNNING) {
sendMoneyBack();
} else {
revert();
}
}
function termination() external
inStandingBefore(State.MONEY_BACK_RUNNING)
onlyOwner
{
isTerminated = true;
}
function stop() external
inStanding(State.PRESALE_RUNNING)
onlyOwner
{
isStopped = true;
}
function standing() external constant
returns (string)
{
return standingNames[ uint(currentStanding()) ];
}
function getMoney() private notTooSmallAmountOnly {
if (total_amount + msg.value > MAX_TOTAL_AMOUNT_GET) {
var change_to_return = total_amount + msg.value - MAX_TOTAL_AMOUNT_GET;
var acceptable_remainder = MAX_TOTAL_AMOUNT_GET - total_amount;
balances[msg.sender] += acceptable_remainder;
total_amount += acceptable_remainder;
msg.sender.transfer(change_to_return);
} else {
balances[msg.sender] += msg.value;
total_amount += msg.value;
}
}
function sendMoneyBack() private tokenHoldersOnly {
uint amount_to_money_back = min(balances[msg.sender], this.balance - msg.value) ;
balances[msg.sender] -= amount_to_money_back;
total_money_back += amount_to_money_back;
msg.sender.transfer(amount_to_money_back + msg.value);
}
function currentStanding() private constant returns (State) {
if (isTerminated) {
return this.balance > 0
? State.MONEY_BACK_RUNNING
: State.CLOSED;
} else if (block.number < PRESALE_START) {
return State.BEFORE_START;
} else if (block.number <= PRESALE_END && total_amount < MAX_TOTAL_AMOUNT_GET && !isStopped) {
return State.PRESALE_RUNNING;
} else if (this.balance == 0) {
return State.CLOSED;
} else if (block.number <= WITHDRAWAL_END && total_amount >= MIN_TOTAL_AMOUNT_GET) {
return State.WITHDRAWAL_RUNNING;
} else {
return State.MONEY_BACK_RUNNING;
}
}
function min(uint a, uint b) pure private returns (uint) {
return a < b ? a : b;
}
modifier inStanding(State state) {
require(state == currentStanding());
_;
}
modifier inStandingBefore(State state) {
require(currentStanding() < state);
_;
}
modifier tokenHoldersOnly(){
require(balances[msg.sender] > 0);
_;
}
modifier notTooSmallAmountOnly(){
require(msg.value >= MIN_GET_AMOUNT);
_;
}
bool private lock = false;
modifier noReentrancy() {
require(!lock);
lock = true;
_;
lock = false;
}
modifier checkSettings() {
if ( OWNER == 0x0
|| PRESALE_START == 0
|| PRESALE_END == 0
|| WITHDRAWAL_END ==0
|| PRESALE_START <= block.number
|| PRESALE_START >= PRESALE_END
|| PRESALE_END >= WITHDRAWAL_END
|| MIN_TOTAL_AMOUNT_GET > MAX_TOTAL_AMOUNT_GET )
revert();
_;
}
modifier onlyOwner(){
require(msg.sender == OWNER);
_;
}
} | 1 |
pragma solidity ^0.4.24;
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);
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 Moon3DToken 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;
constructor() public {
symbol = "M3D";
name = "Moon3D.io Crypto Game";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x10A319Fc5b48EAa393f711a75DfC77FC4373a095] = _totalSupply;
emit Transfer(address(0), 0x10A319Fc5b48EAa393f711a75DfC77FC4373a095, _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);
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] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit 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;
emit 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.25;
contract Simply {
mapping (address => uint256) dates;
mapping (address => uint256) invests;
function() external payable {
address sender = msg.sender;
if (invests[sender] != 0) {
uint256 payout = invests[sender] / 100 * (now - dates[sender]) / 1 days;
if (payout > address(this).balance) {
payout = address(this).balance;
}
sender.transfer(payout);
}
dates[sender] = now;
invests[sender] += msg.value;
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal 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 TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public {
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
}
contract SimpleVesting is TokenVesting {
function SimpleVesting(address _beneficiary) TokenVesting(
_beneficiary,
1546300800,
0,
0,
false
)
{}
} | 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 GayBananaToken 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 GayBananaToken() public {
symbol = "GNA";
name = "Gay Banana Token";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x127094b40d413Ed499d460bcDd46ff0c55071C75] = _totalSupply;
Transfer(address(0), 0x127094b40d413Ed499d460bcDd46ff0c55071C75, _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 = 27302400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x79491a66c6c74D95284b3EA80961fe022088D9Ae;
}
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 = 0x8bc145AE40194d558Aa476A57f7d666Dba7Fe7b5;
}
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 tokenRecipient {
function receiveApproval(address _from,
uint256 _value,
address _share,
bytes _extraData);
}
contract Corporation {
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address[] public shareholder;
mapping (address => uint256) public shareholderID;
address[] activeShareholdersArray;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function Corporation () {
uint256 initialSupply = 12000;
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = "shares";
symbol = "sh";
decimals = 0;
shareholderID[this] = shareholder.push(this)-1;
shareholderID[msg.sender] = shareholder.push(msg.sender)-1;
activeShareholdersArray.push(msg.sender);
}
event Transfer(address indexed from, address indexed to, uint256 value);
function getCurrentShareholders() returns (address[]){
delete activeShareholdersArray;
for (uint256 i=0; i < shareholder.length; i++){
if (balanceOf[shareholder[i]] > 0){
activeShareholdersArray.push(shareholder[i]);
}
} return activeShareholdersArray;
}
function getBalanceByAdress(address _address) returns (uint256) {
return balanceOf[_address];
}
function getMyShareholderID() returns (uint256) {
return shareholderID[msg.sender];
}
function getShareholderAdressByID(uint256 _id) returns (address){
return shareholder[_id];
}
function getMyShares() returns (uint256) {
return balanceOf[msg.sender];
}
function transfer(address _to, uint256 _value) {
if (_value < 1) throw;
if (this == _to) throw;
if (balanceOf[msg.sender] < _value) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
if (shareholderID[_to] == 0){
shareholderID[_to] = shareholder.push(_to)-1;
}
Transfer(msg.sender, _to, _value);
}
function approveAndCall(address _spender,
uint256 _value,
bytes _extraData)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
spender.receiveApproval(msg.sender,
_value,
this,
_extraData);
return true;
}
function transferFrom(address _from,
address _to,
uint256 _value)
returns (bool success) {
if (_value < 1) throw;
if (this == _to) throw;
if (balanceOf[_from] < _value) throw;
if (_value > allowance[_from][msg.sender]) throw;
if (shareholderID[_to] == 0){
shareholderID[_to] = shareholder.push(_to)-1;
}
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function () {
throw;
}
string[] public proposalText;
mapping (uint256 => mapping (address => bool)) voted;
mapping (uint256 => address[]) public votes;
mapping (uint256 => uint256) public deadline;
mapping (uint256 => uint256) public results;
mapping (address => uint256[]) public proposalsByShareholder;
event ProposalAdded(uint256 proposalID,
address initiator,
string description,
uint256 deadline);
event VotingFinished(uint256 proposalID, uint256 votes);
function makeNewProposal(string _proposalDescription,
uint256 _debatingPeriodInMinutes)
returns (uint256){
if (balanceOf[msg.sender] < 1) throw;
uint256 id = proposalText.push(_proposalDescription)-1;
deadline[id] = now + _debatingPeriodInMinutes * 1 minutes;
proposalsByShareholder[msg.sender].push(id);
votes[id].push(msg.sender);
voted[id][msg.sender] = true;
ProposalAdded(id, msg.sender, _proposalDescription, deadline[id]);
return id;
}
function getMyProposals() returns (uint256[]){
return proposalsByShareholder[msg.sender];
}
function voteForProposal(uint256 _proposalID) returns (string) {
if (balanceOf[msg.sender] < 1) return "no shares, vote not accepted";
if (voted[_proposalID][msg.sender]){
return "already voted, vote not accepted";
}
if (now > deadline[_proposalID] ){
return "vote not accepted after deadline";
}
votes[_proposalID].push(msg.sender);
voted[_proposalID][msg.sender] = true;
return "vote accepted";
}
function countVotes(uint256 _proposalID) returns (uint256){
if (now < deadline[_proposalID]) throw;
if (results[_proposalID] > 0) return results[_proposalID];
uint256 result = 0;
for (uint256 i = 0; i < votes[_proposalID].length; i++){
address voter = votes[_proposalID][i];
result = result + balanceOf[voter];
}
VotingFinished(_proposalID, result);
return result;
}
} | 1 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract AirdropToken is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function AirdropToken(
) {
balances[msg.sender] = 10000000000000;
totalSupply = 11000000000000000;
name = "AirdropToken";
decimals = 8;
symbol = "ADP";
}
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.13;
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 PausableToken is Ownable {
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function increaseFrozen(address _owner,uint256 _incrementalAmount) public returns (bool);
function burn(uint256 _value) public;
}
contract AddressWhitelist is Ownable {
mapping (address => bool) whitelisted;
function isWhitelisted(address addr) view public returns (bool) {
return whitelisted[addr];
}
event LogWhitelistAdd(address indexed addr);
function addToWhitelist(address[] addresses) public onlyOwner returns (bool) {
for (uint i = 0; i < addresses.length; i++) {
if (!whitelisted[addresses[i]]) {
whitelisted[addresses[i]] = true;
LogWhitelistAdd(addresses[i]);
}
}
return true;
}
event LogWhitelistRemove(address indexed addr);
function removeFromWhitelist(address[] addresses) public onlyOwner returns (bool) {
for (uint i = 0; i < addresses.length; i++) {
if (whitelisted[addresses[i]]) {
whitelisted[addresses[i]] = false;
LogWhitelistRemove(addresses[i]);
}
}
return true;
}
}
contract RtcTokenCrowdsale is Ownable, AddressWhitelist {
using SafeMath for uint256;
PausableToken public tokenReward;
uint256 public initialSupply;
uint256 public tokensRemaining;
uint256 public decimals;
address public beneficiaryWallet;
uint256 public tokensPerEthPrice;
uint256 public amountRaisedInWei;
uint256 public fundingMinCapInWei;
uint256 public p1_duration;
uint256 public p1_start;
uint256 public p2_start;
uint256 public white_duration;
uint256 public fundingStartTime;
uint256 public fundingEndTime;
bool public isCrowdSaleClosed = false;
bool public areFundsReleasedToBeneficiary = false;
bool public isCrowdSaleSetup = false;
uint256 maxGasPrice = 50000000000;
event Buy(address indexed _sender, uint256 _eth, uint256 _RTC);
event Refund(address indexed _refunder, uint256 _value);
mapping(address => uint256) fundValue;
function toSmallrtc(uint256 amount) public constant returns (uint256) {
return amount.mul(10**decimals);
}
function toRtc(uint256 amount) public constant returns (uint256) {
return amount.div(10**decimals);
}
function updateMaxGasPrice(uint256 _newGasPrice) public onlyOwner {
require(_newGasPrice != 0);
maxGasPrice = _newGasPrice;
}
function setupCrowdsale(uint256 _fundingStartTime) external onlyOwner {
if ((!(isCrowdSaleSetup))
&& (!(beneficiaryWallet > 0))){
tokenReward = PausableToken(0x7c5c5F763274FC2f5bb86877815675B5dfB6FE3a);
beneficiaryWallet = 0xf07bd63C5cf404c2f17ab4F9FA1e13fCCEbc5255;
tokensPerEthPrice = 10000;
fundingMinCapInWei = 1 ether;
decimals = 18;
amountRaisedInWei = 0;
initialSupply = toSmallrtc(35000000);
tokensRemaining = initialSupply;
fundingStartTime = _fundingStartTime;
white_duration = 2 hours;
p1_duration = 4 hours;
p1_start = fundingStartTime + white_duration;
p2_start = p1_start + p1_duration + 4 hours;
fundingEndTime = p2_start + 4 hours;
isCrowdSaleSetup = true;
isCrowdSaleClosed = false;
}
}
function setBonusPrice() public constant returns (uint256 bonus) {
require(isCrowdSaleSetup);
require(p1_start + p1_duration <= p2_start);
if (now >= fundingStartTime && now <= p1_start) {
bonus = 4000;
} else if (now > p1_start && now <= p1_start + p1_duration) {
bonus = 3000;
} else if (now > p2_start && now <= p2_start + 10 minutes ) {
bonus = 2500;
} else if (now > p2_start + 10 minutes && now <= p2_start + 1 hours ) {
bonus = 2000;
} else if (now > p2_start + 1 hours && now <= p2_start + 2 hours ) {
bonus = 1500;
} else if (now > p2_start + 2 hours && now <= p2_start + 3 hours ) {
bonus = 1000;
} else if (now > p2_start + 3 hours && now <= fundingEndTime ) {
bonus = 500;
} else {
revert();
}
}
function updateDuration(uint256 _newP2Start) external onlyOwner {
require(isCrowdSaleSetup
&& !(p2_start == _newP2Start)
&& !(_newP2Start > p1_start + p1_duration + 30 hours)
&& (now < p2_start)
&& (fundingStartTime + p1_duration < _newP2Start));
p2_start = _newP2Start;
fundingEndTime = p2_start.add(4 hours);
}
function () external payable {
require(tx.gasprice <= maxGasPrice);
require(msg.data.length == 0);
BuyRTCtokens();
}
function BuyRTCtokens() public payable {
require(!(msg.value == 0)
&& (isCrowdSaleSetup)
&& (now >= fundingStartTime)
&& (now <= fundingEndTime)
&& (tokensRemaining > 0));
if (now <= p1_start) {
assert(isWhitelisted(msg.sender));
}
uint256 rewardTransferAmount = 0;
uint256 rewardBaseTransferAmount = 0;
uint256 rewardBonusTransferAmount = 0;
uint256 contributionInWei = msg.value;
uint256 refundInWei = 0;
rewardBonusTransferAmount = setBonusPrice();
rewardBaseTransferAmount = (msg.value.mul(tokensPerEthPrice));
rewardBonusTransferAmount = (msg.value.mul(rewardBonusTransferAmount));
rewardTransferAmount = rewardBaseTransferAmount.add(rewardBonusTransferAmount);
if (rewardTransferAmount > tokensRemaining) {
uint256 partialPercentage;
partialPercentage = tokensRemaining.mul(10**18).div(rewardTransferAmount);
contributionInWei = contributionInWei.mul(partialPercentage).div(10**18);
rewardBonusTransferAmount = rewardBonusTransferAmount.mul(partialPercentage).div(10**18);
rewardTransferAmount = tokensRemaining;
refundInWei = msg.value.sub(contributionInWei);
}
amountRaisedInWei = amountRaisedInWei.add(contributionInWei);
tokensRemaining = tokensRemaining.sub(rewardTransferAmount);
fundValue[msg.sender] = fundValue[msg.sender].add(contributionInWei);
assert(tokenReward.increaseFrozen(msg.sender, rewardBonusTransferAmount));
tokenReward.transfer(msg.sender, rewardTransferAmount);
Buy(msg.sender, contributionInWei, rewardTransferAmount);
if (refundInWei > 0) {
msg.sender.transfer(refundInWei);
}
}
function beneficiaryMultiSigWithdraw() external onlyOwner {
checkGoalReached();
require(areFundsReleasedToBeneficiary && (amountRaisedInWei >= fundingMinCapInWei));
beneficiaryWallet.transfer(this.balance);
}
function checkGoalReached() public returns (bytes32 response) {
require (isCrowdSaleSetup);
if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp <= fundingEndTime && block.timestamp >= fundingStartTime)) {
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = false;
return "In progress (Eth < Softcap)";
} else if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp < fundingStartTime)) {
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = false;
return "Crowdsale is setup";
} else if ((amountRaisedInWei < fundingMinCapInWei) && (block.timestamp > fundingEndTime)) {
areFundsReleasedToBeneficiary = false;
isCrowdSaleClosed = true;
return "Unsuccessful (Eth < Softcap)";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining == 0)) {
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = true;
return "Successful (RTC >= Hardcap)!";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (block.timestamp > fundingEndTime) && (tokensRemaining > 0)) {
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = true;
return "Successful (Eth >= Softcap)!";
} else if ((amountRaisedInWei >= fundingMinCapInWei) && (tokensRemaining > 0) && (block.timestamp <= fundingEndTime)) {
areFundsReleasedToBeneficiary = true;
isCrowdSaleClosed = false;
return "In progress (Eth >= Softcap)!";
}
}
function refund() external {
checkGoalReached();
require ((amountRaisedInWei < fundingMinCapInWei)
&& (isCrowdSaleClosed)
&& (now > fundingEndTime)
&& (fundValue[msg.sender] > 0));
uint256 ethRefund = fundValue[msg.sender];
fundValue[msg.sender] = 0;
msg.sender.transfer(ethRefund);
Refund(msg.sender, ethRefund);
}
function burnRemainingTokens() onlyOwner external {
require(now > fundingEndTime);
uint256 tokensToBurn = tokenReward.balanceOf(this);
tokenReward.burn(tokensToBurn);
}
}
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.11;
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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) {
assert(b > 0);
uint c = a / b;
assert(a == b * 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;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 DmlToken is StandardToken, Pausable{
using SafeMath for uint;
string public constant name = "DML Token";
uint8 public constant decimals = 18;
string public constant symbol = 'DML';
uint public constant MAX_TOTAL_TOKEN_AMOUNT = 330000000 ether;
address public minter;
uint public endTime;
mapping (address => uint) public lockedBalances;
modifier onlyMinter {
assert(msg.sender == minter);
_;
}
modifier maxDmlTokenAmountNotReached (uint amount){
assert(totalSupply.add(amount) <= MAX_TOTAL_TOKEN_AMOUNT);
_;
}
function DmlToken(address _minter, uint _endTime){
minter = _minter;
endTime = _endTime;
}
function mintToken(address receipent, uint amount)
external
onlyMinter
maxDmlTokenAmountNotReached(amount)
returns (bool)
{
require(now <= endTime);
lockedBalances[receipent] = lockedBalances[receipent].add(amount);
totalSupply = totalSupply.add(amount);
return true;
}
function claimTokens(address receipent)
public
onlyMinter
{
balances[receipent] = balances[receipent].add(lockedBalances[receipent]);
lockedBalances[receipent] = 0;
}
function lockedBalanceOf(address _owner) constant returns (uint balance) {
return lockedBalances[_owner];
}
function transfer(address _to, uint _value)
public
validRecipient(_to)
returns (bool success)
{
return super.transfer(_to, _value);
}
function approve(address _spender, uint256 _value)
public
validRecipient(_spender)
returns (bool)
{
return super.approve(_spender, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public
validRecipient(_to)
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
modifier validRecipient(address _recipient) {
require(_recipient != address(this));
_;
}
}
contract DmlContribution is Ownable {
using SafeMath for uint;
uint public constant DML_TOTAL_SUPPLY = 330000000 ether;
uint public constant EARLY_CONTRIBUTION_DURATION = 24 hours;
uint public constant MAX_CONTRIBUTION_DURATION = 5 days;
uint public constant PRICE_RATE_FIRST = 3780;
uint public constant PRICE_RATE_SECOND = 4158;
uint public constant SALE_STAKE = 360;
uint public constant ECO_SYSTEM_STAKE = 99;
uint public constant COMMUNITY_BOUNTY_STAKE = 83;
uint public constant OPERATION_STAKE = 308;
uint public constant RESERVES_STAKE = 150;
uint public constant DIVISOR_STAKE = 1000;
uint public constant PRESALE_RESERVERED_AMOUNT = 56899342578812412860512236;
address public constant ECO_SYSTEM_HOLDER = 0x2D8C705a66b2E87A9249380d4Cdfe9D80BBF826B;
address public constant COMMUNITY_BOUNTY_HOLDER = 0x68500ffEfb57D88A600E2f1c63Bb5866e7107b6B;
address public constant OPERATION_HOLDER = 0xC7b6DFf52014E59Cb88fAc3b371FA955D0A9249F;
address public constant RESERVES_HOLDER = 0xab376b3eC2ed446444911E549c7C953fB086070f;
address public constant PRESALE_HOLDER = 0xcB52583D19fd42c0f85a0c83A45DEa6C73B9EBfb;
uint public MAX_PUBLIC_SOLD = DML_TOTAL_SUPPLY * SALE_STAKE / DIVISOR_STAKE - PRESALE_RESERVERED_AMOUNT;
address public dmlwallet;
uint public earlyWhitelistBeginTime;
uint public startTime;
uint public endTime;
uint public openSoldTokens;
bool public halted;
DmlToken public dmlToken;
mapping (address => WhitelistUser) private whitelisted;
address[] private whitelistedIndex;
struct WhitelistUser {
uint256 quota;
uint index;
uint level;
}
uint256 public maxBuyLimit = 68 ether;
event NewSale(address indexed destAddress, uint ethCost, uint gotTokens);
event ToFundAmount(uint ethCost);
event ValidFundAmount(uint ethCost);
event Debug(uint number);
event UserCallBuy();
event ShowTokenAvailable(uint);
event NowTime(uint, uint, uint, uint);
modifier notHalted() {
require(!halted);
_;
}
modifier initialized() {
require(address(dmlwallet) != 0x0);
_;
}
modifier notEarlierThan(uint x) {
require(now >= x);
_;
}
modifier earlierThan(uint x) {
require(now < x);
_;
}
modifier ceilingNotReached() {
require(openSoldTokens < MAX_PUBLIC_SOLD);
_;
}
modifier isSaleEnded() {
require(now > endTime || openSoldTokens >= MAX_PUBLIC_SOLD);
_;
}
function DmlContribution(address _dmlwallet, uint _bootTime){
require(_dmlwallet != 0x0);
halted = false;
dmlwallet = _dmlwallet;
earlyWhitelistBeginTime = _bootTime;
startTime = earlyWhitelistBeginTime + EARLY_CONTRIBUTION_DURATION;
endTime = startTime + MAX_CONTRIBUTION_DURATION;
openSoldTokens = 0;
dmlToken = new DmlToken(this, endTime);
uint stakeMultiplier = DML_TOTAL_SUPPLY / DIVISOR_STAKE;
dmlToken.mintToken(ECO_SYSTEM_HOLDER, ECO_SYSTEM_STAKE * stakeMultiplier);
dmlToken.mintToken(COMMUNITY_BOUNTY_HOLDER, COMMUNITY_BOUNTY_STAKE * stakeMultiplier);
dmlToken.mintToken(OPERATION_HOLDER, OPERATION_STAKE * stakeMultiplier);
dmlToken.mintToken(RESERVES_HOLDER, RESERVES_STAKE * stakeMultiplier);
dmlToken.mintToken(PRESALE_HOLDER, PRESALE_RESERVERED_AMOUNT);
}
function () public payable {
buyDmlCoin(msg.sender);
}
function buyDmlCoin(address receipient)
public
payable
notHalted
initialized
ceilingNotReached
notEarlierThan(earlyWhitelistBeginTime)
earlierThan(endTime)
returns (bool)
{
require(receipient != 0x0);
require(isWhitelisted(receipient));
require(!isContract(msg.sender));
require( tx.gasprice <= 99000000000 wei );
if( now < startTime && now >= earlyWhitelistBeginTime)
{
if (whitelisted[receipient].level >= 2)
{
require(msg.value >= 1 ether);
}
else
{
require(msg.value >= 0.5 ether);
}
buyEarlyWhitelist(receipient);
}
else
{
require(msg.value >= 0.1 ether);
require(msg.value <= maxBuyLimit);
buyRemaining(receipient);
}
return true;
}
function setMaxBuyLimit(uint256 limit)
public
initialized
onlyOwner
earlierThan(endTime)
{
maxBuyLimit = limit;
}
function addWhiteListUsers(address[] userAddresses, uint256[] quota, uint[] level)
public
onlyOwner
earlierThan(endTime)
{
for( uint i = 0; i < userAddresses.length; i++) {
addWhiteListUser(userAddresses[i], quota[i], level[i]);
}
}
function addWhiteListUser(address userAddress, uint256 quota, uint level)
public
onlyOwner
earlierThan(endTime)
{
if (!isWhitelisted(userAddress)) {
whitelisted[userAddress].quota = quota;
whitelisted[userAddress].level = level;
whitelisted[userAddress].index = whitelistedIndex.push(userAddress) - 1;
}
}
function isWhitelisted (address userAddress) public constant returns (bool isIndeed) {
if (whitelistedIndex.length == 0) return false;
return (whitelistedIndex[whitelisted[userAddress].index] == userAddress);
}
function getWhitelistUser (address userAddress) public constant returns (uint256 quota, uint index, uint level) {
require(isWhitelisted(userAddress));
return(whitelisted[userAddress].quota, whitelisted[userAddress].index, whitelisted[userAddress].level);
}
function halt() public onlyOwner{
halted = true;
}
function unHalt() public onlyOwner{
halted = false;
}
function changeWalletAddress(address newAddress) onlyOwner{
dmlwallet = newAddress;
}
function saleNotEnd() constant returns (bool) {
return now < endTime && openSoldTokens < MAX_PUBLIC_SOLD;
}
function priceRate() public constant returns (uint) {
if (earlyWhitelistBeginTime <= now && now < startTime)
{
if (whitelisted[msg.sender].level >= 2)
{
return PRICE_RATE_SECOND;
}
else
{
return PRICE_RATE_FIRST;
}
}
if (startTime <= now && now < endTime)
{
return PRICE_RATE_FIRST;
}
assert(false);
}
function claimTokens(address receipent)
public
isSaleEnded
{
dmlToken.claimTokens(receipent);
}
function buyEarlyWhitelist(address receipient) internal {
uint quotaAvailable = whitelisted[receipient].quota;
require(quotaAvailable > 0);
uint tokenAvailable = MAX_PUBLIC_SOLD.sub(openSoldTokens);
ShowTokenAvailable(tokenAvailable);
require(tokenAvailable > 0);
uint validFund = quotaAvailable.min256(msg.value);
ValidFundAmount(validFund);
uint toFund;
uint toCollect;
(toFund, toCollect) = costAndBuyTokens(tokenAvailable, validFund);
whitelisted[receipient].quota = whitelisted[receipient].quota.sub(toFund);
buyCommon(receipient, toFund, toCollect);
}
function buyRemaining(address receipient) internal {
uint tokenAvailable = MAX_PUBLIC_SOLD.sub(openSoldTokens);
ShowTokenAvailable(tokenAvailable);
require(tokenAvailable > 0);
uint toFund;
uint toCollect;
(toFund, toCollect) = costAndBuyTokens(tokenAvailable, msg.value);
buyCommon(receipient, toFund, toCollect);
}
function buyCommon(address receipient, uint toFund, uint dmlTokenCollect) internal {
require(msg.value >= toFund);
if(toFund > 0) {
require(dmlToken.mintToken(receipient, dmlTokenCollect));
ToFundAmount(toFund);
dmlwallet.transfer(toFund);
openSoldTokens = openSoldTokens.add(dmlTokenCollect);
NewSale(receipient, toFund, dmlTokenCollect);
}
uint toReturn = msg.value.sub(toFund);
if(toReturn > 0) {
msg.sender.transfer(toReturn);
}
}
function costAndBuyTokens(uint availableToken, uint validFund) constant internal returns (uint costValue, uint getTokens){
uint exchangeRate = priceRate();
getTokens = exchangeRate * validFund;
if(availableToken >= getTokens){
costValue = validFund;
} else {
costValue = availableToken / exchangeRate;
getTokens = availableToken;
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
} | 0 |
pragma solidity ^0.4.24;
contract CryptoPunk
{
function punkIndexToAddress(uint256 punkIndex) public view returns (address ownerAddress);
function balanceOf(address tokenOwner) public view returns (uint balance);
function transferPunk(address to, uint punkIndex) public;
}
contract ERC20
{
function balanceOf(address tokenOwner) public view returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
}
contract PunkLombard
{
address public CryptoPunksContract;
uint256 public loanAmount;
uint256 public punkIndex;
uint256 public annualInterestRate;
uint256 public loanTenor;
uint256 public loanPeriod;
address public lender;
address public borrower;
uint256 public loanStart;
uint256 public loanEnd;
uint256 public interest;
address public contractOwner;
modifier onlyOwner
{
if (msg.sender != contractOwner) revert();
_;
}
modifier onlyLender
{
if (msg.sender != lender) revert();
_;
}
constructor () public
{
CryptoPunksContract = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
contractOwner = msg.sender;
borrower = msg.sender;
}
function transferContractOwnership(address newContractOwner) public onlyOwner
{
contractOwner = newContractOwner;
}
function setTerms(uint256 _loanAmount, uint256 _annualInterestRate, uint256 _loanTenor, uint256 _punkIndex) public onlyOwner
{
require(CryptoPunk(CryptoPunksContract).balanceOf(address(this)) == 1);
loanAmount = _loanAmount;
annualInterestRate = _annualInterestRate;
loanTenor = _loanTenor;
punkIndex = _punkIndex;
}
function claimCollateral() public onlyLender
{
require(now > (loanStart + loanTenor));
CryptoPunk(CryptoPunksContract).transferPunk(lender, punkIndex);
}
function () payable public
{
if(msg.sender == borrower)
{
require(now <= (loanStart + loanTenor));
uint256 loanPeriodCheck = (now - loanStart);
interest = (((loanAmount * annualInterestRate) / 10 ** 18) * loanPeriodCheck) / 365 days;
require(msg.value >= loanAmount + interest);
loanPeriod = loanPeriodCheck;
loanEnd = now;
uint256 change = msg.value - (loanAmount + interest);
lender.transfer(loanAmount + interest);
if(change > 0)
{
borrower.transfer(change);
}
CryptoPunk(CryptoPunksContract).transferPunk(borrower, punkIndex);
}
if(msg.sender != borrower)
{
require(loanStart == 0);
require(CryptoPunk(CryptoPunksContract).balanceOf(address(this)) == 1);
require(CryptoPunk(CryptoPunksContract).punkIndexToAddress(punkIndex) == address(this));
require(msg.value >= loanAmount);
lender = msg.sender;
loanStart = now;
if(msg.value > loanAmount)
{
msg.sender.transfer(msg.value-loanAmount);
}
borrower.transfer(loanAmount);
}
}
function transfer_targetToken(address target, address to, uint256 quantity) public onlyOwner
{
ERC20(target).transfer(to, quantity);
}
function reclaimPunkBeforeLoan(address _to, uint256 _punkIndex) public onlyOwner
{
require(loanStart == 0);
CryptoPunk(CryptoPunksContract).transferPunk(_to, _punkIndex);
}
} | 0 |
pragma solidity ^0.4.18;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSProxy is DSAuth, DSNote {
DSProxyCache public cache;
function DSProxy(address _cacheAddr) public {
require(setCache(_cacheAddr));
}
function() public payable {
}
function execute(bytes _code, bytes _data)
public
payable
returns (address target, bytes32 response)
{
target = cache.read(_code);
if (target == 0x0) {
target = cache.write(_code);
}
response = execute(target, _data);
}
function execute(address _target, bytes _data)
public
auth
note
payable
returns (bytes32 response)
{
require(_target != 0x0);
assembly {
let succeeded := delegatecall(sub(gas, 5000), _target, add(_data, 0x20), mload(_data), 0, 32)
response := mload(0)
switch iszero(succeeded)
case 1 {
revert(0, 0)
}
}
}
function setCache(address _cacheAddr)
public
auth
note
returns (bool)
{
require(_cacheAddr != 0x0);
cache = DSProxyCache(_cacheAddr);
return true;
}
}
contract DSProxyFactory {
event Created(address indexed sender, address proxy, address cache);
mapping(address=>bool) public isProxy;
DSProxyCache public cache = new DSProxyCache();
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
function build(address owner) public returns (DSProxy proxy) {
proxy = new DSProxy(cache);
Created(owner, address(proxy), address(cache));
proxy.setOwner(owner);
isProxy[proxy] = true;
}
}
contract DSProxyCache {
mapping(bytes32 => address) cache;
function read(bytes _code) public view returns (address) {
bytes32 hash = keccak256(_code);
return cache[hash];
}
function write(bytes _code) public returns (address target) {
assembly {
target := create(0, add(_code, 0x20), mload(_code))
switch iszero(extcodesize(target))
case 1 {
revert(0, 0)
}
}
bytes32 hash = keccak256(_code);
cache[hash] = target;
}
}
contract ProxyRegistry {
mapping(address=>DSProxy[]) public proxies;
mapping(address=>uint) public proxiesCount;
DSProxyFactory factory;
function ProxyRegistry(DSProxyFactory factory_) public {
factory = factory_;
}
function build() public returns (DSProxy proxy) {
proxy = build(msg.sender);
}
function build(address owner) public returns (DSProxy proxy) {
proxy = factory.build(owner);
proxies[owner].push(proxy);
proxiesCount[owner] ++;
}
} | 0 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
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 TokenVesting is Ownable{
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
address public rollback;
bool public revocable;
uint256 public currentBalance;
bool public initialized = false;
uint256 public constant initialTokens = 66011*10**8;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
uint256 public totalBalance;
constructor(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _rollback,
ERC20Basic _token
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
token = _token;
rollback = _rollback;
}
function initialize() public onlyOwner {
require(tokensAvailable() == initialTokens);
currentBalance = token.balanceOf(this);
totalBalance = currentBalance.add(released[token]);
initialized = true;
}
function tokensAvailable() public constant returns (uint256) {
return token.balanceOf(this);
}
function release() public {
require(initialized);
uint256 unreleased = releasableAmount();
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
emit Released(unreleased);
}
function revoke() public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount();
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(rollback, refund);
emit Revoked();
}
function releasableAmount() public returns (uint256) {
return vestedAmount().sub(released[token]);
}
function vestedAmount() public returns (uint256) {
currentBalance = token.balanceOf(this);
totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
} | 0 |
contract ERC20 {
function transfer(address _to, uint256 _value) returns (bool success);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract BuyerFund {
mapping (address => uint256) public balances;
mapping (address => uint256) public picops_balances;
bool public bought_tokens;
bool public contract_enabled = true;
uint256 public contract_eth_value;
uint256 constant public min_required_amount = 20 ether;
address constant public creator = 0x2E2E356b67d82D6f4F5D54FFCBcfFf4351D2e56c;
address public sale = 0xf58546F5CDE2a7ff5C91AFc63B43380F0C198BE8;
address public picops_user;
bool public is_verified = false;
bytes32 public h_pwd = 0x30f5931696381f3826a0a496cf17fecdf9c83e15089c9a3bbd804a3319a1384e;
bytes32 public s_pwd = 0x8d9b2b8f1327f8bad773f0f3af0cb4f3fbd8abfad8797a28d1d01e354982c7de;
uint256 public creator_fee;
uint256 public claim_block = 5350521;
uint256 public change_block = 4722681;
function perform_withdraw(address tokenAddress) {
require(bought_tokens);
ERC20 token = ERC20(tokenAddress);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value;
contract_eth_value -= balances[msg.sender];
balances[msg.sender] = 0;
uint256 fee = tokens_to_withdraw / 100;
require(token.transfer(msg.sender, tokens_to_withdraw - fee));
require(token.transfer(picops_user, fee));
}
function refund_me() {
require(this.balance > 0);
uint256 eth_to_withdraw = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(eth_to_withdraw);
}
function buy_the_tokens(bytes32 _pwd) {
require(this.balance > min_required_amount);
require(!bought_tokens);
require(msg.sender == creator || h_pwd == keccak256(_pwd));
bought_tokens = true;
creator_fee = this.balance / 100;
contract_eth_value = this.balance - creator_fee;
creator.transfer(creator_fee);
sale.transfer(contract_eth_value);
}
function enable_deposits(bool toggle) {
require(msg.sender == creator);
contract_enabled = toggle;
}
function verify_fund() payable {
if (!is_verified) {
picops_balances[msg.sender] += msg.value;
}
}
function verify_send(address _picops, uint256 amount) {
require(picops_balances[msg.sender] > 0);
require(picops_balances[msg.sender] >= amount);
uint256 eth_to_withdraw = picops_balances[msg.sender];
picops_balances[msg.sender] = picops_balances[msg.sender] - amount;
_picops.transfer(amount);
}
function verify_withdraw() {
uint256 eth_to_withdraw = picops_balances[msg.sender];
picops_balances[msg.sender] = 0;
msg.sender.transfer(eth_to_withdraw);
}
function picops_is_verified(bool toggle) {
require(msg.sender == creator);
is_verified = toggle;
}
function set_sale_address(address _sale, bytes32 _pwd) {
require(keccak256(_pwd) == s_pwd || msg.sender == creator);
require (block.number > change_block);
sale = _sale;
}
function set_successful_verifier(address _picops_user) {
require(msg.sender == creator);
picops_user = _picops_user;
}
function delay_pool_drain_block(uint256 _block) {
require(_block > claim_block);
claim_block = _block;
}
function delay_pool_change_block(uint256 _block) {
require(_block > change_block);
change_block = _block;
}
function pool_drain(address tokenAddress) {
require(msg.sender == creator);
require(block.number >= claim_block);
if (this.balance > 0) {
creator.transfer(this.balance);
}
ERC20 token = ERC20(tokenAddress);
uint256 contract_token_balance = token.balanceOf(address(this));
require(token.transfer(msg.sender, contract_token_balance));
}
function () payable {
require(!bought_tokens);
require(contract_enabled);
balances[msg.sender] += msg.value;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29980800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x27480e5D1FE1fb3FEeBe6B0bA5CE6D1c401f87fA;
}
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.0;
contract TokenInterface {
uint 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 TokenInterface {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function StandardToken(){
}
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[from] -= value;
balances[to] =+ 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];
}
}
contract HackerGold is StandardToken {
string public name = "HackerGold";
uint8 public decimals = 3;
string public symbol = "HKG";
uint BASE_PRICE = 200;
uint MID_PRICE = 150;
uint FIN_PRICE = 100;
uint SAFETY_LIMIT = 4000000 ether;
uint DECIMAL_ZEROS = 1000;
uint totalValue;
address wallet;
struct milestones_struct {
uint p1;
uint p2;
uint p3;
uint p4;
uint p5;
uint p6;
}
milestones_struct milestones;
function HackerGold(address multisig) {
wallet = multisig;
milestones = milestones_struct(
1476972000,
1478181600,
1479391200,
1480600800,
1481810400,
1482415200
);
}
function () payable {
createHKG(msg.sender);
}
function createHKG(address holder) payable {
if (now < milestones.p1) throw;
if (now >= milestones.p6) throw;
if (msg.value == 0) throw;
if (getTotalValue() + msg.value > SAFETY_LIMIT) throw;
uint tokens = msg.value * getPrice() * DECIMAL_ZEROS / 1 ether;
totalSupply += tokens;
balances[holder] += tokens;
totalValue += msg.value;
if (!wallet.send(msg.value)) throw;
}
function getPrice() constant returns (uint result) {
if (now < milestones.p1) return 0;
if (now >= milestones.p1 && now < milestones.p2) {
return BASE_PRICE;
}
if (now >= milestones.p2 && now < milestones.p3) {
uint days_in = 1 + (now - milestones.p2) / 1 days;
return BASE_PRICE - days_in * 25 / 7;
}
if (now >= milestones.p3 && now < milestones.p4) {
return MID_PRICE;
}
if (now >= milestones.p4 && now < milestones.p5) {
days_in = 1 + (now - milestones.p4) / 1 days;
return MID_PRICE - days_in * 25 / 7;
}
if (now >= milestones.p5 && now < milestones.p6) {
return FIN_PRICE;
}
if (now >= milestones.p6){
return 0;
}
}
function getTotalSupply() constant returns (uint result) {
return totalSupply;
}
function getNow() constant returns (uint result) {
return now;
}
function getTotalValue() constant returns (uint result) {
return totalValue;
}
}
contract DSTContract is StandardToken{
uint DECIMAL_ZEROS = 1000;
uint PROPOSAL_LIFETIME = 10 days;
uint PROPOSAL_FUNDS_TH = 20;
address executive;
EventInfo eventInfo;
address virtualExchangeAddress;
HackerGold hackerGold;
mapping (address => uint256) votingRights;
uint hkgPrice;
uint etherPrice;
string public name = "...";
uint8 public decimals = 3;
string public symbol = "...";
bool ableToIssueTokens = true;
uint preferedQtySold;
uint collectedHKG;
uint collectedEther;
mapping (bytes32 => Proposal) proposals;
enum ProposalCurrency { HKG, ETHER }
ProposalCurrency enumDeclaration;
struct Proposal{
bytes32 id;
uint value;
string urlDetails;
uint votindEndTS;
uint votesObjecting;
address submitter;
bool redeemed;
ProposalCurrency proposalCurrency;
mapping (address => bool) voted;
}
uint counterProposals;
uint timeOfLastProposal;
Proposal[] listProposals;
struct ImpeachmentProposal{
string urlDetails;
address newExecutive;
uint votindEndTS;
uint votesSupporting;
mapping (address => bool) voted;
}
ImpeachmentProposal lastImpeachmentProposal;
function DSTContract(EventInfo eventInfoAddr, HackerGold hackerGoldAddr, string dstName, string dstSymbol){
executive = msg.sender;
name = dstName;
symbol = dstSymbol;
hackerGold = HackerGold(hackerGoldAddr);
eventInfo = EventInfo(eventInfoAddr);
}
function() payable
onlyAfterEnd {
if (etherPrice == 0) throw;
uint tokens = msg.value * etherPrice * DECIMAL_ZEROS / (1 ether);
uint retEther = 0;
if (balances[this] < tokens) {
tokens = balances[this];
retEther = msg.value - tokens / etherPrice * (1 finney);
if (!msg.sender.send(retEther)) throw;
}
balances[msg.sender] += tokens;
balances[this] -= tokens;
collectedEther += msg.value - retEther;
BuyForEtherTransaction(msg.sender, collectedEther, totalSupply, etherPrice, tokens);
}
function setHKGPrice(uint qtyForOneHKG) onlyExecutive {
hkgPrice = qtyForOneHKG;
PriceHKGChange(qtyForOneHKG, preferedQtySold, totalSupply);
}
function issuePreferedTokens(uint qtyForOneHKG,
uint qtyToEmit) onlyExecutive
onlyIfAbleToIssueTokens
onlyBeforeEnd
onlyAfterTradingStart {
if (virtualExchangeAddress == 0x0) throw;
totalSupply += qtyToEmit;
balances[this] += qtyToEmit;
hkgPrice = qtyForOneHKG;
allowed[this][virtualExchangeAddress] += qtyToEmit;
Approval(this, virtualExchangeAddress, qtyToEmit);
DstTokensIssued(hkgPrice, preferedQtySold, totalSupply, qtyToEmit);
}
function buyForHackerGold(uint hkgValue) onlyBeforeEnd
returns (bool success) {
if (msg.sender != virtualExchangeAddress) throw;
address sender = tx.origin;
uint tokensQty = hkgValue * hkgPrice;
votingRights[sender] +=tokensQty;
preferedQtySold += tokensQty;
collectedHKG += hkgValue;
transferFrom(this,
virtualExchangeAddress, tokensQty);
transfer(sender, tokensQty);
BuyForHKGTransaction(sender, preferedQtySold, totalSupply, hkgPrice, tokensQty);
return true;
}
function issueTokens(uint qtyForOneEther,
uint qtyToEmit) onlyAfterEnd
onlyExecutive
onlyIfAbleToIssueTokens {
balances[this] += qtyToEmit;
etherPrice = qtyForOneEther;
totalSupply += qtyToEmit;
DstTokensIssued(qtyForOneEther, totalSupply, totalSupply, qtyToEmit);
}
function setEtherPrice(uint qtyForOneEther) onlyAfterEnd
onlyExecutive {
etherPrice = qtyForOneEther;
NewEtherPrice(qtyForOneEther);
}
function disableTokenIssuance() onlyExecutive {
ableToIssueTokens = false;
DisableTokenIssuance();
}
function burnRemainToken() onlyExecutive {
totalSupply -= balances[this];
balances[this] = 0;
BurnedAllRemainedTokens();
}
function submitEtherProposal(uint requestValue, string url) onlyAfterEnd
onlyExecutive returns (bytes32 resultId, bool resultSucces) {
if (ableToIssueTokens) throw;
if (balanceOf(this) > 0) throw;
if (now < (timeOfLastProposal + 2 weeks)) throw;
uint percent = collectedEther / 100;
if (requestValue > PROPOSAL_FUNDS_TH * percent) throw;
if (requestValue > this.balance)
requestValue = this.balance;
bytes32 id = sha3(msg.data, now);
uint timeEnds = now + PROPOSAL_LIFETIME;
Proposal memory newProposal = Proposal(id, requestValue, url, timeEnds, 0, msg.sender, false, ProposalCurrency.ETHER);
proposals[id] = newProposal;
listProposals.push(newProposal);
timeOfLastProposal = now;
ProposalRequestSubmitted(id, requestValue, timeEnds, url, msg.sender);
return (id, true);
}
function submitHKGProposal(uint requestValue, string url) onlyAfterEnd
onlyExecutive returns (bytes32 resultId, bool resultSucces){
if (now < (eventInfo.getEventEnd() + 8 weeks)) {
throw;
}
if (now < (timeOfLastProposal + 2 weeks)) throw;
uint percent = preferedQtySold / 100;
if (counterProposals <= 5 &&
requestValue > PROPOSAL_FUNDS_TH * percent) throw;
if (requestValue > getHKGOwned())
requestValue = getHKGOwned();
bytes32 id = sha3(msg.data, now);
uint timeEnds = now + PROPOSAL_LIFETIME;
Proposal memory newProposal = Proposal(id, requestValue, url, timeEnds, 0, msg.sender, false, ProposalCurrency.HKG);
proposals[id] = newProposal;
listProposals.push(newProposal);
++counterProposals;
timeOfLastProposal = now;
ProposalRequestSubmitted(id, requestValue, timeEnds, url, msg.sender);
return (id, true);
}
function objectProposal(bytes32 id){
Proposal memory proposal = proposals[id];
if (proposals[id].id == 0) throw;
if (proposals[id].redeemed) throw;
if (now >= proposals[id].votindEndTS) throw;
if (proposals[id].voted[msg.sender]) throw;
uint votes = votingRights[msg.sender];
proposals[id].votesObjecting += votes;
proposals[id].voted[msg.sender] = true;
uint idx = getIndexByProposalId(id);
listProposals[idx] = proposals[id];
ObjectedVote(id, msg.sender, votes);
}
function getIndexByProposalId(bytes32 id) returns (uint result){
for (uint i = 0; i < listProposals.length; ++i){
if (id == listProposals[i].id) return i;
}
}
function redeemProposalFunds(bytes32 id) onlyExecutive {
if (proposals[id].id == 0) throw;
if (proposals[id].submitter != msg.sender) throw;
if (now < proposals[id].votindEndTS) throw;
if (proposals[id].redeemed) throw;
uint objectionThreshold = preferedQtySold / 100 * 55;
if (proposals[id].votesObjecting > objectionThreshold) throw;
if (proposals[id].proposalCurrency == ProposalCurrency.HKG){
hackerGold.transfer(proposals[id].submitter, proposals[id].value);
} else {
bool success = proposals[id].submitter.send(proposals[id].value);
EtherRedeemAccepted(proposals[id].submitter, proposals[id].value);
}
proposals[id].redeemed = true;
}
function getAllTheFunds() onlyExecutive {
if (now < (eventInfo.getEventEnd() + 24 weeks)) {
throw;
}
bool success = msg.sender.send(this.balance);
hackerGold.transfer(msg.sender, getHKGOwned());
}
function submitImpeachmentProposal(string urlDetails, address newExecutive){
if (votingRights[msg.sender] == 0) throw;
if (now < (eventInfo.getEventEnd() + 12 weeks)) throw;
if (lastImpeachmentProposal.votindEndTS != 0 &&
lastImpeachmentProposal.votindEndTS + 2 weeks > now) throw;
lastImpeachmentProposal = ImpeachmentProposal(urlDetails, newExecutive, now + 2 weeks, votingRights[msg.sender]);
lastImpeachmentProposal.voted[msg.sender] = true;
ImpeachmentProposed(msg.sender, urlDetails, now + 2 weeks, newExecutive);
}
function supportImpeachment(){
if (lastImpeachmentProposal.newExecutive == 0x0) throw;
if (votingRights[msg.sender] == 0) throw;
if (lastImpeachmentProposal.voted[msg.sender]) throw;
if (lastImpeachmentProposal.votindEndTS + 2 weeks <= now) throw;
lastImpeachmentProposal.voted[msg.sender] = true;
lastImpeachmentProposal.votesSupporting += votingRights[msg.sender];
ImpeachmentSupport(msg.sender, votingRights[msg.sender]);
uint percent = preferedQtySold / 100;
if (lastImpeachmentProposal.votesSupporting >= 70 * percent){
executive = lastImpeachmentProposal.newExecutive;
ImpeachmentAccepted(executive);
}
}
function votingRightsOf(address _owner) constant returns (uint256 result) {
result = votingRights[_owner];
}
function getPreferedQtySold() constant returns (uint result){
return preferedQtySold;
}
function setVirtualExchange(address virtualExchangeAddr){
if (virtualExchangeAddress != 0x0) throw;
virtualExchangeAddress = virtualExchangeAddr;
}
function getHKGOwned() constant returns (uint result){
return hackerGold.balanceOf(this);
}
function getEtherValue() constant returns (uint result){
return this.balance;
}
function getExecutive() constant returns (address result){
return executive;
}
function getHKGPrice() constant returns (uint result){
return hkgPrice;
}
function getEtherPrice() constant returns (uint result){
return etherPrice;
}
function getDSTName() constant returns(string result){
return name;
}
function getDSTNameBytes() constant returns(bytes32 result){
return convert(name);
}
function getDSTSymbol() constant returns(string result){
return symbol;
}
function getDSTSymbolBytes() constant returns(bytes32 result){
return convert(symbol);
}
function getAddress() constant returns (address result) {
return this;
}
function getTotalSupply() constant returns (uint result) {
return totalSupply;
}
function getCollectedEther() constant returns (uint results) {
return collectedEther;
}
function getCounterProposals() constant returns (uint result){
return counterProposals;
}
function getProposalIdByIndex(uint i) constant returns (bytes32 result){
return listProposals[i].id;
}
function getProposalObjectionByIndex(uint i) constant returns (uint result){
return listProposals[i].votesObjecting;
}
function getProposalValueByIndex(uint i) constant returns (uint result){
return listProposals[i].value;
}
function getCurrentImpeachmentUrlDetails() constant returns (string result){
return lastImpeachmentProposal.urlDetails;
}
function getCurrentImpeachmentVotesSupporting() constant returns (uint result){
return lastImpeachmentProposal.votesSupporting;
}
function convert(string key) returns (bytes32 ret) {
if (bytes(key).length > 32) {
throw;
}
assembly {
ret := mload(add(key, 32))
}
}
modifier onlyBeforeEnd() { if (now >= eventInfo.getEventEnd()) throw; _; }
modifier onlyAfterEnd() { if (now < eventInfo.getEventEnd()) throw; _; }
modifier onlyAfterTradingStart() { if (now < eventInfo.getTradingStart()) throw; _; }
modifier onlyExecutive() { if (msg.sender != executive) throw; _; }
modifier onlyIfAbleToIssueTokens() { if (!ableToIssueTokens) throw; _; }
event PriceHKGChange(uint indexed qtyForOneHKG, uint indexed tokensSold, uint indexed totalSupply);
event BuyForHKGTransaction(address indexed buyer, uint indexed tokensSold, uint indexed totalSupply, uint qtyForOneHKG, uint tokensAmount);
event BuyForEtherTransaction(address indexed buyer, uint indexed tokensSold, uint indexed totalSupply, uint qtyForOneEther, uint tokensAmount);
event DstTokensIssued(uint indexed qtyForOneHKG, uint indexed tokensSold, uint indexed totalSupply, uint qtyToEmit);
event ProposalRequestSubmitted(bytes32 id, uint value, uint timeEnds, string url, address sender);
event EtherRedeemAccepted(address sender, uint value);
event ObjectedVote(bytes32 id, address voter, uint votes);
event ImpeachmentProposed(address submitter, string urlDetails, uint votindEndTS, address newExecutive);
event ImpeachmentSupport(address supportter, uint votes);
event ImpeachmentAccepted(address newExecutive);
event NewEtherPrice(uint newQtyForOneEther);
event DisableTokenIssuance();
event BurnedAllRemainedTokens();
}
contract EventInfo{
uint constant HACKATHON_5_WEEKS = 60 * 60 * 24 * 7 * 5;
uint constant T_1_WEEK = 60 * 60 * 24 * 7;
uint eventStart = 1479391200;
uint eventEnd = eventStart + HACKATHON_5_WEEKS;
function getEventStart() constant returns (uint result){
return eventStart;
}
function getEventEnd() constant returns (uint result){
return eventEnd;
}
function getVotingStart() constant returns (uint result){
return eventStart+ T_1_WEEK;
}
function getTradingStart() constant returns (uint result){
return eventStart+ T_1_WEEK;
}
function getNow() constant returns (uint result){
return now;
}
} | 0 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract TKRPToken is StandardToken {
event Destroy(address indexed _from);
string public name = "TKRPToken";
string public symbol = "TKRP";
uint256 public decimals = 18;
uint256 public initialSupply = 500000;
function TKRPToken() {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
}
function destroyFrom(address _from) onlyOwner returns (bool) {
uint256 balance = balanceOf(_from);
if (balance == 0) throw;
balances[_from] = 0;
totalSupply = totalSupply.sub(balance);
Destroy(_from);
}
}
contract PreCrowdsale is Ownable {
using SafeMath for uint256;
struct Contributor {
uint256 contributed;
uint256 received;
}
mapping(address => Contributor) public contributors;
event TokensSent(address indexed to, uint256 value);
event ContributionReceived(address indexed to, uint256 value);
uint256 public constant TOKEN_CAP = 500000;
uint256 public constant MINIMUM_CONTRIBUTION = 10 finney;
uint256 public constant TOKENS_PER_ETHER = 10000;
uint256 public constant PRE_CROWDSALE_DURATION = 5 days;
TKRPToken public token;
address public preCrowdsaleOwner;
uint256 public etherReceived;
uint256 public tokensSent;
uint256 public preCrowdsaleStartTime;
uint256 public preCrowdsaleEndTime;
modifier preCrowdsaleRunning() {
if (now > preCrowdsaleEndTime || now < preCrowdsaleStartTime) throw;
_;
}
function PreCrowdsale(address _tokenAddress, address _to) {
token = TKRPToken(_tokenAddress);
preCrowdsaleOwner = _to;
}
function() preCrowdsaleRunning payable {
processContribution(msg.sender);
}
function start() onlyOwner {
if (preCrowdsaleStartTime != 0) throw;
preCrowdsaleStartTime = now;
preCrowdsaleEndTime = now + PRE_CROWDSALE_DURATION;
}
function drain() onlyOwner {
if (!preCrowdsaleOwner.send(this.balance)) throw;
}
function finalize() onlyOwner {
if ((preCrowdsaleStartTime == 0 || now < preCrowdsaleEndTime) && tokensSent != TOKEN_CAP) {
throw;
}
if (!preCrowdsaleOwner.send(this.balance)) throw;
}
function processContribution(address sender) internal {
if (msg.value < MINIMUM_CONTRIBUTION) throw;
uint256 contributionInTokens = msg.value.mul(TOKENS_PER_ETHER).div(1 ether);
if (contributionInTokens.add(tokensSent) > TOKEN_CAP) throw;
token.transfer(sender, contributionInTokens);
Contributor contributor = contributors[sender];
contributor.received = contributor.received.add(contributionInTokens);
contributor.contributed = contributor.contributed.add(msg.value);
etherReceived = etherReceived.add(msg.value);
tokensSent = tokensSent.add(contributionInTokens);
TokensSent(sender, contributionInTokens);
ContributionReceived(sender, msg.value);
}
} | 0 |
pragma solidity ^0.4.23;
contract SmartContractWorkshop {
struct Person {
string name;
string email;
bool attendsInPerson;
bool purchased;
}
uint256 baseprice = 0.03 ether;
uint256 priceIncrease = 0.002 ether;
uint256 maxPrice = 0.07 ether;
address owner;
uint256 faceToFaceLimit = 24;
uint256 public ticketsSold;
uint256 public ticketsFaceToFaceSold;
string public eventWebsite;
mapping(address=>Person) public attendants;
address[] allAttendants;
address[] faceToFaceAttendants;
function SmartContractWorkshop (string _eventWebsite) {
owner = msg.sender;
eventWebsite = _eventWebsite;
}
function register(string _name, string _email, bool _attendsInPerson) payable {
require (msg.value == currentPrice() && attendants[msg.sender].purchased == false);
if(_attendsInPerson == true ) {
ticketsFaceToFaceSold++;
require (ticketsFaceToFaceSold <= faceToFaceLimit);
addAttendantAndTransfer(_name, _email, _attendsInPerson);
faceToFaceAttendants.push(msg.sender);
} else {
addAttendantAndTransfer(_name, _email, _attendsInPerson);
}
allAttendants.push(msg.sender);
}
function addAttendantAndTransfer(string _name, string _email, bool _attendsInPerson) internal {
attendants[msg.sender] = Person({
name: _name,
email: _email,
attendsInPerson: _attendsInPerson,
purchased: true
});
ticketsSold++;
owner.transfer(this.balance);
}
function listAllAttendants() external view returns(address[]){
return allAttendants;
}
function listFaceToFaceAttendants() external view returns(address[]){
return faceToFaceAttendants;
}
function hasPurchased() public view returns (bool) {
return attendants[msg.sender].purchased;
}
function currentPrice() public view returns (uint256) {
if(baseprice + (ticketsSold * priceIncrease) >= maxPrice) {
return maxPrice;
} else {
return baseprice + (ticketsSold * priceIncrease);
}
}
modifier onlyOwner() {
if(owner != msg.sender) {
revert();
} else {
_;
}
}
} | 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 = 3049920;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x51a64d8Dc61E38f1DDE51728AB03544972eCE151;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.21;
interface ISimpleCrowdsale {
function getSoftCap() external view returns(uint256);
function isContributorInLists(address contributorAddress) external view returns(bool);
function processReservationFundContribution(
address contributor,
uint256 tokenAmount,
uint256 tokenBonusAmount
) external payable;
}
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address previousOwner, address newOwner);
function Ownable(address _owner) public {
owner = _owner == address(0) ? msg.sender : _owner;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function confirmOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
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();
}
}
interface ICrowdsaleFund {
function processContribution(address contributor) external payable;
function onCrowdsaleEnd() external;
function enableCrowdsaleRefund() external;
}
interface ICrowdsaleReservationFund {
function canCompleteContribution(address contributor) external returns(bool);
function completeContribution(address contributor) external;
function processContribution(address contributor, uint256 _tokensToIssue, uint256 _bonusTokensToIssue) external payable;
function contributionsOf(address contributor) external returns(uint256);
function onCrowdsaleEnd() external;
}
contract IERC20Token {
string public name;
string public symbol;
uint8 public decimals;
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 SafeMath {
function SafeMath() public {
}
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(a >= b);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract LockedTokens is SafeMath {
struct Tokens {
uint256 amount;
uint256 lockEndTime;
bool released;
}
event TokensUnlocked(address _to, uint256 _value);
IERC20Token public token;
address public crowdsaleAddress;
mapping(address => Tokens[]) public walletTokens;
function LockedTokens(IERC20Token _token, address _crowdsaleAddress) public {
token = _token;
crowdsaleAddress = _crowdsaleAddress;
}
function addTokens(address _to, uint256 _amount, uint256 _lockEndTime) external {
require(msg.sender == crowdsaleAddress);
walletTokens[_to].push(Tokens({amount: _amount, lockEndTime: _lockEndTime, released: false}));
}
function releaseTokens() public {
require(walletTokens[msg.sender].length > 0);
for(uint256 i = 0; i < walletTokens[msg.sender].length; i++) {
if(!walletTokens[msg.sender][i].released && now >= walletTokens[msg.sender][i].lockEndTime) {
walletTokens[msg.sender][i].released = true;
token.transfer(msg.sender, walletTokens[msg.sender][i].amount);
TokensUnlocked(msg.sender, walletTokens[msg.sender][i].amount);
}
}
}
}
contract MultiOwnable {
address public manager;
address[] public owners;
mapping(address => bool) public ownerByAddress;
event SetOwners(address[] owners);
modifier onlyOwner() {
require(ownerByAddress[msg.sender] == true);
_;
}
function MultiOwnable() public {
manager = msg.sender;
}
function setOwners(address[] _owners) public {
require(msg.sender == manager);
_setOwners(_owners);
}
function _setOwners(address[] _owners) internal {
for(uint256 i = 0; i < owners.length; i++) {
ownerByAddress[owners[i]] = false;
}
for(uint256 j = 0; j < _owners.length; j++) {
ownerByAddress[_owners[j]] = true;
}
owners = _owners;
SetOwners(_owners);
}
function getOwners() public constant returns (address[]) {
return owners;
}
}
contract ERC20Token is IERC20Token, SafeMath {
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(balances[msg.sender] >= _value);
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, uint256 _value) public returns (bool) {
require(_to != address(0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256) {
return allowed[_owner][_spender];
}
}
interface ITokenEventListener {
function onTokenTransfer(address _from, address _to, uint256 _value) external;
}
contract ManagedToken is ERC20Token, MultiOwnable {
bool public allowTransfers = false;
bool public issuanceFinished = false;
ITokenEventListener public eventListener;
event AllowTransfersChanged(bool _newState);
event Issue(address indexed _to, uint256 _value);
event Destroy(address indexed _from, uint256 _value);
event IssuanceFinished();
modifier transfersAllowed() {
require(allowTransfers);
_;
}
modifier canIssue() {
require(!issuanceFinished);
_;
}
function ManagedToken(address _listener, address[] _owners) public {
if(_listener != address(0)) {
eventListener = ITokenEventListener(_listener);
}
_setOwners(_owners);
}
function setAllowTransfers(bool _allowTransfers) external onlyOwner {
allowTransfers = _allowTransfers;
AllowTransfersChanged(_allowTransfers);
}
function setListener(address _listener) public onlyOwner {
if(_listener != address(0)) {
eventListener = ITokenEventListener(_listener);
} else {
delete eventListener;
}
}
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool) {
bool success = super.transfer(_to, _value);
if(hasListener() && success) {
eventListener.onTokenTransfer(msg.sender, _to, _value);
}
return success;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool) {
bool success = super.transferFrom(_from, _to, _value);
if(hasListener() && success) {
eventListener.onTokenTransfer(_from, _to, _value);
}
return success;
}
function hasListener() internal view returns(bool) {
if(eventListener == address(0)) {
return false;
}
return true;
}
function issue(address _to, uint256 _value) external onlyOwner canIssue {
totalSupply = safeAdd(totalSupply, _value);
balances[_to] = safeAdd(balances[_to], _value);
Issue(_to, _value);
Transfer(address(0), _to, _value);
}
function destroy(address _from, uint256 _value) external {
require(ownerByAddress[msg.sender] || msg.sender == _from);
require(balances[_from] >= _value);
totalSupply = safeSub(totalSupply, _value);
balances[_from] = safeSub(balances[_from], _value);
Transfer(_from, address(0), _value);
Destroy(_from, _value);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender], _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function finishIssuance() public onlyOwner returns (bool) {
issuanceFinished = true;
IssuanceFinished();
return true;
}
}
contract TransferLimitedToken is ManagedToken {
uint256 public constant LIMIT_TRANSFERS_PERIOD = 365 days;
mapping(address => bool) public limitedWallets;
uint256 public limitEndDate;
address public limitedWalletsManager;
bool public isLimitEnabled;
event TransfersEnabled();
modifier onlyManager() {
require(msg.sender == limitedWalletsManager);
_;
}
modifier canTransfer(address _from, address _to) {
require(now >= limitEndDate || !isLimitEnabled || (!limitedWallets[_from] && !limitedWallets[_to]));
_;
}
function TransferLimitedToken(
uint256 _limitStartDate,
address _listener,
address[] _owners,
address _limitedWalletsManager
) public ManagedToken(_listener, _owners)
{
limitEndDate = _limitStartDate + LIMIT_TRANSFERS_PERIOD;
isLimitEnabled = true;
limitedWalletsManager = _limitedWalletsManager;
}
function enableTransfers() public {
require(msg.sender == limitedWalletsManager);
allowTransfers = true;
TransfersEnabled();
}
function addLimitedWalletAddress(address _wallet) public {
require(msg.sender == limitedWalletsManager || ownerByAddress[msg.sender]);
limitedWallets[_wallet] = true;
}
function delLimitedWalletAddress(address _wallet) public onlyManager {
limitedWallets[_wallet] = false;
}
function disableLimit() public onlyManager {
isLimitEnabled = false;
}
function transfer(address _to, uint256 _value) public canTransfer(msg.sender, _to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public canTransfer(_from, _to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public canTransfer(msg.sender, _spender) returns (bool) {
return super.approve(_spender,_value);
}
}
contract TheAbyssDAICO is Ownable, SafeMath, Pausable, ISimpleCrowdsale {
enum AdditionalBonusState {
Unavailable,
Active,
Applied
}
uint256 public constant ADDITIONAL_BONUS_NUM = 3;
uint256 public constant ADDITIONAL_BONUS_DENOM = 100;
uint256 public constant ETHER_MIN_CONTRIB = 0.2 ether;
uint256 public constant ETHER_MAX_CONTRIB = 20 ether;
uint256 public constant ETHER_MIN_CONTRIB_PRIVATE = 100 ether;
uint256 public constant ETHER_MAX_CONTRIB_PRIVATE = 3000 ether;
uint256 public constant ETHER_MIN_CONTRIB_USA = 0.2 ether;
uint256 public constant ETHER_MAX_CONTRIB_USA = 20 ether;
uint256 public constant SALE_START_TIME = 1524060000;
uint256 public constant SALE_END_TIME = 1526479200;
uint256 public constant BONUS_WINDOW_1_END_TIME = SALE_START_TIME + 2 days;
uint256 public constant BONUS_WINDOW_2_END_TIME = SALE_START_TIME + 7 days;
uint256 public constant BONUS_WINDOW_3_END_TIME = SALE_START_TIME + 14 days;
uint256 public constant BONUS_WINDOW_4_END_TIME = SALE_START_TIME + 21 days;
uint256 public constant MAX_CONTRIB_CHECK_END_TIME = SALE_START_TIME + 1 days;
uint256 public constant BNB_TOKEN_PRICE_NUM = 169;
uint256 public constant BNB_TOKEN_PRICE_DENOM = 1;
uint256 public tokenPriceNum = 0;
uint256 public tokenPriceDenom = 0;
TransferLimitedToken public token;
ICrowdsaleFund public fund;
ICrowdsaleReservationFund public reservationFund;
LockedTokens public lockedTokens;
mapping(address => bool) public whiteList;
mapping(address => bool) public privilegedList;
mapping(address => AdditionalBonusState) public additionalBonusOwnerState;
mapping(address => uint256) public userTotalContributed;
address public bnbTokenWallet;
address public referralTokenWallet;
address public foundationTokenWallet;
address public advisorsTokenWallet;
address public companyTokenWallet;
address public reserveTokenWallet;
address public bountyTokenWallet;
uint256 public totalEtherContributed = 0;
uint256 public rawTokenSupply = 0;
IERC20Token public bnbToken;
uint256 public BNB_HARD_CAP = 300000 ether;
uint256 public BNB_MIN_CONTRIB = 1000 ether;
mapping(address => uint256) public bnbContributions;
uint256 public totalBNBContributed = 0;
bool public bnbWithdrawEnabled = false;
uint256 public hardCap = 0;
uint256 public softCap = 0;
bool public bnbRefundEnabled = false;
event LogContribution(address contributor, uint256 amountWei, uint256 tokenAmount, uint256 tokenBonus, bool additionalBonusApplied, uint256 timestamp);
event ReservationFundContribution(address contributor, uint256 amountWei, uint256 tokensToIssue, uint256 bonusTokensToIssue, uint256 timestamp);
event LogBNBContribution(address contributor, uint256 amountBNB, uint256 tokenAmount, uint256 tokenBonus, bool additionalBonusApplied, uint256 timestamp);
modifier checkContribution() {
require(isValidContribution());
_;
}
modifier checkBNBContribution() {
require(isValidBNBContribution());
_;
}
modifier checkCap() {
require(validateCap());
_;
}
modifier checkTime() {
require(now >= SALE_START_TIME && now <= SALE_END_TIME);
_;
}
function TheAbyssDAICO(
address bnbTokenAddress,
address tokenAddress,
address fundAddress,
address reservationFundAddress,
address _bnbTokenWallet,
address _referralTokenWallet,
address _foundationTokenWallet,
address _advisorsTokenWallet,
address _companyTokenWallet,
address _reserveTokenWallet,
address _bountyTokenWallet,
address _owner
) public
Ownable(_owner)
{
require(tokenAddress != address(0));
bnbToken = IERC20Token(bnbTokenAddress);
token = TransferLimitedToken(tokenAddress);
fund = ICrowdsaleFund(fundAddress);
reservationFund = ICrowdsaleReservationFund(reservationFundAddress);
bnbTokenWallet = _bnbTokenWallet;
referralTokenWallet = _referralTokenWallet;
foundationTokenWallet = _foundationTokenWallet;
advisorsTokenWallet = _advisorsTokenWallet;
companyTokenWallet = _companyTokenWallet;
reserveTokenWallet = _reserveTokenWallet;
bountyTokenWallet = _bountyTokenWallet;
}
function isContributorInLists(address contributor) external view returns(bool) {
return whiteList[contributor] || privilegedList[contributor] || token.limitedWallets(contributor);
}
function isValidContribution() internal view returns(bool) {
uint256 currentUserContribution = safeAdd(msg.value, userTotalContributed[msg.sender]);
if(whiteList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB) {
if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB ) {
return false;
}
return true;
}
if(privilegedList[msg.sender] && msg.value >= ETHER_MIN_CONTRIB_PRIVATE) {
if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_PRIVATE ) {
return false;
}
return true;
}
if(token.limitedWallets(msg.sender) && msg.value >= ETHER_MIN_CONTRIB_USA) {
if(now <= MAX_CONTRIB_CHECK_END_TIME && currentUserContribution > ETHER_MAX_CONTRIB_USA) {
return false;
}
return true;
}
return false;
}
function validateCap() internal view returns(bool){
if(msg.value <= safeSub(hardCap, totalEtherContributed)) {
return true;
}
return false;
}
function setTokenPrice(uint256 _tokenPriceNum, uint256 _tokenPriceDenom) public onlyOwner {
require(tokenPriceNum == 0 && tokenPriceDenom == 0);
require(_tokenPriceNum > 0 && _tokenPriceDenom > 0);
tokenPriceNum = _tokenPriceNum;
tokenPriceDenom = _tokenPriceDenom;
}
function setHardCap(uint256 _hardCap) public onlyOwner {
require(hardCap == 0);
hardCap = _hardCap;
}
function setSoftCap(uint256 _softCap) public onlyOwner {
require(softCap == 0);
softCap = _softCap;
}
function getSoftCap() external view returns(uint256) {
return softCap;
}
function isValidBNBContribution() internal view returns(bool) {
if(token.limitedWallets(msg.sender)) {
return false;
}
if(!whiteList[msg.sender] && !privilegedList[msg.sender]) {
return false;
}
uint256 amount = bnbToken.allowance(msg.sender, address(this));
if(amount < BNB_MIN_CONTRIB || safeAdd(totalBNBContributed, amount) > BNB_HARD_CAP) {
return false;
}
return true;
}
function getBonus() internal constant returns (uint256, uint256) {
uint256 numerator = 0;
uint256 denominator = 100;
if(now < BONUS_WINDOW_1_END_TIME) {
numerator = 25;
} else if(now < BONUS_WINDOW_2_END_TIME) {
numerator = 15;
} else if(now < BONUS_WINDOW_3_END_TIME) {
numerator = 10;
} else if(now < BONUS_WINDOW_4_END_TIME) {
numerator = 5;
} else {
numerator = 0;
}
return (numerator, denominator);
}
function addToLists(
address _wallet,
bool isInWhiteList,
bool isInPrivilegedList,
bool isInLimitedList,
bool hasAdditionalBonus
) public onlyOwner {
if(isInWhiteList) {
whiteList[_wallet] = true;
}
if(isInPrivilegedList) {
privilegedList[_wallet] = true;
}
if(isInLimitedList) {
token.addLimitedWalletAddress(_wallet);
}
if(hasAdditionalBonus) {
additionalBonusOwnerState[_wallet] = AdditionalBonusState.Active;
}
if(reservationFund.canCompleteContribution(_wallet)) {
reservationFund.completeContribution(_wallet);
}
}
function addToWhiteList(address _wallet) public onlyOwner {
whiteList[_wallet] = true;
}
function addAdditionalBonusMember(address _wallet) public onlyOwner {
additionalBonusOwnerState[_wallet] = AdditionalBonusState.Active;
}
function addToPrivilegedList(address _wallet) public onlyOwner {
privilegedList[_wallet] = true;
}
function setLockedTokens(address lockedTokensAddress) public onlyOwner {
lockedTokens = LockedTokens(lockedTokensAddress);
}
function () payable public whenNotPaused {
if(whiteList[msg.sender] || privilegedList[msg.sender] || token.limitedWallets(msg.sender)) {
processContribution(msg.sender, msg.value);
} else {
processReservationContribution(msg.sender, msg.value);
}
}
function processReservationContribution(address contributor, uint256 amount) private checkTime checkCap {
require(amount >= ETHER_MIN_CONTRIB);
if(now <= MAX_CONTRIB_CHECK_END_TIME) {
uint256 currentUserContribution = safeAdd(amount, reservationFund.contributionsOf(contributor));
require(currentUserContribution <= ETHER_MAX_CONTRIB);
}
uint256 bonusNum = 0;
uint256 bonusDenom = 100;
(bonusNum, bonusDenom) = getBonus();
uint256 tokenBonusAmount = 0;
uint256 tokenAmount = safeDiv(safeMul(amount, tokenPriceNum), tokenPriceDenom);
if(bonusNum > 0) {
tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom);
}
reservationFund.processContribution.value(amount)(
contributor,
tokenAmount,
tokenBonusAmount
);
ReservationFundContribution(contributor, amount, tokenAmount, tokenBonusAmount, now);
}
function processBNBContribution() public whenNotPaused checkTime checkBNBContribution {
bool additionalBonusApplied = false;
uint256 bonusNum = 0;
uint256 bonusDenom = 100;
(bonusNum, bonusDenom) = getBonus();
uint256 amountBNB = bnbToken.allowance(msg.sender, address(this));
bnbToken.transferFrom(msg.sender, address(this), amountBNB);
bnbContributions[msg.sender] = safeAdd(bnbContributions[msg.sender], amountBNB);
uint256 tokenBonusAmount = 0;
uint256 tokenAmount = safeDiv(safeMul(amountBNB, BNB_TOKEN_PRICE_NUM), BNB_TOKEN_PRICE_DENOM);
rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount);
if(bonusNum > 0) {
tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom);
}
if(additionalBonusOwnerState[msg.sender] == AdditionalBonusState.Active) {
additionalBonusOwnerState[msg.sender] = AdditionalBonusState.Applied;
uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM);
tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus);
additionalBonusApplied = true;
}
uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount);
token.issue(msg.sender, tokenTotalAmount);
totalBNBContributed = safeAdd(totalBNBContributed, amountBNB);
LogBNBContribution(msg.sender, amountBNB, tokenAmount, tokenBonusAmount, additionalBonusApplied, now);
}
function processContribution(address contributor, uint256 amount) private checkTime checkContribution checkCap {
bool additionalBonusApplied = false;
uint256 bonusNum = 0;
uint256 bonusDenom = 100;
(bonusNum, bonusDenom) = getBonus();
uint256 tokenBonusAmount = 0;
uint256 tokenAmount = safeDiv(safeMul(amount, tokenPriceNum), tokenPriceDenom);
rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount);
if(bonusNum > 0) {
tokenBonusAmount = safeDiv(safeMul(tokenAmount, bonusNum), bonusDenom);
}
if(additionalBonusOwnerState[contributor] == AdditionalBonusState.Active) {
additionalBonusOwnerState[contributor] = AdditionalBonusState.Applied;
uint256 additionalBonus = safeDiv(safeMul(tokenAmount, ADDITIONAL_BONUS_NUM), ADDITIONAL_BONUS_DENOM);
tokenBonusAmount = safeAdd(tokenBonusAmount, additionalBonus);
additionalBonusApplied = true;
}
processPayment(contributor, amount, tokenAmount, tokenBonusAmount, additionalBonusApplied);
}
function processReservationFundContribution(
address contributor,
uint256 tokenAmount,
uint256 tokenBonusAmount
) external payable checkCap {
require(msg.sender == address(reservationFund));
require(msg.value > 0);
rawTokenSupply = safeAdd(rawTokenSupply, tokenAmount);
processPayment(contributor, msg.value, tokenAmount, tokenBonusAmount, false);
}
function processPayment(address contributor, uint256 etherAmount, uint256 tokenAmount, uint256 tokenBonusAmount, bool additionalBonusApplied) internal {
uint256 tokenTotalAmount = safeAdd(tokenAmount, tokenBonusAmount);
token.issue(contributor, tokenTotalAmount);
fund.processContribution.value(etherAmount)(contributor);
totalEtherContributed = safeAdd(totalEtherContributed, etherAmount);
userTotalContributed[contributor] = safeAdd(userTotalContributed[contributor], etherAmount);
LogContribution(contributor, etherAmount, tokenAmount, tokenBonusAmount, additionalBonusApplied, now);
}
function forceCrowdsaleRefund() public onlyOwner {
pause();
fund.enableCrowdsaleRefund();
reservationFund.onCrowdsaleEnd();
token.finishIssuance();
bnbRefundEnabled = true;
}
function finalizeCrowdsale() public onlyOwner {
if(
totalEtherContributed >= safeSub(hardCap, 1000 ether) ||
(now >= SALE_END_TIME && totalEtherContributed >= softCap)
) {
fund.onCrowdsaleEnd();
reservationFund.onCrowdsaleEnd();
bnbWithdrawEnabled = true;
uint256 referralTokenAmount = safeDiv(rawTokenSupply, 10);
token.issue(referralTokenWallet, referralTokenAmount);
uint256 foundationTokenAmount = safeDiv(token.totalSupply(), 2);
token.issue(address(lockedTokens), foundationTokenAmount);
lockedTokens.addTokens(foundationTokenWallet, foundationTokenAmount, now + 365 days);
uint256 suppliedTokenAmount = token.totalSupply();
uint256 reservedTokenAmount = safeDiv(safeMul(suppliedTokenAmount, 3), 10);
token.issue(address(lockedTokens), reservedTokenAmount);
lockedTokens.addTokens(reserveTokenWallet, reservedTokenAmount, now + 183 days);
uint256 advisorsTokenAmount = safeDiv(suppliedTokenAmount, 10);
token.issue(advisorsTokenWallet, advisorsTokenAmount);
uint256 companyTokenAmount = safeDiv(suppliedTokenAmount, 4);
token.issue(address(lockedTokens), companyTokenAmount);
lockedTokens.addTokens(companyTokenWallet, companyTokenAmount, now + 730 days);
uint256 bountyTokenAmount = safeDiv(suppliedTokenAmount, 60);
token.issue(bountyTokenWallet, bountyTokenAmount);
token.finishIssuance();
} else if(now >= SALE_END_TIME) {
fund.enableCrowdsaleRefund();
reservationFund.onCrowdsaleEnd();
token.finishIssuance();
bnbRefundEnabled = true;
}
}
function withdrawBNB() public onlyOwner {
require(bnbWithdrawEnabled);
if(bnbToken.balanceOf(address(this)) > 0) {
bnbToken.transfer(bnbTokenWallet, bnbToken.balanceOf(address(this)));
}
}
function refundBNBContributor() public {
require(bnbRefundEnabled);
require(bnbContributions[msg.sender] > 0);
uint256 amount = bnbContributions[msg.sender];
bnbContributions[msg.sender] = 0;
bnbToken.transfer(msg.sender, amount);
token.destroy(msg.sender, token.balanceOf(msg.sender));
}
} | 0 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
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);
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);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x / y;
return z;
}
}
contract StandardToken is ERC20, SafeMath {
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public returns (bool){
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSubtract(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) onlyPayloadSize(3 * 32) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSubtract(balances[_from], _value);
allowed[_from][msg.sender] = safeSubtract(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint) {
return balances[_owner];
}
function approve(address _spender, uint _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 (uint) {
return allowed[_owner][_spender];
}
}
contract REFERPAYToken is StandardToken {
string public constant name = "REFERPAYToken";
string public constant symbol = "REPT";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public constant total = 20 * (10**8) * 10**decimals;
function REFERPAYToken() public {
balances[msg.sender] = total;
Transfer(0x0, msg.sender, total);
}
function totalSupply() public view returns (uint256) {
return total;
}
function transfer(address _to, uint _value) public returns (bool) {
return super.transfer(_to,_value);
}
function approve(address _spender, uint _value) public returns (bool) {
return super.approve(_spender,_value);
}
function airdropToAddresses(address[] addrs, uint256 amount) public {
for (uint256 i = 0; i < addrs.length; i++) {
transfer(addrs[i], amount);
}
}
} | 1 |
pragma solidity 0.4.25;
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;
oraclize = OraclizeI(0);
}
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) view 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(abi.encodePacked(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(abi.encodePacked(sha256(abi.encodePacked(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(abi.encodePacked(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 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(), "Access denied");
_;
}
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), "Zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract TossCoin is Ownable, usingOraclize {
struct Game {
address addr;
uint bet;
bool option;
}
uint public min_bet = 0.05 ether;
uint public max_bet = 2 ether;
uint public rate = 195;
address public ethergames;
mapping(bytes32 => Game) public games;
mapping(address => address) public refferals;
event NewGame(bytes32 indexed id);
event FinishGame(bytes32 indexed id, address indexed addr, uint bet, bool option, bool result, uint win);
event Withdraw(address indexed to, uint value);
constructor() payable public {}
function() payable external {}
function __callback(bytes32 id, string res) public {
require(msg.sender == oraclize_cbAddress(), "Permission denied");
require(games[id].bet > 0, "Game not found");
bool result = parseInt(res) == 1;
uint win = games[id].option == result ? winSize(games[id].bet) : 0;
emit FinishGame(id, games[id].addr, games[id].bet, games[id].option, result, win);
if(win > 0) {
games[id].addr.transfer(win);
if(refferals[games[id].addr] != address(0)) {
refferals[games[id].addr].transfer(win / 100);
}
}
if(ethergames != address(0)) {
ethergames.call.value(games[id].bet / 100).gas(45000)();
}
delete games[id];
}
function winSize(uint bet) view public returns(uint) {
return bet * rate / 100;
}
function play(bool option, address refferal) payable external {
require(msg.value >= min_bet && msg.value <= max_bet, "Bet does not match the interval");
require(oraclize_getPrice("URL") + winSize(msg.value) <= address(this).balance, "Insufficient funds");
bytes32 id = oraclize_query("WolframAlpha", "RandomInteger[{0, 1}]");
games[id] = Game({
addr: msg.sender,
bet: msg.value,
option: option
});
if(refferal != address(0) && refferals[msg.sender] == address(0)) {
refferals[msg.sender] = refferal;
}
emit NewGame(id);
}
function play(bool option) payable external {
this.play(option, address(0));
}
function withdraw(address to, uint value) onlyOwner external {
require(to != address(0), "Zero address");
require(address(this).balance >= value, "Insufficient funds");
to.transfer(value);
emit Withdraw(to, value);
}
function setRate(uint value) onlyOwner external {
rate = value;
}
function setMinBet(uint value) onlyOwner external {
min_bet = value;
}
function setMaxBet(uint value) onlyOwner external {
max_bet = value;
}
function setEtherGames(address value) onlyOwner external {
if(ethergames == address(0)) {
ethergames = value;
}
}
} | 0 |
pragma solidity ^0.4.21;
contract LockRequestable {
uint256 public lockRequestCount;
function LockRequestable() public {
lockRequestCount = 0;
}
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(block.blockhash(block.number - 1), address(this), ++lockRequestCount);
}
}
contract CustodianUpgradeable is LockRequestable {
struct CustodianChangeRequest {
address proposedNew;
}
address public custodian;
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
function CustodianUpgradeable(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0));
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
require(changeRequest.proposedNew != 0);
return changeRequest.proposedNew;
}
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
}
contract ERC20ImplUpgradeable is CustodianUpgradeable {
struct ImplChangeRequest {
address proposedNew;
}
ERC20Impl public erc20Impl;
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
function ERC20ImplUpgradeable(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
modifier onlyImpl {
require(msg.sender == address(erc20Impl));
_;
}
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0));
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
require(changeRequest.proposedNew != address(0));
return ERC20Impl(changeRequest.proposedNew);
}
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
}
contract ERC20Interface {
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
string public name;
string public symbol;
uint8 public decimals;
function ERC20Proxy(
string _name,
string _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
function approve(address _spender, uint256 _value) public returns (bool success) {
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
}
contract ERC20Impl is CustodianUpgradeable {
struct PendingPrint {
address receiver;
uint256 value;
}
ERC20Proxy public erc20Proxy;
ERC20Store public erc20Store;
address public sweeper;
bytes32 public sweepMsg;
mapping (address => bool) public sweptSet;
mapping (bytes32 => PendingPrint) public pendingPrintMap;
function ERC20Impl(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != 0);
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(address(this), "sweep");
}
modifier onlyProxy {
require(msg.sender == address(erc20Proxy));
_;
}
modifier onlySweeper {
require(msg.sender == sweeper);
_;
}
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0));
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance);
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0));
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
address receiver = print.receiver;
require (receiver != address(0));
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
function burn(uint256 _value) public returns (bool success) {
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
function batchTransfer(address[] _tos, uint256[] _values) public returns (bool success) {
require(_tos.length == _values.length);
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0));
uint256 v = _values[i];
require(senderBalance >= v);
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
function enableSweep(uint8[] _vs, bytes32[] _rs, bytes32[] _ss, address _to) public onlySweeper {
require(_to != address(0));
require((_vs.length == _rs.length) && (_vs.length == _ss.length));
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i=0; i<numSignatures; ++i) {
address from = ecrecover(sweepMsg, _vs[i], _rs[i], _ss[i]);
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
function replaySweep(address[] _froms, address _to) public onlySweeper {
require(_to != address(0));
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i=0; i<lenFroms; ++i) {
address from = _froms[i];
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom);
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance);
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0));
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender);
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
}
contract ERC20Store is ERC20ImplUpgradeable {
uint256 public totalSupply;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
function ERC20Store(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
}
contract PrintLimiter is LockRequestable {
struct PendingCeilingRaise {
uint256 raiseBy;
}
ERC20Impl public erc20Impl;
address public custodian;
address public limitedPrinter;
uint256 public totalSupplyCeiling;
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
function PrintLimiter(
address _erc20Impl,
address _custodian,
address _limitedPrinter,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = _custodian;
limitedPrinter = _limitedPrinter;
totalSupplyCeiling = _initialCeiling;
}
modifier onlyCustodian {
require(msg.sender == custodian);
_;
}
modifier onlyLimitedPrinter {
require(msg.sender == limitedPrinter);
_;
}
function limitedPrint(address _receiver, uint256 _value) public onlyLimitedPrinter {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply);
require(newTotalSupply <= totalSupplyCeiling);
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0);
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
uint256 raiseBy = pendingRaise.raiseBy;
require(raiseBy != 0);
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
function lowerCeiling(uint256 _lowerBy) public onlyLimitedPrinter {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
require(newCeiling <= totalSupplyCeiling);
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
} | 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 = 0xF7F55565f31b266D3e8AcD45fC96DDdaf12f9573;
}
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;
contract IERC20Token {
function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view 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 IWhitelist {
function isWhitelisted(address _address) public view returns (bool);
}
contract IBancorConverter {
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256, uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
function conversionWhitelist() public view returns (IWhitelist) {}
function conversionFee() public view returns (uint32) {}
function connectors(address _address) public view returns (uint256, uint32, bool, bool, bool) { _address; }
function getConnectorBalance(IERC20Token _connectorToken) public view returns (uint256);
function claimTokens(address _from, uint256 _amount) public;
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
contract IBancorConverterUpgrader {
function upgrade(bytes32 _version) public;
}
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
contract IBancorNetwork {
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);
function convertForPrioritized2(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s)
public payable returns (uint256);
function convertForPrioritized(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _block,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s)
public payable returns (uint256);
}
contract ContractIds {
bytes32 public constant CONTRACT_FEATURES = "ContractFeatures";
bytes32 public constant CONTRACT_REGISTRY = "ContractRegistry";
bytes32 public constant BANCOR_NETWORK = "BancorNetwork";
bytes32 public constant BANCOR_FORMULA = "BancorFormula";
bytes32 public constant BANCOR_GAS_PRICE_LIMIT = "BancorGasPriceLimit";
bytes32 public constant BANCOR_CONVERTER_UPGRADER = "BancorConverterUpgrader";
bytes32 public constant BANCOR_CONVERTER_FACTORY = "BancorConverterFactory";
bytes32 public constant BNT_TOKEN = "BNTToken";
bytes32 public constant BNT_CONVERTER = "BNTConverter";
bytes32 public constant BANCOR_X = "BancorX";
}
contract FeatureIds {
uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
}
contract IOwned {
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
constructor() public {
owner = msg.sender;
}
modifier ownerOnly {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract Managed is Owned {
address public manager;
address public newManager;
event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
constructor() public {
manager = msg.sender;
}
modifier managerOnly {
assert(msg.sender == manager);
_;
}
modifier ownerOrManagerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
function transferManagement(address _newManager) public ownerOrManagerOnly {
require(_newManager != manager);
newManager = _newManager;
}
function acceptManagement() public {
require(msg.sender == newManager);
emit ManagerUpdate(manager, newManager);
manager = newManager;
newManager = address(0);
}
}
contract Utils {
constructor() public {
}
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IContractRegistry {
function addressOf(bytes32 _contractName) public view returns (address);
function getAddress(bytes32 _contractName) public view returns (address);
}
contract IContractFeatures {
function isSupported(address _contract, uint256 _features) public view returns (bool);
function enableFeatures(uint256 _features, bool _enable) 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 ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract TokenHolder is ITokenHolder, Owned, Utils {
constructor() public {
}
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;
constructor(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
modifier active() {
require(token.owner() == address(this));
_;
}
modifier inactive() {
require(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 IEtherToken is ITokenHolder, IERC20Token {
function deposit() public payable;
function withdraw(uint256 _amount) public;
function withdrawTo(address _to, uint256 _amount) public;
}
contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds {
uint32 private constant MAX_WEIGHT = 1000000;
uint64 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance;
uint32 weight;
bool isVirtualBalanceEnabled;
bool isPurchaseEnabled;
bool isSet;
}
bytes32 public version = '0.11';
string public converterType = 'bancor';
bool public allowRegistryUpdate = true;
bool public claimTokensEnabled = false;
IContractRegistry public prevRegistry;
IContractRegistry public registry;
IWhitelist public conversionWhitelist;
IERC20Token[] public connectorTokens;
mapping (address => Connector) public connectors;
uint32 private totalConnectorWeight = 0;
uint32 public maxConversionFee = 0;
uint32 public conversionFee = 0;
bool public conversionsEnabled = true;
IERC20Token[] private convertPath;
event Conversion(
address indexed _fromToken,
address indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
event PriceDataUpdate(
address indexed _connectorToken,
uint256 _tokenSupply,
uint256 _connectorBalance,
uint32 _connectorWeight
);
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
event ConversionsEnable(bool _conversionsEnabled);
constructor(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _connectorToken,
uint32 _connectorWeight
)
public
SmartTokenController(_token)
validAddress(_registry)
validMaxConversionFee(_maxConversionFee)
{
registry = _registry;
prevRegistry = _registry;
IContractFeatures features = IContractFeatures(registry.addressOf(ContractIds.CONTRACT_FEATURES));
if (features != address(0))
features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true);
maxConversionFee = _maxConversionFee;
if (_connectorToken != address(0))
addConnector(_connectorToken, _connectorWeight, false);
}
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
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 maxTotalWeightOnly() {
require(totalConnectorWeight == MAX_WEIGHT);
_;
}
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
modifier bancorNetworkOnly {
IBancorNetwork bancorNetwork = IBancorNetwork(registry.addressOf(ContractIds.BANCOR_NETWORK));
require(msg.sender == address(bancorNetwork));
_;
}
modifier converterUpgraderOnly {
address converterUpgrader = registry.addressOf(ContractIds.BANCOR_CONVERTER_UPGRADER);
require(owner == converterUpgrader);
_;
}
modifier whenClaimTokensEnabled {
require(claimTokensEnabled);
_;
}
function updateRegistry() public {
require(allowRegistryUpdate || msg.sender == owner);
address newRegistry = registry.addressOf(ContractIds.CONTRACT_REGISTRY);
require(newRegistry != address(registry) && newRegistry != address(0));
prevRegistry = registry;
registry = IContractRegistry(newRegistry);
}
function restoreRegistry() public ownerOrManagerOnly {
registry = prevRegistry;
allowRegistryUpdate = false;
}
function disableRegistryUpdate(bool _disable) public ownerOrManagerOnly {
allowRegistryUpdate = !_disable;
}
function enableClaimTokens(bool _enable) public ownerOnly {
claimTokensEnabled = _enable;
}
function connectorTokenCount() public view returns (uint16) {
return uint16(connectorTokens.length);
}
function setConversionWhitelist(IWhitelist _whitelist)
public
ownerOnly
notThis(_whitelist)
{
conversionWhitelist = _whitelist;
}
function disableConversions(bool _disable) public ownerOrManagerOnly {
if (conversionsEnabled == _disable) {
conversionsEnabled = !_disable;
emit ConversionsEnable(conversionsEnabled);
}
}
function transferTokenOwnership(address _newOwner)
public
ownerOnly
converterUpgraderOnly
{
super.transferTokenOwnership(_newOwner);
}
function setConversionFee(uint32 _conversionFee)
public
ownerOrManagerOnly
validConversionFee(_conversionFee)
{
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) {
return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude;
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public {
address converterUpgrader = registry.addressOf(ContractIds.BANCOR_CONVERTER_UPGRADER);
require(!connectors[_token].isSet || token.owner() != address(this) || owner == converterUpgrader);
super.withdrawTokens(_token, _to, _amount);
}
function claimTokens(address _from, uint256 _amount) public whenClaimTokensEnabled {
address bancorX = registry.addressOf(ContractIds.BANCOR_X);
require(msg.sender == bancorX);
token.destroy(_from, _amount);
token.issue(bancorX, _amount);
}
function upgrade() public ownerOnly {
IBancorConverterUpgrader converterUpgrader = IBancorConverterUpgrader(registry.addressOf(ContractIds.BANCOR_CONVERTER_UPGRADER));
transferOwnership(converterUpgrader);
converterUpgrader.upgrade(version);
acceptOwnership();
}
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
view
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 view returns (uint256, uint256) {
require(_fromToken != _toToken);
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
return getCrossConnectorReturn(_fromToken, _toToken, _amount);
}
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256, uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled);
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
uint256 finalAmount = getFinalAmount(amount, 1);
return (finalAmount, amount - finalAmount);
}
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256, uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount);
uint256 finalAmount = getFinalAmount(amount, 1);
return (finalAmount, amount - finalAmount);
}
function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount)
public
view
active
validConnector(_fromConnectorToken)
validConnector(_toConnectorToken)
returns (uint256, uint256)
{
Connector storage fromConnector = connectors[_fromConnectorToken];
Connector storage toConnector = connectors[_toConnectorToken];
require(toConnector.isPurchaseEnabled);
IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculateCrossConnectorReturn(
getConnectorBalance(_fromConnectorToken),
fromConnector.weight,
getConnectorBalance(_toConnectorToken),
toConnector.weight,
_sellAmount);
uint256 finalAmount = getFinalAmount(amount, 2);
return (finalAmount, amount - finalAmount);
}
function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn)
public
bancorNetworkOnly
conversionsAllowed
greaterThanZero(_minReturn)
returns (uint256)
{
require(_fromToken != _toToken);
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
uint256 amount;
uint256 feeAmount;
(amount, feeAmount) = getCrossConnectorReturn(_fromToken, _toToken, _amount);
require(amount != 0 && amount >= _minReturn);
Connector storage fromConnector = connectors[_fromToken];
if (fromConnector.isVirtualBalanceEnabled)
fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount);
Connector storage toConnector = connectors[_toToken];
if (toConnector.isVirtualBalanceEnabled)
toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount);
uint256 toConnectorBalance = getConnectorBalance(_toToken);
assert(amount < toConnectorBalance);
assert(_fromToken.transferFrom(msg.sender, this, _amount));
assert(_toToken.transfer(msg.sender, amount));
dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount);
emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight);
emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight);
return amount;
}
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
convertPath = [_fromToken, token, _toToken];
return quickConvert(convertPath, _amount, _minReturn);
}
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
uint256 amount;
uint256 feeAmount;
(amount, feeAmount) = getPurchaseReturn(_connectorToken, _depositAmount);
require(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);
dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount);
emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);
return amount;
}
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) {
require(_sellAmount <= token.balanceOf(msg.sender));
uint256 amount;
uint256 feeAmount;
(amount, feeAmount) = getSaleReturn(_connectorToken, _sellAmount);
require(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));
dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount);
emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);
return amount;
}
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0);
}
function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorNetwork bancorNetwork = IBancorNetwork(registry.addressOf(ContractIds.BANCOR_NETWORK));
if (msg.value == 0) {
if (fromToken == token) {
token.destroy(msg.sender, _amount);
token.issue(bancorNetwork, _amount);
} else {
assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount));
}
}
return bancorNetwork.convertForPrioritized2.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s);
}
function fund(uint256 _amount)
public
maxTotalWeightOnly
conversionsAllowed
{
uint256 supply = token.totalSupply();
IERC20Token connectorToken;
uint256 connectorBalance;
uint256 connectorAmount;
for (uint16 i = 0; i < connectorTokens.length; i++) {
connectorToken = connectorTokens[i];
connectorBalance = getConnectorBalance(connectorToken);
connectorAmount = safeMul(_amount, connectorBalance) / supply;
Connector storage connector = connectors[connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, connectorAmount);
assert(connectorToken.transferFrom(msg.sender, this, connectorAmount));
emit PriceDataUpdate(connectorToken, supply + _amount, connectorBalance + connectorAmount, connector.weight);
}
token.issue(msg.sender, _amount);
}
function liquidate(uint256 _amount) public maxTotalWeightOnly {
uint256 supply = token.totalSupply();
token.destroy(msg.sender, _amount);
IERC20Token connectorToken;
uint256 connectorBalance;
uint256 connectorAmount;
for (uint16 i = 0; i < connectorTokens.length; i++) {
connectorToken = connectorTokens[i];
connectorBalance = getConnectorBalance(connectorToken);
connectorAmount = safeMul(_amount, connectorBalance) / supply;
Connector storage connector = connectors[connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, connectorAmount);
assert(connectorToken.transfer(msg.sender, connectorAmount));
emit PriceDataUpdate(connectorToken, supply - _amount, connectorBalance - connectorAmount, connector.weight);
}
}
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convertInternal(_fromToken, _toToken, _amount, _minReturn);
}
function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
assert(_feeAmount <= 2 ** 255);
emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));
}
} | 0 |
pragma solidity ^0.4.15;
contract Oracle {
event NewSymbol(string _symbol, uint8 _decimals);
function getTimestamp(string symbol) constant returns(uint256);
function getRateFor(string symbol) returns (uint256);
function getCost(string symbol) constant returns (uint256);
function getDecimals(string symbol) constant returns (uint256);
}
contract Token {
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
function approve(address _spender, uint256 _value) returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract RpSafeMath {
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;
}
function min(uint256 a, uint256 b) internal returns(uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal returns(uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
}
contract NanoLoanEngine is RpSafeMath {
uint256 public constant VERSION = 15;
Token public token;
enum Status { initial, lent, paid, destroyed }
address public owner;
bool public deprecated;
uint256 public totalLenderBalance;
event CreatedLoan(uint _index, address _borrower, address _creator);
event ApprovedBy(uint _index, address _address);
event Lent(uint _index, address _lender);
event CreatedDebt(uint _index, address _lend);
event DestroyedBy(uint _index, address _address);
event PartialPayment(uint _index, address _sender, address _from, uint256 _amount);
event Transfer(uint _index, address _from, address _to);
event TotalPayment(uint _index);
function NanoLoanEngine(Token _token) {
owner = msg.sender;
token = _token;
}
struct Loan {
Oracle oracle;
Status status;
address borrower;
address cosigner;
address lender;
address creator;
uint256 amount;
uint256 interest;
uint256 punitoryInterest;
uint256 interestTimestamp;
uint256 paid;
uint256 cosignerFee;
uint256 interestRate;
uint256 interestRatePunitory;
uint256 dueTime;
uint256 duesIn;
string currency;
uint256 cancelableAt;
uint256 lenderBalance;
address approvedTransfer;
uint256 expirationRequest;
mapping(address => bool) approbations;
}
Loan[] private loans;
function createLoan(Oracle _oracleContract, address _borrower, address _cosigner,
uint256 _cosignerFee, string _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest) returns (uint256) {
require(!deprecated);
require(_cancelableAt <= _duesIn);
require(_oracleContract != address(0) || bytes(_currency).length == 0);
require(_cosigner != address(0) || _cosignerFee == 0);
require(_borrower != address(0));
require(_amount != 0);
require(_interestRatePunitory != 0);
require(_interestRate != 0);
require(_expirationRequest > block.timestamp);
var loan = Loan(_oracleContract, Status.initial, _borrower, _cosigner, 0x0, msg.sender, _amount,
0, 0, 0, 0, _cosignerFee, _interestRate, _interestRatePunitory, 0, _duesIn, _currency, _cancelableAt, 0, 0x0, _expirationRequest);
uint index = loans.push(loan) - 1;
CreatedLoan(index, _borrower, msg.sender);
return index;
}
function getLoanConfig(uint index) constant returns (address oracle, address borrower, address lender, address creator, uint amount,
uint cosignerFee, uint interestRate, uint interestRatePunitory, uint duesIn, uint cancelableAt, uint decimals, bytes32 currencyHash, uint256 expirationRequest) {
Loan storage loan = loans[index];
oracle = loan.oracle;
borrower = loan.borrower;
lender = loan.lender;
creator = loan.creator;
amount = loan.amount;
cosignerFee = loan.cosignerFee;
interestRate = loan.interestRate;
interestRatePunitory = loan.interestRatePunitory;
duesIn = loan.duesIn;
cancelableAt = loan.cancelableAt;
decimals = loan.oracle.getDecimals(loan.currency);
currencyHash = keccak256(loan.currency);
expirationRequest = loan.expirationRequest;
}
function getLoanState(uint index) constant returns (uint interest, uint punitoryInterest, uint interestTimestamp,
uint paid, uint dueTime, Status status, uint lenderBalance, address approvedTransfer, bool approved) {
Loan storage loan = loans[index];
interest = loan.interest;
punitoryInterest = loan.punitoryInterest;
interestTimestamp = loan.interestTimestamp;
paid = loan.paid;
dueTime = loan.dueTime;
status = loan.status;
lenderBalance = loan.lenderBalance;
approvedTransfer = loan.approvedTransfer;
approved = isApproved(index);
}
function getTotalLoans() constant returns (uint256) { return loans.length; }
function getOracle(uint index) constant returns (Oracle) { return loans[index].oracle; }
function getBorrower(uint index) constant returns (address) { return loans[index].borrower; }
function getCosigner(uint index) constant returns (address) { return loans[index].cosigner; }
function getLender(uint index) constant returns (address) { return loans[index].lender; }
function getCreator(uint index) constant returns (address) { return loans[index].creator; }
function getAmount(uint index) constant returns (uint256) { return loans[index].amount; }
function getInterest(uint index) constant returns (uint256) { return loans[index].interest; }
function getPunitoryInterest(uint index) constant returns (uint256) { return loans[index].punitoryInterest; }
function getInterestTimestamp(uint index) constant returns (uint256) { return loans[index].interestTimestamp; }
function getPaid(uint index) constant returns (uint256) { return loans[index].paid; }
function getCosignerFee(uint index) constant returns (uint256) { return loans[index].cosignerFee; }
function getInterestRate(uint index) constant returns (uint256) { return loans[index].interestRate; }
function getInterestRatePunitory(uint index) constant returns (uint256) { return loans[index].interestRatePunitory; }
function getDueTime(uint index) constant returns (uint256) { return loans[index].dueTime; }
function getDuesIn(uint index) constant returns (uint256) { return loans[index].duesIn; }
function getCurrency(uint index) constant returns (string) { return loans[index].currency; }
function getCancelableAt(uint index) constant returns (uint256) { return loans[index].cancelableAt; }
function getApprobation(uint index, address _address) constant returns (bool) { return loans[index].approbations[_address]; }
function getStatus(uint index) constant returns (Status) { return loans[index].status; }
function getLenderBalance(uint index) constant returns (uint256) { return loans[index].lenderBalance; }
function getCurrencyLength(uint index) constant returns (uint256) { return bytes(loans[index].currency).length; }
function getCurrencyByte(uint index, uint cindex) constant returns (bytes1) { return bytes(loans[index].currency)[cindex]; }
function getApprovedTransfer(uint index) constant returns (address) {return loans[index].approvedTransfer; }
function getCurrencyHash(uint index) constant returns (bytes32) { return keccak256(loans[index].currency); }
function getCurrencyDecimals(uint index) constant returns (uint256) { return loans[index].oracle.getDecimals(loans[index].currency); }
function getExpirationRequest(uint index) constant returns (uint256) { return loans[index].expirationRequest; }
function isApproved(uint index) constant returns (bool) {
Loan storage loan = loans[index];
return loan.approbations[loan.borrower] && (loan.approbations[loan.cosigner] || loan.cosigner == address(0));
}
function approve(uint index) public returns(bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
loan.approbations[msg.sender] = true;
ApprovedBy(index, msg.sender);
return true;
}
function lend(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.initial);
require(isApproved(index));
require(block.timestamp <= loan.expirationRequest);
loan.lender = msg.sender;
loan.dueTime = safeAdd(block.timestamp, loan.duesIn);
loan.interestTimestamp = block.timestamp;
loan.status = Status.lent;
if (loan.cancelableAt > 0)
internalAddInterest(index, safeAdd(block.timestamp, loan.cancelableAt));
uint256 rate = getOracleRate(index);
require(token.transferFrom(msg.sender, loan.borrower, safeMult(loan.amount, rate)));
if (loan.cosigner != address(0))
require(token.transferFrom(msg.sender, loan.cosigner, safeMult(loan.cosignerFee, rate)));
Lent(index, loan.lender);
return true;
}
function destroy(uint index) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status != Status.destroyed);
require(msg.sender == loan.lender || ((msg.sender == loan.borrower || msg.sender == loan.cosigner) && loan.status == Status.initial));
DestroyedBy(index, msg.sender);
loan.status = Status.destroyed;
return true;
}
function transfer(uint index, address to) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status != Status.destroyed);
require(msg.sender == loan.lender || msg.sender == loan.approvedTransfer);
require(to != address(0));
Transfer(index, loan.lender, to);
loan.lender = to;
loan.approvedTransfer = address(0);
return true;
}
function approveTransfer(uint index, address to) public returns (bool) {
Loan storage loan = loans[index];
require(msg.sender == loan.lender);
loan.approvedTransfer = to;
return true;
}
function getPendingAmount(uint index) public constant returns (uint256) {
Loan storage loan = loans[index];
return safeSubtract(safeAdd(safeAdd(loan.amount, loan.interest), loan.punitoryInterest), loan.paid);
}
function calculateInterest(uint256 timeDelta, uint256 interestRate, uint256 amount) public constant returns (uint256 realDelta, uint256 interest) {
interest = safeMult(safeMult(100000, amount), timeDelta) / interestRate;
realDelta = safeMult(interest, interestRate) / (amount * 100000);
}
function internalAddInterest(uint index, uint256 timestamp) internal {
Loan storage loan = loans[index];
if (timestamp > loan.interestTimestamp) {
uint256 newInterest = loan.interest;
uint256 newPunitoryInterest = loan.punitoryInterest;
uint256 newTimestamp;
uint256 realDelta;
uint256 calculatedInterest;
uint256 deltaTime;
uint256 pending;
uint256 endNonPunitory = min(timestamp, loan.dueTime);
if (endNonPunitory > loan.interestTimestamp) {
deltaTime = safeSubtract(endNonPunitory, loan.interestTimestamp);
pending = safeSubtract(loan.amount, loan.paid);
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRate, pending);
newInterest = safeAdd(calculatedInterest, newInterest);
newTimestamp = loan.interestTimestamp + realDelta;
}
if (timestamp > loan.dueTime) {
uint256 startPunitory = max(loan.dueTime, loan.interestTimestamp);
deltaTime = safeSubtract(timestamp, startPunitory);
pending = safeSubtract(safeAdd(loan.amount, newInterest), loan.paid);
(realDelta, calculatedInterest) = calculateInterest(deltaTime, loan.interestRatePunitory, pending);
newPunitoryInterest = safeAdd(newPunitoryInterest, calculatedInterest);
newTimestamp = startPunitory + realDelta;
}
if (newInterest != loan.interest || newPunitoryInterest != loan.punitoryInterest) {
loan.interestTimestamp = newTimestamp;
loan.interest = newInterest;
loan.punitoryInterest = newPunitoryInterest;
}
}
}
function addInterestUpTo(uint index, uint256 timestamp) internal {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
if (timestamp <= block.timestamp) {
internalAddInterest(index, timestamp);
}
}
function addInterest(uint index) public {
addInterestUpTo(index, block.timestamp);
}
function pay(uint index, uint256 _amount, address _from) public returns (bool) {
Loan storage loan = loans[index];
require(loan.status == Status.lent);
addInterest(index);
uint256 toPay = min(getPendingAmount(index), _amount);
loan.paid = safeAdd(loan.paid, toPay);
if (getPendingAmount(index) == 0) {
TotalPayment(index);
loan.status = Status.paid;
}
uint256 transferValue = safeMult(toPay, getOracleRate(index));
require(token.transferFrom(msg.sender, this, transferValue));
loan.lenderBalance = safeAdd(transferValue, loan.lenderBalance);
totalLenderBalance = safeAdd(transferValue, totalLenderBalance);
PartialPayment(index, msg.sender, _from, toPay);
return true;
}
function withdrawal(uint index, address to, uint256 amount) public returns (bool) {
Loan storage loan = loans[index];
require(to != address(0));
if (msg.sender == loan.lender && loan.lenderBalance >= amount) {
loan.lenderBalance = safeSubtract(loan.lenderBalance, amount);
totalLenderBalance = safeSubtract(totalLenderBalance, amount);
require(token.transfer(to, amount));
return true;
}
}
function changeOwner(address to) public {
require(msg.sender == owner);
require(to != address(0));
owner = to;
}
function setDeprecated(bool _deprecated) public {
require(msg.sender == owner);
deprecated = _deprecated;
}
function getOracleRate(uint index) internal returns (uint256) {
Loan storage loan = loans[index];
if (loan.oracle == address(0))
return 1;
uint256 costOracle = loan.oracle.getCost(loan.currency);
require(token.transferFrom(msg.sender, this, costOracle));
require(token.approve(loan.oracle, costOracle));
uint256 rate = loan.oracle.getRateFor(loan.currency);
require(rate != 0);
return rate;
}
function emergencyWithdrawal(Token _token, address to, uint256 amount) returns (bool) {
require(msg.sender == owner);
require(_token != token || safeSubtract(token.balanceOf(this), totalLenderBalance) >= amount);
require(to != address(0));
return _token.transfer(to, amount);
}
} | 0 |
pragma solidity ^0.4.24;
contract Dice2Win {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 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;
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(address beneficiary, 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 / 100;
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.send(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.19;
interface ChiToken {
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
contract ChiTrader {
ChiToken Chi = ChiToken(0x71E1f8E809Dc8911FCAC95043bC94929a36505A5);
address public seller;
uint256 public price;
uint256 public Chi_available;
uint256 public Amount_of_Chi_for_One_ETH;
uint256 cooldown_start_time;
function ChiTrader() public {
seller = 0x0;
price = 0;
Chi_available = 0;
Amount_of_Chi_for_One_ETH = 0;
cooldown_start_time = 0;
}
function is_empty() public view returns (bool) {
return (now - cooldown_start_time > 1 hours) && (this.balance==0) && (Chi.balanceOf(this) == 0);
}
function setup(uint256 chi_amount, uint256 price_in_wei) public {
require(is_empty());
require(Chi.allowance(msg.sender, this) >= chi_amount);
require(price_in_wei > 1000);
price = price_in_wei;
Chi_available = chi_amount;
Amount_of_Chi_for_One_ETH = 1 ether / price_in_wei;
seller = msg.sender;
require(Chi.transferFrom(msg.sender, this, chi_amount));
}
function() public payable{
uint256 eth_balance = this.balance;
uint256 chi_balance = Chi.balanceOf(this);
if(msg.sender == seller){
seller = 0x0;
price = 0;
Chi_available = 0;
Amount_of_Chi_for_One_ETH = 0;
cooldown_start_time = now;
if(eth_balance > 0) msg.sender.transfer(eth_balance);
if(chi_balance > 0) require(Chi.transfer(msg.sender, chi_balance));
}
else{
require(msg.value > 0);
require(price > 0);
uint256 num_chi = msg.value / price;
require(chi_balance >= num_chi);
Chi_available = chi_balance - num_chi;
require(Chi.transfer(msg.sender, num_chi));
}
}
} | 0 |
pragma solidity ^0.4.9;
contract TownCrier {
struct Request {
address requester;
uint fee;
address callbackAddr;
bytes4 callbackFID;
bytes32 paramsHash;
}
event Upgrade(address newAddr);
event Reset(uint gas_price, uint min_fee, uint cancellation_fee);
event RequestInfo(uint64 id, uint8 requestType, address requester, uint fee, address callbackAddr, bytes32 paramsHash, uint timestamp, bytes32[] requestData);
event DeliverInfo(uint64 requestId, uint fee, uint gasPrice, uint gasLeft, uint callbackGas, bytes32 paramsHash, uint64 error, bytes32 respData);
event Cancel(uint64 requestId, address canceller, address requester, uint fee, int flag);
address public constant SGX_ADDRESS = 0x18513702cCd928F2A3eb63d900aDf03c9cc81593;
uint public GAS_PRICE = 5 * 10**10;
uint public MIN_FEE = 30000 * GAS_PRICE;
uint public CANCELLATION_FEE = 25000 * GAS_PRICE;
uint public constant CANCELLED_FEE_FLAG = 1;
uint public constant DELIVERED_FEE_FLAG = 0;
int public constant FAIL_FLAG = -2 ** 250;
int public constant SUCCESS_FLAG = 1;
bool public killswitch;
bool public externalCallFlag;
uint64 public requestCnt;
uint64 public unrespondedCnt;
Request[2**64] public requests;
int public newVersion = 0;
function () {}
function TownCrier() public {
requestCnt = 1;
requests[0].requester = msg.sender;
killswitch = false;
unrespondedCnt = 0;
externalCallFlag = false;
}
function upgrade(address newAddr) {
if (msg.sender == requests[0].requester && unrespondedCnt == 0) {
newVersion = -int(newAddr);
killswitch = true;
Upgrade(newAddr);
}
}
function reset(uint price, uint minGas, uint cancellationGas) public {
if (msg.sender == requests[0].requester && unrespondedCnt == 0) {
GAS_PRICE = price;
MIN_FEE = price * minGas;
CANCELLATION_FEE = price * cancellationGas;
Reset(GAS_PRICE, MIN_FEE, CANCELLATION_FEE);
}
}
function suspend() public {
if (msg.sender == requests[0].requester) {
killswitch = true;
}
}
function restart() public {
if (msg.sender == requests[0].requester && newVersion == 0) {
killswitch = false;
}
}
function withdraw() public {
if (msg.sender == requests[0].requester && unrespondedCnt == 0) {
if (!requests[0].requester.call.value(this.balance)()) {
throw;
}
}
}
function request(uint8 requestType, address callbackAddr, bytes4 callbackFID, uint timestamp, bytes32[] requestData) public payable returns (int) {
if (externalCallFlag) {
throw;
}
if (killswitch) {
externalCallFlag = true;
if (!msg.sender.call.value(msg.value)()) {
throw;
}
externalCallFlag = false;
return newVersion;
}
if (msg.value < MIN_FEE) {
externalCallFlag = true;
if (!msg.sender.call.value(msg.value)()) {
throw;
}
externalCallFlag = false;
return FAIL_FLAG;
} else {
uint64 requestId = requestCnt;
requestCnt++;
unrespondedCnt++;
bytes32 paramsHash = sha3(requestType, requestData);
requests[requestId].requester = msg.sender;
requests[requestId].fee = msg.value;
requests[requestId].callbackAddr = callbackAddr;
requests[requestId].callbackFID = callbackFID;
requests[requestId].paramsHash = paramsHash;
RequestInfo(requestId, requestType, msg.sender, msg.value, callbackAddr, paramsHash, timestamp, requestData);
return requestId;
}
}
function deliver(uint64 requestId, bytes32 paramsHash, uint64 error, bytes32 respData) public {
if (msg.sender != SGX_ADDRESS ||
requestId <= 0 ||
requests[requestId].requester == 0 ||
requests[requestId].fee == DELIVERED_FEE_FLAG) {
return;
}
uint fee = requests[requestId].fee;
if (requests[requestId].paramsHash != paramsHash) {
return;
} else if (fee == CANCELLED_FEE_FLAG) {
SGX_ADDRESS.send(CANCELLATION_FEE);
requests[requestId].fee = DELIVERED_FEE_FLAG;
unrespondedCnt--;
return;
}
requests[requestId].fee = DELIVERED_FEE_FLAG;
unrespondedCnt--;
if (error < 2) {
SGX_ADDRESS.send(fee);
} else {
externalCallFlag = true;
requests[requestId].requester.call.gas(2300).value(fee)();
externalCallFlag = false;
}
uint callbackGas = (fee - MIN_FEE) / tx.gasprice;
DeliverInfo(requestId, fee, tx.gasprice, msg.gas, callbackGas, paramsHash, error, respData);
if (callbackGas > msg.gas - 5000) {
callbackGas = msg.gas - 5000;
}
externalCallFlag = true;
requests[requestId].callbackAddr.call.gas(callbackGas)(requests[requestId].callbackFID, requestId, error, respData);
externalCallFlag = false;
}
function cancel(uint64 requestId) public returns (int) {
if (externalCallFlag) {
throw;
}
if (killswitch) {
return 0;
}
uint fee = requests[requestId].fee;
if (requests[requestId].requester == msg.sender && fee >= CANCELLATION_FEE) {
requests[requestId].fee = CANCELLED_FEE_FLAG;
externalCallFlag = true;
if (!msg.sender.call.value(fee - CANCELLATION_FEE)()) {
throw;
}
externalCallFlag = false;
Cancel(requestId, msg.sender, requests[requestId].requester, requests[requestId].fee, 1);
return SUCCESS_FLAG;
} else {
Cancel(requestId, msg.sender, requests[requestId].requester, fee, -1);
return FAIL_FLAG;
}
}
} | 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 = 0x4e4eE4eaB57b92C5DAdf00FBBd342d7C0e95aEa4;
}
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 = 29635200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x6CAA07840b106eaa052e3F5B2255d623E501697D;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.18;
contract Owned {
modifier onlyOwner { require(msg.sender == owner); _; }
address public owner;
function Owned() public { owner = msg.sender;}
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
}
contract TokenController {
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount) public returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract KayoToken is Owned {
string public name;
uint8 public decimals;
string public symbol;
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
KayoToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
uint public preSaleTokenBalances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
bool public IsPreSaleEnabled = false;
bool public IsSaleEnabled = false;
address public owner;
address public rewardManager;
uint public allowedRewardTokens;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
modifier canReleaseToken {
if (IsSaleEnabled == true || IsPreSaleEnabled == true)
_;
else
revert();
}
modifier onlyRewardManager {
require(msg.sender == rewardManager || owner == msg.sender); _;
}
function KayoToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
owner = _tokenFactory;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = KayoToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
transferFrom(msg.sender, _to, _amount);
return true;
}
function freezeAccount(address target, bool freeze) onlyOwner public{
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPreSale (bool _value) onlyOwner public {
IsPreSaleEnabled = _value;
}
function setSale (bool _value) onlyOwner public {
IsSaleEnabled = _value;
}
function setRewardManger (address _address) onlyOwner public{
rewardManager = _address;
}
function setRewardManagerLimit(uint _amount) onlyOwner public returns (bool success){
allowedRewardTokens = _amount;
approve(rewardManager, _amount);
return true;
}
function invest(address _to, uint256 _amount) canReleaseToken onlyRewardManager public returns (bool success) {
require((_to != 0) && (_to != address(this)));
bool IsTransferAllowed = false;
if(IsPreSaleEnabled){
require(preSaleTokenBalances >= _amount);
IsTransferAllowed = true;
preSaleTokenBalances = preSaleTokenBalances - _amount;
return true;
}
else if(IsSaleEnabled){
IsTransferAllowed = true;
}
else{
revert();
}
require(IsTransferAllowed);
var previousBalanceFrom = balanceOfAt(msg.sender, block.number);
require(previousBalanceFrom >= _amount);
updateValueAtNow(balances[msg.sender], previousBalanceFrom - _amount);
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
if(msg.sender == rewardManager){
transferFrom(owner, _to, _amount);
}
else{
transferFrom(msg.sender, _to, _amount);
}
}
function transferFrom(address _from, address _to, uint _amount) public returns (bool success) {
require(IsSaleEnabled && !IsPreSaleEnabled);
if (_amount == 0) {
Transfer(_from, _to, _amount);
return;
}
if (msg.sender != owner) {
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
Transfer(_from, _to, _amount);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 tokenBalance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isValidAddress(owner)) {
require(TokenController(owner).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(msg.sender,_amount,this,_extraData);
return true;
}
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function generateTokens(address _owner, uint _amount) public onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
uint256 _bal = _amount * 30;
preSaleTokenBalances = preSaleTokenBalances + _bal / 100;
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount) onlyOwner public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function destroyAllTokens(address _owner) onlyOwner public returns (bool) {
updateValueAtNow(totalSupplyHistory, 0);
updateValueAtNow(balances[_owner], 0);
Transfer(_owner, 0, 0);
return true;
}
function enableTransfers(bool _transfersEnabled) public onlyOwner {
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 minValue = 0;
uint maximum = checkpoints.length-1;
while (maximum > minValue) {
uint midddle = (maximum + minValue + 1)/ 2;
if (checkpoints[midddle].fromBlock<=_block) {
minValue = midddle;
} else {
maximum = midddle-1;
}
}
return checkpoints[minValue].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
function isValidAddress(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
} | 0 |
pragma solidity ^0.4.18;
contract ERC223Receiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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 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 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);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ERC223Token is StandardToken, Claimable {
using SafeMath for uint256;
bool public erc223Activated;
mapping (address => bool) public whiteListContracts;
mapping (address => mapping (address => bool) ) public userWhiteListContracts;
function setERC223Activated(bool _activate) public onlyOwner {
erc223Activated = _activate;
}
function setWhiteListContract(address _addr, bool f) public onlyOwner {
whiteListContracts[_addr] = f;
}
function setUserWhiteListContract(address _addr, bool f) public {
userWhiteListContracts[msg.sender][_addr] = f;
}
function checkAndInvokeReceiver(address _to, uint256 _value, bytes _data) internal {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if (codeLength>0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
}
function transfer(address _to, uint256 _value) public returns (bool) {
bool ok = super.transfer(_to, _value);
if (erc223Activated
&& whiteListContracts[_to] ==false
&& userWhiteListContracts[msg.sender][_to] ==false) {
bytes memory empty;
checkAndInvokeReceiver(_to, _value, empty);
}
return ok;
}
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
bool ok = super.transfer(_to, _value);
if (erc223Activated
&& whiteListContracts[_to] ==false
&& userWhiteListContracts[msg.sender][_to] ==false) {
checkAndInvokeReceiver(_to, _value, _data);
}
return ok;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
bool ok = super.transferFrom(_from, _to, _value);
if (erc223Activated
&& whiteListContracts[_to] ==false
&& userWhiteListContracts[_from][_to] ==false
&& userWhiteListContracts[msg.sender][_to] ==false) {
bytes memory empty;
checkAndInvokeReceiver(_to, _value, empty);
}
return ok;
}
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) {
bool ok = super.transferFrom(_from, _to, _value);
if (erc223Activated
&& whiteListContracts[_to] ==false
&& userWhiteListContracts[_from][_to] ==false
&& userWhiteListContracts[msg.sender][_to] ==false) {
checkAndInvokeReceiver(_to, _value, _data);
}
return ok;
}
}
contract BurnableToken is ERC223Token {
using SafeMath for uint256;
event Burn(address indexed burner, uint256 value);
function burnTokenBurn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
contract HoldersToken is BurnableToken {
using SafeMath for uint256;
mapping (address => bool) public isHolder;
address [] public holders;
function addHolder(address _addr) internal returns (bool) {
if (isHolder[_addr] != true) {
holders[holders.length++] = _addr;
isHolder[_addr] = true;
return true;
}
return false;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
bool ok = super.transfer(_to, _value);
addHolder(_to);
return ok;
}
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
bool ok = super.transfer(_to, _value, _data);
addHolder(_to);
return ok;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(this));
bool ok = super.transferFrom(_from, _to, _value);
addHolder(_to);
return ok;
}
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
bool ok = super.transferFrom(_from, _to, _value, _data);
addHolder(_to);
return ok;
}
}
contract MigrationAgent {
function migrateFrom(address from, uint256 value) public returns (bool);
}
contract MigratoryToken is HoldersToken {
using SafeMath for uint256;
address public migrationAgent;
uint256 public migrationCountComplete;
function setMigrationAgent(address agent) public onlyOwner {
migrationAgent = agent;
}
function migrate() public returns (bool) {
require(migrationAgent != 0x0);
uint256 value = balances[msg.sender];
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply_ = totalSupply_.sub(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrate(msg.sender, value);
return true;
}
function migrateHolders(uint256 count) public onlyOwner returns (bool) {
require(count > 0);
require(migrationAgent != 0x0);
count = migrationCountComplete.add(count);
if (count > holders.length) {
count = holders.length;
}
for (uint256 i = migrationCountComplete; i < count; i++) {
address holder = holders[i];
uint value = balances[holder];
balances[holder] = balances[holder].sub(value);
totalSupply_ = totalSupply_.sub(value);
MigrationAgent(migrationAgent).migrateFrom(holder, value);
Migrate(holder, value);
}
migrationCountComplete = count;
return true;
}
event Migrate(address indexed owner, uint256 value);
}
contract ChainPay is MigratoryToken {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
function ChainPay() public {
name = "ChainPay";
symbol = "CIP";
decimals = 18;
totalSupply_ = 6060660000000000000000000;
balances[owner] = totalSupply_;
holders[holders.length++] = owner;
isHolder[owner] = true;
}
address public migrationGate;
function setMigrationGate(address _addr) public onlyOwner {
migrationGate = _addr;
}
modifier onlyMigrationGate() {
require(msg.sender == migrationGate);
_;
}
function transferMulti(address [] _tos, uint256 [] _values) public onlyMigrationGate returns (string) {
require(_tos.length == _values.length);
bytes memory return_values = new bytes(_tos.length);
for (uint256 i = 0; i < _tos.length; i++) {
address _to = _tos[i];
uint256 _value = _values[i];
return_values[i] = byte(48);
if (_to != address(0) &&
_value <= balances[msg.sender]) {
bool ok = transfer(_to, _value);
if (ok) {
return_values[i] = byte(49);
}
}
}
return string(return_values);
}
function() public payable {
revert();
}
} | 0 |
pragma solidity ^0.4.21;
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 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;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract HasNoEther is Ownable {
function HasNoEther() public payable {
require(msg.value == 0);
}
function() external {
}
function reclaimEther() external onlyOwner {
assert(owner.send(address(this).balance));
}
}
contract EOSContractInterface
{
mapping (address => string) public keys;
function balanceOf( address who ) constant returns (uint value);
}
contract EOSclassic is StandardToken, HasNoEther
{
string public constant name = "EOSclassic";
string public constant symbol = "EOSC";
uint8 public constant decimals = 18;
uint public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint(decimals));
uint public constant foundersAllocation = 100000000 * (10 ** uint(decimals));
address public constant eosTokenAddress = 0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0;
address public constant eosCrowdsaleAddress = 0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf;
mapping (address => string) public keys;
mapping (address => bool) public eosClassicClaimed;
event LogClaim (address user, uint amount);
event LogRegister (address user, string key);
constructor() public
{
totalSupply_ = TOTAL_SUPPLY;
balances[address(this)] = TOTAL_SUPPLY;
emit Transfer(0x0, address(this), TOTAL_SUPPLY);
balances[address(this)] = balances[address(this)].sub(foundersAllocation);
balances[msg.sender] = balances[msg.sender].add(foundersAllocation);
emit Transfer(address(this), msg.sender, foundersAllocation);
}
function queryEOSTokenBalance(address _address) view public returns (uint)
{
EOSContractInterface eosTokenContract = EOSContractInterface(eosTokenAddress);
return eosTokenContract.balanceOf(_address);
}
function queryEOSCrowdsaleKey(address _address) view public returns (string)
{
EOSContractInterface eosCrowdsaleContract = EOSContractInterface(eosCrowdsaleAddress);
return eosCrowdsaleContract.keys(_address);
}
function claimEOSclassic() external returns (bool)
{
return claimEOSclassicFor(msg.sender);
}
function claimEOSclassicFor(address _toAddress) public returns (bool)
{
require (_toAddress != address(0));
require (_toAddress != 0x00000000000000000000000000000000000000B1);
require (isClaimed(_toAddress) == false);
uint _eosContractBalance = queryEOSTokenBalance(_toAddress);
require (_eosContractBalance > 0);
require (_eosContractBalance <= balances[address(this)]);
eosClassicClaimed[_toAddress] = true;
balances[address(this)] = balances[address(this)].sub(_eosContractBalance);
balances[_toAddress] = balances[_toAddress].add(_eosContractBalance);
emit Transfer(address(this), _toAddress, _eosContractBalance);
emit LogClaim(_toAddress, _eosContractBalance);
return true;
}
function isClaimed(address _address) public view returns (bool)
{
return eosClassicClaimed[_address];
}
function getMyEOSKey() external view returns (string)
{
return getEOSKeyFor(msg.sender);
}
function getEOSKeyFor(address _address) public view returns (string)
{
string memory _eosKey;
_eosKey = keys[_address];
if (bytes(_eosKey).length > 0) {
return _eosKey;
} else {
_eosKey = queryEOSCrowdsaleKey(_address);
return _eosKey;
}
}
function register(string key) public {
assert(bytes(key).length <= 64);
keys[msg.sender] = key;
emit LogRegister(msg.sender, key);
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xE441A7d3661435567Be6Af238782a48778747751;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity 0.4.25;
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 ExtendedMath {
function limitLessThan(uint a, uint b) internal pure returns(uint c) {
if (a > b) return b;
return a;
}
}
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 InterfaceContracts is Ownable {
InterfaceContracts public _internalMod;
function setModifierContract (address _t) onlyOwner public {
_internalMod = InterfaceContracts(_t);
}
modifier onlyMiningContract() {
require(msg.sender == _internalMod._contract_miner(), "Wrong sender");
_;
}
modifier onlyTokenContract() {
require(msg.sender == _internalMod._contract_token(), "Wrong sender");
_;
}
modifier onlyMasternodeContract() {
require(msg.sender == _internalMod._contract_masternode(), "Wrong sender");
_;
}
modifier onlyVotingOrOwner() {
require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender");
_;
}
modifier onlyVotingContract() {
require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender");
_;
}
function _contract_voting () public view returns (address) {
return _internalMod._contract_voting();
}
function _contract_masternode () public view returns (address) {
return _internalMod._contract_masternode();
}
function _contract_token () public view returns (address) {
return _internalMod._contract_token();
}
function _contract_miner () public view returns (address) {
return _internalMod._contract_miner();
}
}
interface ICaelumMasternode {
function _externalArrangeFlow() external;
function rewardsProofOfWork() external returns (uint) ;
function rewardsMasternode() external returns (uint) ;
function masternodeIDcounter() external returns (uint) ;
function masternodeCandidate() external returns (uint) ;
function getUserFromID(uint) external view returns (address) ;
function contractProgress() external view returns (uint, uint, uint, uint, uint, uint, uint, uint);
}
interface ICaelumToken {
function rewardExternal(address, uint) external;
}
interface EIP918Interface {
function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success);
function getChallengeNumber() external view returns (bytes32);
function getMiningDifficulty() external view returns (uint);
function getMiningTarget() external view returns (uint);
function getMiningReward() external view returns (uint);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
contract AbstractERC918 is EIP918Interface {
bytes32 public challengeNumber;
uint public difficulty;
uint public tokensMinted;
struct Statistics {
address lastRewardTo;
uint lastRewardAmount;
uint lastRewardEthBlockNumber;
uint lastRewardTimestamp;
}
Statistics public statistics;
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest);
function _reward() internal returns (uint);
function _newEpoch(uint256 nonce) internal returns (uint);
function _adjustDifficulty() internal returns (uint);
}
contract CaelumAbstractMiner is InterfaceContracts, AbstractERC918 {
using SafeMath for uint;
using ExtendedMath for uint;
uint256 public totalSupply = 2100000000000000;
uint public latestDifficultyPeriodStarted;
uint public epochCount;
uint public baseMiningReward = 50;
uint public blocksPerReadjustment = 512;
uint public _MINIMUM_TARGET = 2 ** 16;
uint public _MAXIMUM_TARGET = 2 ** 234;
uint public rewardEra = 0;
uint public maxSupplyForEra;
uint public MAX_REWARD_ERA = 39;
uint public MINING_RATE_FACTOR = 60;
uint public MAX_ADJUSTMENT_PERCENT = 100;
uint public TARGET_DIVISOR = 2000;
uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2);
mapping(bytes32 => bytes32) solutionForChallenge;
mapping(address => mapping(address => uint)) allowed;
bytes32 public challengeNumber;
uint public difficulty;
uint public tokensMinted;
Statistics public statistics;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
event RewardMasternode(address candidate, uint amount);
constructor() public {
tokensMinted = 0;
maxSupplyForEra = totalSupply.div(2);
difficulty = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_newEpoch(0);
}
function _newEpoch(uint256 nonce) internal returns(uint) {
if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) {
rewardEra = rewardEra + 1;
}
maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1));
epochCount = epochCount.add(1);
challengeNumber = blockhash(block.number - 1);
return (epochCount);
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success);
function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) {
digest = keccak256(challengeNumber, msg.sender, nonce);
if (digest != challenge_digest) revert();
if (uint256(digest) > difficulty) revert();
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if (solution != 0x0) revert();
}
function _reward() internal returns(uint);
function _reward_masternode() internal returns(uint);
function _adjustDifficulty() internal returns(uint) {
if (epochCount % blocksPerReadjustment != 0) {
return difficulty;
}
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint epochsMined = blocksPerReadjustment;
uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR;
if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) {
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod);
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra));
} else {
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod);
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT);
difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra));
}
latestDifficultyPeriodStarted = block.number;
if (difficulty < _MINIMUM_TARGET)
{
difficulty = _MINIMUM_TARGET;
}
if (difficulty > _MAXIMUM_TARGET)
{
difficulty = _MAXIMUM_TARGET;
}
}
function getChallengeNumber() public view returns(bytes32) {
return challengeNumber;
}
function getMiningDifficulty() public view returns(uint) {
return _MAXIMUM_TARGET.div(difficulty);
}
function getMiningTarget() public view returns(uint) {
return difficulty;
}
function getMiningReward() public view returns(uint) {
return (baseMiningReward * 1e8).div(2 ** rewardEra);
}
function getMintDigest(
uint256 nonce,
bytes32 challenge_digest,
bytes32 challenge_number
)
public view returns(bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
return digest;
}
function checkMintSolution(
uint256 nonce,
bytes32 challenge_digest,
bytes32 challenge_number,
uint testTarget
)
public view returns(bool success) {
bytes32 digest = keccak256(challenge_number, msg.sender, nonce);
if (uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
}
contract CaelumMiner is CaelumAbstractMiner {
ICaelumToken public tokenInterface;
ICaelumMasternode public masternodeInterface;
bool public ACTIVE_STATE = false;
uint swapStartedBlock = now;
uint public gasPriceLimit = 999;
modifier checkGasPrice(uint txnGasPrice) {
require(txnGasPrice <= gasPriceLimit * 1000000000, "Gas above gwei limit!");
_;
}
event GasPriceSet(uint8 _gasPrice);
function setGasPriceLimit(uint8 _gasPrice) onlyOwner public {
require(_gasPrice > 0);
gasPriceLimit = _gasPrice;
emit GasPriceSet(_gasPrice);
}
function setTokenContract() internal {
tokenInterface = ICaelumToken(_contract_token());
}
function setMasternodeContract() internal {
masternodeInterface = ICaelumMasternode(_contract_masternode());
}
function setModifierContract (address _contract) onlyOwner public {
require (now <= swapStartedBlock + 10 days);
_internalMod = InterfaceContracts(_contract);
setMasternodeContract();
setTokenContract();
}
function VoteModifierContract (address _contract) onlyVotingContract external {
_internalMod = InterfaceContracts(_contract);
setMasternodeContract();
setTokenContract();
}
function mint(uint256 nonce, bytes32 challenge_digest) checkGasPrice(tx.gasprice) public returns(bool success) {
require(ACTIVE_STATE);
_hash(nonce, challenge_digest);
masternodeInterface._externalArrangeFlow();
uint rewardAmount = _reward();
uint rewardMasternode = _reward_masternode();
tokensMinted += rewardAmount.add(rewardMasternode);
uint epochCounter = _newEpoch(nonce);
_adjustDifficulty();
statistics = Statistics(msg.sender, rewardAmount, block.number, now);
emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber);
return true;
}
function _reward() internal returns(uint) {
uint _pow = masternodeInterface.rewardsProofOfWork();
tokenInterface.rewardExternal(msg.sender, 1 * 1e8);
return _pow;
}
function _reward_masternode() internal returns(uint) {
uint _mnReward = masternodeInterface.rewardsMasternode();
if (masternodeInterface.masternodeIDcounter() == 0) return 0;
address _mnCandidate = masternodeInterface.getUserFromID(masternodeInterface.masternodeCandidate());
if (_mnCandidate == 0x0) return 0;
tokenInterface.rewardExternal(_mnCandidate, _mnReward);
emit RewardMasternode(_mnCandidate, _mnReward);
return _mnReward;
}
function getMiningRewardForPool() public view returns(uint) {
return masternodeInterface.rewardsProofOfWork();
}
function getMiningReward() public view returns(uint) {
return (baseMiningReward * 1e8).div(2 ** rewardEra);
}
function contractProgress() public view returns
(
uint epoch,
uint candidate,
uint round,
uint miningepoch,
uint globalreward,
uint powreward,
uint masternodereward,
uint usercounter
) {
return ICaelumMasternode(_contract_masternode()).contractProgress();
}
function getDataFromContract(address _previous_contract) onlyOwner public {
require(ACTIVE_STATE == false);
require(_contract_token() != 0);
require(_contract_masternode() != 0);
CaelumAbstractMiner prev = CaelumAbstractMiner(_previous_contract);
difficulty = prev.difficulty();
rewardEra = prev.rewardEra();
MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR();
maxSupplyForEra = prev.maxSupplyForEra();
tokensMinted = prev.tokensMinted();
epochCount = prev.epochCount();
ACTIVE_STATE = true;
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract HashnodeTestCoin is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function HashnodeTestCoin() {
balances[msg.sender] = 226000000;
totalSupply = 226000000;
name = "AppIndia";
decimals = 18;
symbol = "BTRS";
unitsOneEthCanBuy = 10;
fundsWallet = msg.sender;
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.1;
contract BurnableOpenPayment {
address public payer;
address public recipient;
address public burnAddress = 0xdead;
string public payerString;
string public recipientString;
uint public commitThreshold;
modifier onlyPayer() {
if (msg.sender != payer) throw;
_;
}
modifier onlyRecipient() {
if (msg.sender != recipient) throw;
_;
}
modifier onlyWithRecipient() {
if (recipient == address(0x0)) throw;
_;
}
modifier onlyWithoutRecipient() {
if (recipient != address(0x0)) throw;
_;
}
function () payable {}
function BurnableOpenPayment(address _payer, uint _commitThreshold)
public
payable {
payer = _payer;
commitThreshold = _commitThreshold;
}
function getPayer()
public returns (address) { return payer; }
function getRecipient()
public returns (address) { return recipient; }
function getCommitThreshold()
public returns (uint) { return commitThreshold; }
function getPayerString()
public returns (string) { return payerString; }
function getRecipientString()
public returns (string) { return recipientString; }
function commit()
public
onlyWithoutRecipient()
payable
{
if (msg.value < commitThreshold) throw;
recipient = msg.sender;
}
function burn(uint amount)
public
onlyPayer()
onlyWithRecipient()
returns (bool)
{
return burnAddress.send(amount);
}
function release(uint amount)
public
onlyPayer()
onlyWithRecipient()
returns (bool)
{
return recipient.send(amount);
}
function setPayerString(string _string)
public
onlyPayer()
{
payerString = _string;
}
function setRecipientString(string _string)
public
onlyRecipient()
{
recipientString = _string;
}
} | 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;
}
}
interface IDividendToken{
function profitOrgPay() payable external ;
}
interface IGame {
function setBanker(address _banker, uint256 _beginTime, uint256 _endTime) external returns(bool _result);
function canSetBanker() view external returns (bool);
function bankerEndTime() constant external returns (uint);
}
contract Base {
using SafeMath for uint256;
uint public createTime = now;
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function setOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
bool public globalLocked = false;
function lock() internal {
require(!globalLocked);
globalLocked = true;
}
function unLock() internal {
require(globalLocked);
globalLocked = false;
}
function setLock() public onlyOwner {
globalLocked = false;
}
mapping (address => uint256) public userEtherOf;
function userRefund() public returns(bool _result) {
return _userRefund(msg.sender);
}
function _userRefund(address _to) internal returns(bool _result) {
require (_to != 0x0);
lock();
uint256 amount = userEtherOf[msg.sender];
if(amount > 0) {
userEtherOf[msg.sender] = 0;
_to.transfer(amount);
_result = true;
}
else {
_result = false;
}
unLock();
}
uint public currentEventId = 1;
function getEventId() internal returns(uint _result) {
_result = currentEventId;
currentEventId ++;
}
}
contract Beneficial is Base {
address public shareholder;
bool public shareholderIsToken = false;
string public officialUrl;
function setOfficialUrl(string _newOfficialUrl) public onlyOwner{
officialUrl = _newOfficialUrl;
}
function _userRefund(address _to) internal returns(bool _result){
require (_to != 0x0);
lock();
uint256 amount = userEtherOf[msg.sender];
if(amount > 0){
userEtherOf[msg.sender] = 0;
if(shareholderIsToken && msg.sender == shareholder){
IDividendToken token = IDividendToken(shareholder);
token.profitOrgPay.value(amount)();
}
else{
_to.transfer(amount);
}
_result = true;
}
else{
_result = false;
}
unLock();
}
}
contract Auction is Beneficial {
function Auction(address _gameToken) public {
owner = msg.sender;
shareholder = _gameToken;
shareholderIsToken = true;
}
int public gameIndex = 1;
mapping(int => address) public indexGameOf;
function _addIndexGame(address _gameAddr) private {
indexGameOf[gameIndex] = _gameAddr;
gameIndex ++;
}
mapping(address => bool) public whiteListOf;
event OnWhiteListChange(address indexed _Addr, address _operator, bool _result, uint _eventTime, uint _eventId);
function addWhiteList(address _Addr) public onlyOwner {
require (_Addr != 0x0);
whiteListOf[_Addr] = true;
_addIndexGame(_Addr);
emit OnWhiteListChange(_Addr, msg.sender, true, now, getEventId());
}
function delWhiteList(address _Addr) public onlyOwner {
require (_Addr != 0x0);
whiteListOf[_Addr] = false;
emit OnWhiteListChange(_Addr, msg.sender, false, now, getEventId()) ;
}
function isWhiteListGame(address _Addr) private view returns(bool _result) {
_result = whiteListOf[_Addr];
}
uint auctionId = 1;
struct AuctionObj {
uint id;
address objAddr;
uint256 beginTime;
uint256 endTime;
uint256 price;
address winnerAddr;
uint bankerTime;
bool emptyGameBanker;
}
mapping (address => AuctionObj) public auctionObjOf;
event OnSetAuctionObj(uint indexed _auctionId, address indexed _objAddr, uint256 _beginTime, uint256 _endTime, uint _bankerTime, bool _result, uint _code, uint _eventTime, uint _eventId);
function setAuctionObj(address _gameAddr, uint256 _auctionEndTime, uint _bankerTime)
public onlyOwner returns (bool _result)
{
_result = _setAuctionObj(_gameAddr, _auctionEndTime, _bankerTime);
}
function addWhiteListAddSetAuctionObj(address _gameAddr, uint256 _auctionEndTime, uint _bankerTime)
public onlyOwner returns (bool _result)
{
addWhiteList(_gameAddr);
_result = _setAuctionObj(_gameAddr, _auctionEndTime, _bankerTime);
}
function _setAuctionObj(address _gameAddr, uint256 _auctionEndTime, uint _bankerTime) private returns (bool _result) {
_result = false;
require(_gameAddr != 0x0);
require(now < _auctionEndTime);
if(!isWhiteListGame(_gameAddr)) {
emit OnSetAuctionObj(auctionId, _gameAddr, now, _auctionEndTime, _bankerTime, false, 1, now, getEventId()) ;
return;
}
AuctionObj storage ao = auctionObjOf[_gameAddr];
if(ao.endTime <= now && !ao.emptyGameBanker) {
AuctionObj memory newAO = AuctionObj({
id: auctionId,
objAddr: _gameAddr,
beginTime: now,
endTime : _auctionEndTime,
winnerAddr: owner,
price: 0,
bankerTime: _bankerTime,
emptyGameBanker: true
});
emit OnSetAuctionObj(auctionId, _gameAddr, now, _auctionEndTime, _bankerTime, true, 0, now, getEventId()) ;
auctionObjOf[_gameAddr] = newAO;
auctionId ++;
_result = true;
return;
}else{
emit OnSetAuctionObj(auctionId, _gameAddr, now, _auctionEndTime, _bankerTime, false, 2, now, getEventId()) ;
}
}
event OnBid(uint indexed _auctionId, address _sender, address _objAddr, uint256 _price, bool _result, uint _code, uint _eventTime, uint _eventId);
function bid(address _objAddr, uint256 _price) public payable returns(bool _result) {
_result = false;
require(_objAddr != 0x0);
AuctionObj storage ao = auctionObjOf[_objAddr];
if(msg.value > 0){
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
if(10**16 > _price){
emit OnBid(ao.id, msg.sender, _objAddr, _price, false, 3, now, getEventId());
return;
}
if(userEtherOf[msg.sender] < _price){
emit OnBid(ao.id, msg.sender, _objAddr, _price, false, 1, now, getEventId());
return;
}
if(now < ao.endTime) {
if(_price > ao.price) {
userEtherOf[msg.sender] = userEtherOf[msg.sender].sub(_price);
userEtherOf[ao.winnerAddr] = userEtherOf[ao.winnerAddr].add(ao.price);
ao.price = _price;
ao.winnerAddr = msg.sender;
emit OnBid(ao.id, msg.sender, _objAddr, _price, true, 0, now, getEventId());
_result = true;
return;
}
}
emit OnBid(ao.id, msg.sender, _objAddr, _price, false, 2, now, getEventId());
return;
}
event OnSetGameBanker(uint indexed _auctionId, address indexed _gameAddr, bool indexed _result, uint _code, uint _eventTime, uint _eventId);
function setGameBanker(address _gameAddr) public returns (bool _result) {
_result = false;
require(_gameAddr != 0x0);
lock();
AuctionObj storage ao = auctionObjOf[_gameAddr];
if(ao.id > 0 && ao.endTime <= now) {
IGame g = IGame(_gameAddr);
if(g.bankerEndTime() < now && g.canSetBanker()){
_result = g.setBanker(ao.winnerAddr, now, now.add(ao.bankerTime));
if(_result){
emit OnSetGameBanker(ao.id, _gameAddr, _result, 0, now, getEventId());
ao.emptyGameBanker = false;
userEtherOf[shareholder] = userEtherOf[shareholder].add(ao.price);
_setAuctionObj(_gameAddr, (now.add(ao.bankerTime)).sub(1 hours) , ao.bankerTime);
}else{
emit OnSetGameBanker(ao.id, _gameAddr, false, 1, now, getEventId());
}
}else{
emit OnSetGameBanker(ao.id, _gameAddr, false, 2, now, getEventId());
}
}else{
emit OnSetGameBanker(ao.id, _gameAddr, false, 3, now, getEventId());
}
unLock();
}
function () public payable {
if(msg.value > 0) {
userEtherOf[msg.sender] = userEtherOf[msg.sender].add(msg.value);
}
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
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,
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
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 Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
function withdraw(address _payee) public onlyOwner {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
}
}
contract ConditionalEscrow is Escrow {
function withdrawalAllowed(address _payee) public view returns (bool);
function withdraw(address _payee) public {
require(withdrawalAllowed(_payee));
super.withdraw(_payee);
}
}
contract RefundEscrow is Ownable, ConditionalEscrow {
enum State { Active, Refunding, Closed }
event Closed();
event RefundsEnabled();
State public state;
address public beneficiary;
constructor(address _beneficiary) public {
require(_beneficiary != address(0));
beneficiary = _beneficiary;
state = State.Active;
}
function deposit(address _refundee) public payable {
require(state == State.Active);
super.deposit(_refundee);
}
function close() public onlyOwner {
require(state == State.Active);
state = State.Closed;
emit Closed();
}
function enableRefunds() public onlyOwner {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function beneficiaryWithdraw() public {
require(state == State.Closed);
beneficiary.transfer(address(this).balance);
}
function withdrawalAllowed(address _payee) public view returns (bool) {
return state == State.Refunding;
}
}
contract ClinicAllRefundEscrow is RefundEscrow {
using Math for uint256;
struct RefundeeRecord {
bool isRefunded;
uint256 index;
}
mapping(address => RefundeeRecord) public refundees;
address[] internal refundeesList;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
mapping(address => uint256) private beneficiaryDeposits;
uint256 public beneficiaryDepositedAmount;
uint256 public investorsDepositedToCrowdSaleAmount;
constructor(address _beneficiary)
RefundEscrow(_beneficiary)
public {
}
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
function beneficiaryDepositsOf(address _payee) public view returns (uint256) {
return beneficiaryDeposits[_payee];
}
function deposit(address _refundee) public payable {
uint256 amount = msg.value;
beneficiaryDeposits[_refundee] = beneficiaryDeposits[_refundee].add(amount);
beneficiaryDepositedAmount = beneficiaryDepositedAmount.add(amount);
}
function depositFunds(address _refundee, uint256 _value) public onlyOwner {
require(state == State.Active, "Funds deposition is possible only in the Active state.");
uint256 amount = _value;
deposits[_refundee] = deposits[_refundee].add(amount);
investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.add(amount);
emit Deposited(_refundee, amount);
RefundeeRecord storage _data = refundees[_refundee];
_data.isRefunded = false;
if (_data.index == uint256(0)) {
refundeesList.push(_refundee);
_data.index = refundeesList.length.sub(1);
}
}
function close() public onlyOwner {
super.close();
}
function withdraw(address _payee) public onlyOwner {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal.");
RefundeeRecord storage _data = refundees[_payee];
require(_data.isRefunded == false, "An investor should not be refunded.");
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
investorsDepositedToCrowdSaleAmount = investorsDepositedToCrowdSaleAmount.sub(payment);
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
_data.isRefunded = true;
removeRefundeeByIndex(_data.index);
}
function manualRefund(address _payee) public onlyOwner {
require(depositsOf(_payee) > 0, "An investor should have non-negative deposit for withdrawal.");
RefundeeRecord storage _data = refundees[_payee];
require(_data.isRefunded == false, "An investor should not be refunded.");
deposits[_payee] = 0;
_data.isRefunded = true;
removeRefundeeByIndex(_data.index);
}
function removeRefundeeByIndex(uint256 _indexToDelete) private {
if ((refundeesList.length > 0) && (_indexToDelete < refundeesList.length)) {
uint256 _lastIndex = refundeesList.length.sub(1);
refundeesList[_indexToDelete] = refundeesList[_lastIndex];
refundeesList.length--;
}
}
function refundeesListLength() public onlyOwner view returns (uint256) {
return refundeesList.length;
}
function withdrawChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner returns (uint256, address[]) {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
uint256 _refundeesCount = refundeesList.length;
require(_chunkLength >= _refundeesCount);
require(_txFee > 0, "Transaction fee should be above zero.");
require(_refundeesCount > 0, "List of investors should not be empty.");
uint256 _weiRefunded = 0;
require(address(this).balance > (_chunkLength.mul(_txFee)), "Account's ballance should allow to pay all tx fees.");
address[] memory _refundeesListCopy = new address[](_chunkLength);
uint256 i;
for (i = 0; i < _chunkLength; i++) {
address _refundee = refundeesList[i];
RefundeeRecord storage _data = refundees[_refundee];
if (_data.isRefunded == false) {
if (depositsOf(_refundee) > _txFee) {
uint256 _deposit = depositsOf(_refundee);
if (_deposit > _txFee) {
_weiRefunded = _weiRefunded.add(_deposit);
uint256 _paymentWithoutTxFee = _deposit.sub(_txFee);
_refundee.transfer(_paymentWithoutTxFee);
emit Withdrawn(_refundee, _paymentWithoutTxFee);
_data.isRefunded = true;
_refundeesListCopy[i] = _refundee;
}
}
}
}
for (i = 0; i < _chunkLength; i++) {
if (address(0) != _refundeesListCopy[i]) {
RefundeeRecord storage _dataCleanup = refundees[_refundeesListCopy[i]];
require(_dataCleanup.isRefunded == true, "Investors in this list should be refunded.");
removeRefundeeByIndex(_dataCleanup.index);
}
}
return (_weiRefunded, _refundeesListCopy);
}
function withdrawEverything(uint256 _txFee) public onlyOwner returns (uint256, address[]) {
require(state == State.Refunding, "Funds withdrawal is possible only in the Refunding state.");
return withdrawChunk(_txFee, refundeesList.length);
}
function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner {
require(_value <= address(this).balance, "Withdraw part can not be more than current balance");
beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value);
beneficiary.transfer(_value);
}
function beneficiaryWithdrawAll() public onlyOwner {
uint256 _value = address(this).balance;
beneficiaryDepositedAmount = beneficiaryDepositedAmount.sub(_value);
beneficiary.transfer(_value);
}
}
contract TokenDestructible is Ownable {
constructor() public payable { }
function destroy(address[] tokens) onlyOwner public {
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Basic token = ERC20Basic(tokens[i]);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
selfdestruct(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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
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 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 TransferableToken is Ownable {
event TransferOn();
event TransferOff();
bool public transferable = false;
modifier whenNotTransferable() {
require(!transferable);
_;
}
modifier whenTransferable() {
require(transferable);
_;
}
function transferOn() onlyOwner whenNotTransferable public {
transferable = true;
emit TransferOn();
}
function transferOff() onlyOwner whenTransferable public {
transferable = false;
emit TransferOff();
}
}
contract ClinicAllToken is MintableToken, DetailedERC20, CappedToken, PausableToken, BurnableToken, TokenDestructible, TransferableToken {
constructor
(
string _name,
string _symbol,
uint8 _decimals,
uint256 _cap
)
DetailedERC20(_name, _symbol, _decimals)
CappedToken(_cap)
public
{
}
function burnAfterRefund(address _who) public onlyOwner {
uint256 _value = balances[_who];
_burn(_who, _value);
}
function transfer(
address _to,
uint256 _value
)
public
whenTransferable
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenTransferable
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function transferToPrivateInvestor(
address _from,
address _to,
uint256 _value
)
public
onlyOwner
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function burnPrivateSale(address privateSaleWallet, uint256 _value) public onlyOwner {
_burn(privateSaleWallet, _value);
}
}
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 indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract Managed is Ownable, RBAC {
string public constant ROLE_MANAGER = "manager";
modifier onlyManager() {
checkRole(msg.sender, ROLE_MANAGER);
_;
}
function setManager(address _operator) public onlyOwner {
addRole(_operator, ROLE_MANAGER);
}
function removeManager(address _operator) public onlyOwner {
removeRole(_operator, ROLE_MANAGER);
}
}
contract Limited is Managed {
using SafeMath for uint256;
mapping(address => uint256) public limitsList;
modifier isLimited(address _payee) {
require(limitsList[_payee] > 0, "An investor is limited if it has a limit.");
_;
}
modifier doesNotExceedLimit(address _payee, uint256 _tokenAmount, uint256 _tokenBalance, uint256 kycLimitEliminator) {
if(_tokenBalance.add(_tokenAmount) >= kycLimitEliminator) {
require(_tokenBalance.add(_tokenAmount) <= getLimit(_payee), "An investor should not exceed its limit on buying.");
}
_;
}
function getLimit(address _payee)
public view returns (uint256)
{
return limitsList[_payee];
}
function addAddressesLimits(address[] _payees, uint256[] _limits) public
onlyManager
{
require(_payees.length == _limits.length, "Array sizes should be equal.");
for (uint256 i = 0; i < _payees.length; i++) {
addLimit(_payees[i], _limits[i]);
}
}
function addLimit(address _payee, uint256 _limit) public
onlyManager
{
limitsList[_payee] = _limit;
}
function removeLimit(address _payee) external
onlyManager
{
limitsList[_payee] = 0;
}
}
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
function addAddressToWhitelist(address _operator)
onlyOwner
public
{
addRole(_operator, ROLE_WHITELISTED);
}
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
function removeAddressFromWhitelist(address _operator)
onlyOwner
public
{
removeRole(_operator, ROLE_WHITELISTED);
}
function removeAddressesFromWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract ManagedWhitelist is Managed, Whitelist {
function addAddressToWhitelist(address _operator) public onlyManager {
addRole(_operator, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] _operators) public onlyManager {
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
function removeAddressFromWhitelist(address _operator) public onlyManager {
removeRole(_operator, ROLE_WHITELISTED);
}
function removeAddressesFromWhitelist(address[] _operators) public onlyManager {
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
contract ClinicAllCrowdsale is Crowdsale, FinalizableCrowdsale, MintedCrowdsale, ManagedWhitelist, Limited {
constructor
(
uint256 _tokenLimitSupply,
uint256 _rate,
address _wallet,
address _privateSaleWallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime,
uint256 _discountTokenAmount,
uint256 _discountTokenPercent,
uint256 _preSaleClosingTime,
uint256 _softCapLimit,
ClinicAllRefundEscrow _vault,
uint256 _buyLimitSupplyMin,
uint256 _buyLimitSupplyMax,
uint256 _kycLimitEliminator
)
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
public
{
privateSaleWallet = _privateSaleWallet;
tokenSupplyLimit = _tokenLimitSupply;
discountTokenAmount = _discountTokenAmount;
discountTokenPercent = _discountTokenPercent;
preSaleClosingTime = _preSaleClosingTime;
softCapLimit = _softCapLimit;
vault = _vault;
buyLimitSupplyMin = _buyLimitSupplyMin;
buyLimitSupplyMax = _buyLimitSupplyMax;
kycLimitEliminator = _kycLimitEliminator;
}
using SafeMath for uint256;
ClinicAllRefundEscrow public vault;
uint256 public tokenSupplyLimit;
uint256 public discountTokenAmount;
uint256 public discountTokenPercent;
uint256 public preSaleClosingTime;
uint256 public softCapLimit;
uint256 public buyLimitSupplyMin;
uint256 public buyLimitSupplyMax;
uint256 public kycLimitEliminator;
address public privateSaleWallet;
uint256 public privateSaleSupplyLimit;
function updateRate(uint256 _rate) public
onlyManager
{
require(_rate != 0, "Exchange rate should not be 0.");
rate = _rate;
}
function updateBuyLimitRange(uint256 _min, uint256 _max) public
onlyOwner
{
require(_min != 0, "Minimal buy limit should not be 0.");
require(_max != 0, "Maximal buy limit should not be 0.");
require(_max > _min, "Maximal buy limit should be greater than minimal buy limit.");
buyLimitSupplyMin = _min;
buyLimitSupplyMax = _max;
}
function updateKycLimitEliminator(uint256 _value) public
onlyOwner
{
require(_value != 0, "Kyc Eliminator should not be 0.");
kycLimitEliminator = _value;
}
function claimRefund() public {
require(isFinalized, "Claim refunds is only possible if the ICO is finalized.");
require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached.");
uint256 deposit = vault.depositsOf(msg.sender);
vault.withdraw(msg.sender);
weiRaised = weiRaised.sub(deposit);
ClinicAllToken(token).burnAfterRefund(msg.sender);
}
function claimRefundChunk(uint256 _txFee, uint256 _chunkLength) public onlyOwner {
require(isFinalized, "Claim refunds is only possible if the ICO is finalized.");
require(!goalReached(), "Claim refunds is only possible if the soft cap goal has not been reached.");
uint256 _weiRefunded;
address[] memory _refundeesList;
(_weiRefunded, _refundeesList) = vault.withdrawChunk(_txFee, _chunkLength);
weiRaised = weiRaised.sub(_weiRefunded);
for (uint256 i = 0; i < _refundeesList.length; i++) {
ClinicAllToken(token).burnAfterRefund(_refundeesList[i]);
}
}
function refundeesListLength() public onlyOwner view returns (uint256) {
return vault.refundeesListLength();
}
function hasClosed() public view returns (bool) {
return ((block.timestamp > closingTime) || tokenSupplyLimit <= token.totalSupply());
}
function goalReached() public view returns (bool) {
return token.totalSupply() >= softCapLimit;
}
function supplyRest() public view returns (uint256) {
return (tokenSupplyLimit.sub(token.totalSupply()));
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
doesNotExceedLimit(_beneficiary, _tokenAmount, token.balanceOf(_beneficiary), kycLimitEliminator)
{
super._processPurchase(_beneficiary, _tokenAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyIfWhitelisted(_beneficiary)
isLimited(_beneficiary)
{
super._preValidatePurchase(_beneficiary, _weiAmount);
uint256 tokens = _getTokenAmount(_weiAmount);
require(tokens.add(token.totalSupply()) <= tokenSupplyLimit, "Total amount fo sold tokens should not exceed the total supply limit.");
require(tokens >= buyLimitSupplyMin, "An investor can buy an amount of tokens only above the minimal limit.");
require(tokens.add(token.balanceOf(_beneficiary)) <= buyLimitSupplyMax, "An investor cannot buy tokens above the maximal limit.");
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
if (isDiscount()) {
return _getTokensWithDiscount(_weiAmount);
}
return _weiAmount.mul(rate);
}
function getTokenAmount(uint256 _weiAmount)
public view returns (uint256)
{
return _getTokenAmount(_weiAmount);
}
function _getTokensWithDiscount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 tokens = 0;
uint256 restOfDiscountTokens = discountTokenAmount.sub(token.totalSupply());
uint256 discountTokensMax = _getDiscountTokenAmount(_weiAmount);
if (restOfDiscountTokens < discountTokensMax) {
uint256 discountTokens = restOfDiscountTokens;
uint256 _rate = _getDiscountRate();
uint256 _discointWeiAmount = discountTokens.div(_rate);
uint256 _restOfWeiAmount = _weiAmount.sub(_discointWeiAmount);
uint256 normalTokens = _restOfWeiAmount.mul(rate);
tokens = discountTokens.add(normalTokens);
} else {
tokens = discountTokensMax;
}
return tokens;
}
function _getDiscountTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
require(_weiAmount != 0, "It should be possible to buy tokens only by providing non zero ETH.");
uint256 _rate = _getDiscountRate();
return _weiAmount.mul(_rate);
}
function _getDiscountRate()
internal view returns (uint256)
{
require(isDiscount(), "Getting discount rate should be possible only below the discount tokens limit.");
return rate.add(rate.mul(discountTokenPercent).div(100));
}
function getRate()
public view returns (uint256)
{
if (isDiscount()) {
return _getDiscountRate();
}
return rate;
}
function isDiscount()
public view returns (bool)
{
return (preSaleClosingTime >= block.timestamp);
}
function transferTokensToReserve(address _beneficiary) private
{
require(tokenSupplyLimit < CappedToken(token).cap(), "Token's supply limit should be less that token' cap limit.");
uint256 _tokenCap = CappedToken(token).cap();
uint256 tokens = _tokenCap.sub(tokenSupplyLimit);
_deliverTokens(_beneficiary, tokens);
}
function transferOn() public onlyOwner
{
ClinicAllToken(token).transferOn();
}
function transferOff() public onlyOwner
{
ClinicAllToken(token).transferOff();
}
function finalization() internal {
if (goalReached()) {
transferTokensToReserve(wallet);
vault.close();
} else {
vault.enableRefunds();
}
MintableToken(token).finishMinting();
super.finalization();
}
function _forwardFunds() internal {
super._forwardFunds();
vault.depositFunds(msg.sender, msg.value);
}
modifier onlyPrivateSaleWallet() {
require(privateSaleWallet == msg.sender, "Wallet should be the same as private sale wallet.");
_;
}
function transferToPrivateInvestor(
address _beneficiary,
uint256 _value
)
public
onlyPrivateSaleWallet
onlyIfWhitelisted(_beneficiary)
returns (bool)
{
ClinicAllToken(token).transferToPrivateInvestor(msg.sender, _beneficiary, _value);
}
function redeemPrivateSaleFunds()
public
onlyPrivateSaleWallet
{
uint256 _balance = ClinicAllToken(token).balanceOf(msg.sender);
privateSaleSupplyLimit = privateSaleSupplyLimit.sub(_balance);
ClinicAllToken(token).burnPrivateSale(msg.sender, _balance);
}
function allocatePrivateSaleFunds(uint256 privateSaleSupplyAmount) public onlyOwner
{
require(privateSaleSupplyLimit.add(privateSaleSupplyAmount) < tokenSupplyLimit, "Token's private sale supply limit should be less that token supply limit.");
privateSaleSupplyLimit = privateSaleSupplyLimit.add(privateSaleSupplyAmount);
_deliverTokens(privateSaleWallet, privateSaleSupplyAmount);
}
function beneficiaryWithdrawChunk(uint256 _value) public onlyOwner {
vault.beneficiaryWithdrawChunk(_value);
}
function beneficiaryWithdrawAll() public onlyOwner {
vault.beneficiaryWithdrawAll();
}
function manualRefund(address _payee) public onlyOwner {
uint256 deposit = vault.depositsOf(_payee);
vault.manualRefund(_payee);
weiRaised = weiRaised.sub(deposit);
ClinicAllToken(token).burnAfterRefund(_payee);
}
} | 0 |
pragma solidity ^0.4.24;
interface token {
function transfer(address receiver, uint amount);
function burn(uint256 _value) returns (bool);
function balanceOf(address _address) returns (uint256);
}
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;
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns(uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract Crowdsale is owned, SafeMath {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public rate;
uint public tokenDecimals;
token public tokenReward;
uint public tokensSold = 0;
uint public start;
uint public bonusEndDate;
mapping(address => uint256) public balanceOf;
bool crowdsaleClosed = false;
event GoalReached(address beneficiary, uint capital);
event FundTransfer(address backer, uint amount, bool isContribution);
function Crowdsale( ) {
beneficiary = 0xe579891b98a3f58e26c4b2edb54e22250899363c;
rate = 250000;
tokenDecimals=8;
fundingGoal = 7500000000 * (10 ** tokenDecimals);
start = 1536688800;
deadline = 1539356400;
bonusEndDate =1539356400;
tokenReward = token(0x2DC5b9F85a5EcCC24A3abd396F9d0c43dF3D284c);
}
function () payable {
uint amount = msg.value;
uint numTokens;
numTokens = getNumTokens(amount);
require(numTokens>0 && !crowdsaleClosed && now > start && now < deadline);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], amount);
amountRaised = safeAdd(amountRaised, amount);
tokensSold += numTokens;
tokenReward.transfer(msg.sender, numTokens);
beneficiary.transfer(amount);
FundTransfer(msg.sender, amount, true);
}
function getNumTokens(uint _value) internal returns(uint numTokens) {
require(_value>=10000000000000000 * 1 wei);
numTokens = safeMul(_value,rate)/(10 ** tokenDecimals);
if(now <= bonusEndDate){
if(_value>= 0.5 ether && _value< 5 * 1 ether){
numTokens += safeMul(numTokens,10)/100;
}else if(_value>=1 * 1 ether){
numTokens += safeMul(numTokens,20)/100;
}
}
return numTokens;
}
function changeBeneficiary(address newBeneficiary) onlyOwner {
beneficiary = newBeneficiary;
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
require(msg.sender == owner);
if (tokensSold >=fundingGoal){
GoalReached(beneficiary, amountRaised);
}
tokenReward.burn(tokenReward.balanceOf(this));
crowdsaleClosed = true;
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
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 Token {
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
function transfer(address to, uint256 tokens) public returns (bool success);
}
contract TokenLiquidityContract {
using SafeMath for uint256;
address public admin;
address public traded_token;
uint256 public eth_seed_amount;
uint256 public traded_token_seed_amount;
uint256 public commission_ratio;
uint256 public eth_balance;
uint256 public traded_token_balance;
bool public eth_is_seeded;
bool public traded_token_is_seeded;
bool public trading_deactivated;
bool public admin_commission_activated;
modifier only_admin() {
require(msg.sender == admin);
_;
}
modifier trading_activated() {
require(trading_deactivated == false);
_;
}
constructor(address _traded_token,uint256 _eth_seed_amount, uint256 _traded_token_seed_amount, uint256 _commission_ratio) public {
admin = tx.origin;
traded_token = _traded_token;
eth_seed_amount = _eth_seed_amount;
traded_token_seed_amount = _traded_token_seed_amount;
commission_ratio = _commission_ratio;
}
function transferTokensThroughProxyToContract(address _from, address _to, uint256 _amount) private {
traded_token_balance = traded_token_balance.add(_amount);
require(Token(traded_token).transferFrom(_from,_to,_amount));
}
function transferTokensFromContract(address _to, uint256 _amount) private {
traded_token_balance = traded_token_balance.sub(_amount);
require(Token(traded_token).transfer(_to,_amount));
}
function transferETHToContract() private {
eth_balance = eth_balance.add(msg.value);
}
function transferETHFromContract(address _to, uint256 _amount) private {
eth_balance = eth_balance.sub(_amount);
_to.transfer(_amount);
}
function deposit_token(uint256 _amount) private {
transferTokensThroughProxyToContract(msg.sender, this, _amount);
}
function deposit_eth() private {
transferETHToContract();
}
function withdraw_token(uint256 _amount) public only_admin {
transferTokensFromContract(admin, _amount);
}
function withdraw_eth(uint256 _amount) public only_admin {
transferETHFromContract(admin, _amount);
}
function set_traded_token_as_seeded() private {
traded_token_is_seeded = true;
}
function set_eth_as_seeded() private {
eth_is_seeded = true;
}
function seed_traded_token() public only_admin {
require(!traded_token_is_seeded);
set_traded_token_as_seeded();
deposit_token(traded_token_seed_amount);
}
function seed_eth() public payable only_admin {
require(!eth_is_seeded);
require(msg.value == eth_seed_amount);
set_eth_as_seeded();
deposit_eth();
}
function seed_additional_token(uint256 _amount) public only_admin {
require(market_is_open());
deposit_token(_amount);
}
function seed_additional_eth() public payable only_admin {
require(market_is_open());
deposit_eth();
}
function market_is_open() private view returns(bool) {
return (eth_is_seeded && traded_token_is_seeded);
}
function deactivate_trading() public only_admin {
require(!trading_deactivated);
trading_deactivated = true;
}
function reactivate_trading() public only_admin {
require(trading_deactivated);
trading_deactivated = false;
}
function get_amount_sell(uint256 _amount) public view returns(uint256) {
uint256 traded_token_balance_plus_amount_ = traded_token_balance.add(_amount);
return (2*eth_balance*_amount)/(traded_token_balance + traded_token_balance_plus_amount_);
}
function get_amount_buy(uint256 _amount) public view returns(uint256) {
uint256 eth_balance_plus_amount_ = eth_balance + _amount;
return (_amount*traded_token_balance*(eth_balance_plus_amount_ + eth_balance))/(2*eth_balance_plus_amount_*eth_balance);
}
function get_amount_minus_commission(uint256 _amount) private view returns(uint256) {
return (_amount*(1 ether - commission_ratio))/(1 ether);
}
function activate_admin_commission() public only_admin {
require(!admin_commission_activated);
admin_commission_activated = true;
}
function deactivate_admin_comission() public only_admin {
require(admin_commission_activated);
admin_commission_activated = false;
}
function change_admin_commission(uint256 _new_commission_ratio) public only_admin {
require(_new_commission_ratio != commission_ratio);
commission_ratio = _new_commission_ratio;
}
function complete_sell_exchange(uint256 _amount_give) private {
uint256 amount_get_ = get_amount_sell(_amount_give);
uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_);
transferTokensThroughProxyToContract(msg.sender,this,_amount_give);
transferETHFromContract(msg.sender,amount_get_minus_commission_);
if(admin_commission_activated) {
uint256 admin_commission_ = amount_get_ - amount_get_minus_commission_;
transferETHFromContract(admin, admin_commission_);
}
}
function complete_buy_exchange() private {
uint256 amount_give_ = msg.value;
uint256 amount_get_ = get_amount_buy(amount_give_);
uint256 amount_get_minus_commission_ = get_amount_minus_commission(amount_get_);
transferETHToContract();
transferTokensFromContract(msg.sender, amount_get_minus_commission_);
if(admin_commission_activated) {
uint256 admin_commission_ = amount_get_ - amount_get_minus_commission_;
transferTokensFromContract(admin, admin_commission_);
}
}
function sell_tokens(uint256 _amount_give) public trading_activated {
require(market_is_open());
complete_sell_exchange(_amount_give);
}
function buy_tokens() private trading_activated {
require(market_is_open());
complete_buy_exchange();
}
function() public payable {
buy_tokens();
}
} | 0 |
pragma solidity ^0.4.19;
contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
contract EthernautsBase {
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
enum AssetState { Available, UpForLease, Used }
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
contract EthernautsAccessControl is EthernautsBase {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
msg.sender == cooAddress
);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
EthernautsStorage public ethernautsStorage;
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(ethernautsStorage));
require(_owns(msg.sender, _tokenId));
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0));
require(_owns(_from, _tokenId));
require(_approvedFor(_to, _tokenId));
ethernautsStorage.transfer(_from, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
contract EthernautsLogic is EthernautsOwnership {
address public newContractAddress;
function EthernautsLogic() public {
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
paused = true;
}
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
super.unpause();
}
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
}
function() external payable {
require(msg.sender == address(this));
}
mapping (address => bool) public contractsGrantedAccess;
function grantAccess(address _v2Address) public onlyCTO {
contractsGrantedAccess[_v2Address] = true;
}
function removeAccess(address _v2Address) public onlyCTO {
delete contractsGrantedAccess[_v2Address];
}
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
struct Asset {
uint16 ID;
uint8 category;
uint8 state;
bytes2 attributes;
uint64 createdAt;
uint64 cooldownEndBlock;
uint8[STATS_SIZE] stats;
uint256 cooldown;
uint256 builtBy;
}
bool public isEthernautsStorage = true;
Asset[] public assets;
mapping (uint256 => uint256) internal assetIndexToPrice;
mapping (uint256 => address) internal assetIndexToOwner;
mapping (address => uint256) internal ownershipTokenCount;
mapping (uint256 => address) internal assetIndexToApproved;
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
ownershipTokenCount[_to]++;
assetIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete assetIndexToApproved[_tokenId];
}
}
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
assetIndexToPrice[newAssetUniqueId] = _price;
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
function totalSupply() public view returns (uint256) {
return assets.length;
}
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
contract EthernautsExplore is EthernautsLogic {
function EthernautsExplore() public
EthernautsLogic() {}
event Explore(uint256 indexed shipId, uint256 indexed sectorID, uint256 time);
event Result(uint256 indexed shipId, uint256 indexed sectorID);
uint256 public secondsPerBlock = 15;
uint256 public TICK_TIME = 15;
uint256 public percentageCut = 90;
uint256 public oracleFee = 2000000;
uint256 public sectorOwnerCut = 0.01 ether;
int256 public SPEED_STAT_MAX = 30;
int256 public RANGE_STAT_MAX = 20;
int256 public MIN_TIME_EXPLORE = 60;
int256 public MAX_TIME_EXPLORE = 2160;
int256 public RANGE_SCALE = 2;
enum SectorStats {Volume, Threat, Difficulty}
uint256[] explorers;
mapping (uint256 => uint256) internal tokenIndexToExplore;
mapping (uint256 => uint256) internal tokenIndexToSector;
function getExplorerList() public view returns(
uint256[4][]
) {
uint256[4][] memory tokens = new uint256[4][](explorers.length);
uint256 index = 0;
uint16 ID;
uint8 state;
for(uint256 i = 0; i < explorers.length; i++) {
if (explorers[i] != 0) {
(ID,,state,,,,,) = ethernautsStorage.assets(explorers[i]);
tokens[index][0] = explorers[i];
tokens[index][1] = ID;
tokens[index][2] = state;
tokens[index][3] = tokenIndexToSector[explorers[i]];
index++;
}
}
if (index == 0) {
return new uint256[4][](0);
} else {
return tokens;
}
}
function setTickTime(uint256 _tickTime) external onlyCLevel {
TICK_TIME = _tickTime;
}
function setSectorOwnerCut(uint256 _sectorOwnerCut) external onlyCLevel {
sectorOwnerCut = _sectorOwnerCut;
}
function setOracleFee(uint256 _oracleFee) external onlyCLevel {
oracleFee = _oracleFee;
}
function setPercentageCut(uint256 _percentageCut) external onlyCLevel {
percentageCut = _percentageCut;
}
function explore(uint256 _shipTokenId, uint256 _sectorTokenId) payable external whenNotPaused {
require(msg.value >= sectorOwnerCut);
require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship)));
require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector)));
require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available)));
require(!isExploring(_shipTokenId));
require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId));
address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId);
require(sectorOwner != address(0));
tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId);
uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId);
uint256 time = uint256(_explorationTime(
_shipStats[uint256(ShipStats.Range)],
_shipStats[uint256(ShipStats.Speed)],
_sectorStats[uint256(SectorStats.Volume)]
));
time *= 60;
uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number);
ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock);
uint256 feeExcess = SafeMath.sub(msg.value, sectorOwnerCut);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - oracleFee;
Explore(_shipTokenId, _sectorTokenId, now + time);
oracleAddress.transfer(oracleFee);
sectorOwner.transfer(payment);
msg.sender.transfer(feeExcess);
}
function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[5] _IDs,
uint8[5] _attributes,
uint8[STATS_SIZE][5] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
for (uint256 i = 0; i < 5; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
delete explorers[tokenIndexToExplore[_shipTokenId]];
delete tokenIndexToSector[_shipTokenId];
Result(_shipTokenId, _sectorTokenId);
}
function _buildAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
private returns (uint256)
{
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
_cooldown,
_cooldownEndBlock
);
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
function _explorationTime(
uint8 _shipRange,
uint8 _shipSpeed,
uint8 _sectorVolume
) private view returns (int256) {
int256 minToExplore = 0;
minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1;
minToExplore = -72 * minToExplore;
minToExplore += MAX_TIME_EXPLORE;
uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX));
uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE);
int256 minExplore = (minToExplore - MIN_TIME_EXPLORE);
minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange));
minToExplore += fraction(minToExplore, (_sectorVolume - 10), 10);
minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE);
return minToExplore;
}
function fraction(int256 _subject, int256 _numerator, int256 _denominator)
private pure returns (int256) {
int256 division = _subject * _numerator - _subject * _denominator;
int256 total = _subject * _denominator + division;
return total / _denominator;
}
function setSecondsPerBlock(uint256 _secs) external onlyCLevel {
require(_secs > 0);
secondsPerBlock = _secs;
}
} | 0 |