source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
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 STASHInterface {
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 STASHToken is STASHInterface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function STASHToken() public {
symbol = "STASH";
name = "BitStash";
decimals = 18;
_totalSupply = 6000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
unitsOneEthCanBuy = 600000;
fundsWallet = msg.sender;
}
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);
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() payable public{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
if (balances[fundsWallet] < amount) {
return;
}
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return STASHInterface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.11;
contract DaoToken {
uint256 public CAP;
uint256 public totalEthers;
function proxyPayment(address participant) payable;
function transfer(address _to, uint _amount) returns (bool success);
}
contract ZiberToken {
mapping (address => uint256) public balances;
mapping (address => bool) public checked_in;
uint256 public bounty;
bool public bought_tokens;
uint256 public time_bought;
bool public kill_switch;
string public name;
string public symbol;
uint8 public decimals;
uint256 ZBR_per_eth = 17440;
uint256 ZBR_total_reserve = 100000000;
uint256 ZBR_dev_reserved = 10000000;
uint256 ZBR_for_selling = 80000000;
uint256 ZBR_for_bounty= 10000000;
uint256 ETH_to_end = 50000 ether;
uint registredTo;
uint256 loadedRefund;
uint256 _supply;
string _name;
string _symbol;
uint8 _decimals;
DaoToken public token = DaoToken(0xa9d585CE3B227d69985c3F7A866fE7d0e510da50);
address developer_address = 0x650887B33BFA423240ED7Bc4BD26c66075E3bEaf;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function ZiberToken() {
_supply = 10000000000;
balanceOf[msg.sender] = _supply;
name = "ZIBER Crowdsale Tokens";
symbol = "ZBR";
decimals = 2;
}
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
function loadRefund() payable {
if(msg.value == 0) throw;
loadedRefund = safeAdd(loadedRefund, msg.value);
}
function refund() private {
uint256 weiValue = this.balance;
if (weiValue == 0) throw;
uint256 weiRefunded;
weiRefunded = safeAdd(weiRefunded, weiValue);
refund();
if (!msg.sender.send(weiValue)) throw;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function activate_kill_switch() {
if (msg.sender != developer_address) throw;
kill_switch = true;
}
function withdraw(){
if (!bought_tokens) {
uint256 eth_amount = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(eth_amount);
}
else {
uint256 ZBR_amount = balances[msg.sender] * ZBR_per_eth;
balances[msg.sender] = 0;
uint256 fee = 0;
if (!checked_in[msg.sender]) {
fee = ZBR_amount / 100;
if(!token.transfer(developer_address, fee)) throw;
}
if(!token.transfer(msg.sender, ZBR_amount - fee)) throw;
}
}
function add_to_bounty() payable {
if (msg.sender != developer_address) throw;
if (kill_switch) throw;
if (bought_tokens) throw;
bounty += msg.value;
}
function claim_bounty(){
if (bought_tokens) return;
if (kill_switch) throw;
bought_tokens = true;
time_bought = now + 1 days;
token.proxyPayment.value(this.balance - bounty)(address(this));
if(this.balance > ETH_to_end)
{
msg.sender.transfer(bounty);
}
else {
time_bought = now + 1 days * 9;
if(this.balance > ETH_to_end) {
msg.sender.transfer(bounty);
}
}
}
function default_helper() payable {
if (msg.value <= 1 finney) {
if (bought_tokens) {
if (token.totalEthers() >= token.CAP()) throw;
checked_in[msg.sender] = true;
}
else {
withdraw();
}
}
else {
if (kill_switch) throw;
if (bought_tokens) throw;
balances[msg.sender] += msg.value;
}
}
function () payable {
default_helper();
}
modifier onlyOwner() {
if (msg.sender != developer_address) {
throw;
}
_;
}
function withdrawEth() onlyOwner {
msg.sender.transfer(this.balance);
}
function kill() onlyOwner {
selfdestruct(developer_address);
}
} | 0 |
pragma solidity 0.4.25;
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns(address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20 {
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 Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(ERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
contract CGCXMarchMassLock is Ownable {
using SafeERC20 for ERC20;
ERC20 public token;
mapping (address => uint256) public lockups;
uint256 public releaseTime;
constructor(address _token, uint256 _releaseTime) public {
token = ERC20(_token);
releaseTime = _releaseTime;
}
function release() public {
releaseFrom(msg.sender);
}
function releaseFrom(address _beneficiary) public {
require(block.timestamp >= releaseTime);
uint256 amount = lockups[_beneficiary];
require(amount > 0);
token.safeTransfer(_beneficiary, amount);
lockups[_beneficiary] = 0;
}
function releaseFromMultiple(address[] _addresses) public {
for (uint256 i = 0; i < _addresses.length; i++) {
releaseFrom(_addresses[i]);
}
}
function submit(address[] _addresses, uint256[] _amounts) public onlyOwner {
for (uint256 i = 0; i < _addresses.length; i++) {
lockups[_addresses[i]] = _amounts[i];
}
}
} | 1 |
pragma solidity ^0.4.18;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract 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 ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract EventfulMarket {
event LogItemUpdate(uint id);
event LogTrade(uint pay_amt, address indexed pay_gem,
uint buy_amt, address indexed buy_gem);
event LogMake(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogBump(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
event LogTake(
bytes32 id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
address indexed taker,
uint128 take_amt,
uint128 give_amt,
uint64 timestamp
);
event LogKill(
bytes32 indexed id,
bytes32 indexed pair,
address indexed maker,
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt,
uint64 timestamp
);
}
contract SimpleMarket is EventfulMarket, DSMath {
uint public last_offer_id;
mapping (uint => OfferInfo) public offers;
bool locked;
struct OfferInfo {
uint pay_amt;
ERC20 pay_gem;
uint buy_amt;
ERC20 buy_gem;
address owner;
uint64 timestamp;
}
modifier can_buy(uint id) {
require(isActive(id));
_;
}
modifier can_cancel(uint id) {
require(isActive(id));
require(getOwner(id) == msg.sender);
_;
}
modifier can_offer {
_;
}
modifier synchronized {
require(!locked);
locked = true;
_;
locked = false;
}
function isActive(uint id) public constant returns (bool active) {
return offers[id].timestamp > 0;
}
function getOwner(uint id) public constant returns (address owner) {
return offers[id].owner;
}
function getOffer(uint id) public constant returns (uint, ERC20, uint, ERC20) {
var offer = offers[id];
return (offer.pay_amt, offer.pay_gem,
offer.buy_amt, offer.buy_gem);
}
function bump(bytes32 id_)
public
can_buy(uint256(id_))
{
var id = uint256(id_);
LogBump(
id_,
keccak256(offers[id].pay_gem, offers[id].buy_gem),
offers[id].owner,
offers[id].pay_gem,
offers[id].buy_gem,
uint128(offers[id].pay_amt),
uint128(offers[id].buy_amt),
offers[id].timestamp
);
}
function buy(uint id, uint quantity)
public
can_buy(id)
synchronized
returns (bool)
{
OfferInfo memory offer = offers[id];
uint spend = mul(quantity, offer.buy_amt) / offer.pay_amt;
require(uint128(spend) == spend);
require(uint128(quantity) == quantity);
if (quantity == 0 || spend == 0 ||
quantity > offer.pay_amt || spend > offer.buy_amt)
{
return false;
}
offers[id].pay_amt = sub(offer.pay_amt, quantity);
offers[id].buy_amt = sub(offer.buy_amt, spend);
require( offer.buy_gem.transferFrom(msg.sender, offer.owner, spend) );
require( offer.pay_gem.transfer(msg.sender, quantity) );
LogItemUpdate(id);
LogTake(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
msg.sender,
uint128(quantity),
uint128(spend),
uint64(now)
);
LogTrade(quantity, offer.pay_gem, spend, offer.buy_gem);
if (offers[id].pay_amt == 0) {
delete offers[id];
}
return true;
}
function cancel(uint id)
public
can_cancel(id)
synchronized
returns (bool success)
{
OfferInfo memory offer = offers[id];
delete offers[id];
require( offer.pay_gem.transfer(offer.owner, offer.pay_amt) );
LogItemUpdate(id);
LogKill(
bytes32(id),
keccak256(offer.pay_gem, offer.buy_gem),
offer.owner,
offer.pay_gem,
offer.buy_gem,
uint128(offer.pay_amt),
uint128(offer.buy_amt),
uint64(now)
);
success = true;
}
function kill(bytes32 id)
public
{
require(cancel(uint256(id)));
}
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32 id)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
function offer(uint pay_amt, ERC20 pay_gem, uint buy_amt, ERC20 buy_gem)
public
can_offer
synchronized
returns (uint id)
{
require(uint128(pay_amt) == pay_amt);
require(uint128(buy_amt) == buy_amt);
require(pay_amt > 0);
require(pay_gem != ERC20(0x0));
require(buy_amt > 0);
require(buy_gem != ERC20(0x0));
require(pay_gem != buy_gem);
OfferInfo memory info;
info.pay_amt = pay_amt;
info.pay_gem = pay_gem;
info.buy_amt = buy_amt;
info.buy_gem = buy_gem;
info.owner = msg.sender;
info.timestamp = uint64(now);
id = _next_id();
offers[id] = info;
require( pay_gem.transferFrom(msg.sender, this, pay_amt) );
LogItemUpdate(id);
LogMake(
bytes32(id),
keccak256(pay_gem, buy_gem),
msg.sender,
pay_gem,
buy_gem,
uint128(pay_amt),
uint128(buy_amt),
uint64(now)
);
}
function take(bytes32 id, uint128 maxTakeAmount)
public
{
require(buy(uint256(id), maxTakeAmount));
}
function _next_id()
internal
returns (uint)
{
last_offer_id++; return last_offer_id;
}
}
contract ExpiringMarket is DSAuth, SimpleMarket {
uint64 public close_time;
bool public stopped;
modifier can_offer {
require(!isClosed());
_;
}
modifier can_buy(uint id) {
require(isActive(id));
require(!isClosed());
_;
}
modifier can_cancel(uint id) {
require(isActive(id));
require(isClosed() || (msg.sender == getOwner(id)));
_;
}
function ExpiringMarket(uint64 _close_time)
public
{
close_time = _close_time;
}
function isClosed() public constant returns (bool closed) {
return stopped || getTime() > close_time;
}
function getTime() public constant returns (uint64) {
return uint64(now);
}
function stop() public auth {
stopped = true;
}
}
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 MatchingEvents {
event LogBuyEnabled(bool isEnabled);
event LogMinSell(address pay_gem, uint min_amount);
event LogMatchingEnabled(bool isEnabled);
event LogUnsortedOffer(uint id);
event LogSortedOffer(uint id);
event LogAddTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogRemTokenPairWhitelist(ERC20 baseToken, ERC20 quoteToken);
event LogInsert(address keeper, uint id);
event LogDelete(address keeper, uint id);
}
contract MatchingMarket is MatchingEvents, ExpiringMarket, DSNote {
bool public buyEnabled = true;
bool public matchingEnabled = true;
struct sortInfo {
uint next;
uint prev;
uint delb;
}
mapping(uint => sortInfo) public _rank;
mapping(address => mapping(address => uint)) public _best;
mapping(address => mapping(address => uint)) public _span;
mapping(address => uint) public _dust;
mapping(uint => uint) public _near;
mapping(bytes32 => bool) public _menu;
uint _head;
modifier isWhitelist(ERC20 buy_gem, ERC20 pay_gem) {
require(_menu[keccak256(buy_gem, pay_gem)] || _menu[keccak256(pay_gem, buy_gem)]);
_;
}
function MatchingMarket(uint64 close_time) ExpiringMarket(close_time) public {
}
function make(
ERC20 pay_gem,
ERC20 buy_gem,
uint128 pay_amt,
uint128 buy_amt
)
public
returns (bytes32)
{
return bytes32(offer(pay_amt, pay_gem, buy_amt, buy_gem));
}
function take(bytes32 id, uint128 maxTakeAmount) public {
require(buy(uint256(id), maxTakeAmount));
}
function kill(bytes32 id) public {
require(cancel(uint256(id)));
}
function offer(
uint pay_amt,
ERC20 pay_gem,
uint buy_amt,
ERC20 buy_gem
)
public
isWhitelist(pay_gem, buy_gem)
returns (uint)
{
var fn = matchingEnabled ? _offeru : super.offer;
return fn(pay_amt, pay_gem, buy_amt, buy_gem);
}
function offer(
uint pay_amt,
ERC20 pay_gem,
uint buy_amt,
ERC20 buy_gem,
uint pos
)
public
isWhitelist(pay_gem, buy_gem)
can_offer
returns (uint)
{
return offer(pay_amt, pay_gem, buy_amt, buy_gem, pos, false);
}
function offer(
uint pay_amt,
ERC20 pay_gem,
uint buy_amt,
ERC20 buy_gem,
uint pos,
bool rounding
)
public
isWhitelist(pay_gem, buy_gem)
can_offer
returns (uint)
{
require(_dust[pay_gem] <= pay_amt);
if (matchingEnabled) {
return _matcho(pay_amt, pay_gem, buy_amt, buy_gem, pos, rounding);
}
return super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
}
function buy(uint id, uint amount)
public
can_buy(id)
returns (bool)
{
var fn = matchingEnabled ? _buys : super.buy;
return fn(id, amount);
}
function cancel(uint id)
public
can_cancel(id)
returns (bool success)
{
if (matchingEnabled) {
if (isOfferSorted(id)) {
require(_unsort(id));
} else {
require(_hide(id));
}
}
return super.cancel(id);
}
function insert(
uint id,
uint pos
)
public
returns (bool)
{
require(!isOfferSorted(id));
require(isActive(id));
require(pos == 0 || isActive(pos));
require(_hide(id));
_sort(id, pos);
LogInsert(msg.sender, id);
return true;
}
function del_rank(uint id)
public
returns (bool)
{
require(!isActive(id) && _rank[id].delb != 0 && _rank[id].delb < block.number - 10);
delete _rank[id];
LogDelete(msg.sender, id);
return true;
}
function addTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(!isTokenPairWhitelisted(baseToken, quoteToken));
require(address(baseToken) != 0x0 && address(quoteToken) != 0x0);
_menu[keccak256(baseToken, quoteToken)] = true;
LogAddTokenPairWhitelist(baseToken, quoteToken);
return true;
}
function remTokenPairWhitelist(
ERC20 baseToken,
ERC20 quoteToken
)
public
auth
note
returns (bool)
{
require(isTokenPairWhitelisted(baseToken, quoteToken));
delete _menu[keccak256(baseToken, quoteToken)];
delete _menu[keccak256(quoteToken, baseToken)];
LogRemTokenPairWhitelist(baseToken, quoteToken);
return true;
}
function isTokenPairWhitelisted(
ERC20 baseToken,
ERC20 quoteToken
)
public
constant
returns (bool)
{
return (_menu[keccak256(baseToken, quoteToken)] || _menu[keccak256(quoteToken, baseToken)]);
}
function setMinSell(
ERC20 pay_gem,
uint dust
)
public
auth
note
returns (bool)
{
_dust[pay_gem] = dust;
LogMinSell(pay_gem, dust);
return true;
}
function getMinSell(
ERC20 pay_gem
)
public
constant
returns (uint)
{
return _dust[pay_gem];
}
function setBuyEnabled(bool buyEnabled_) public auth returns (bool) {
buyEnabled = buyEnabled_;
LogBuyEnabled(buyEnabled);
return true;
}
function setMatchingEnabled(bool matchingEnabled_) public auth returns (bool) {
matchingEnabled = matchingEnabled_;
LogMatchingEnabled(matchingEnabled);
return true;
}
function getBestOffer(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _best[sell_gem][buy_gem];
}
function getWorseOffer(uint id) public constant returns(uint) {
return _rank[id].prev;
}
function getBetterOffer(uint id) public constant returns(uint) {
return _rank[id].next;
}
function getOfferCount(ERC20 sell_gem, ERC20 buy_gem) public constant returns(uint) {
return _span[sell_gem][buy_gem];
}
function getFirstUnsortedOffer() public constant returns(uint) {
return _head;
}
function getNextUnsortedOffer(uint id) public constant returns(uint) {
return _near[id];
}
function isOfferSorted(uint id) public constant returns(bool) {
return _rank[id].next != 0
|| _rank[id].prev != 0
|| _best[offers[id].pay_gem][offers[id].buy_gem] == id;
}
function sellAllAmount(ERC20 pay_gem, uint pay_amt, ERC20 buy_gem, uint min_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (pay_amt > 0) {
offerId = getBestOffer(buy_gem, pay_gem);
require(offerId != 0);
if (pay_amt * 1 ether < wdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) {
break;
}
if (pay_amt >= offers[offerId].buy_amt) {
fill_amt = add(fill_amt, offers[offerId].pay_amt);
pay_amt = sub(pay_amt, offers[offerId].buy_amt);
take(bytes32(offerId), uint128(offers[offerId].pay_amt));
} else {
var baux = rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9;
fill_amt = add(fill_amt, baux);
take(bytes32(offerId), uint128(baux));
pay_amt = 0;
}
}
require(fill_amt >= min_fill_amount);
}
function buyAllAmount(ERC20 buy_gem, uint buy_amt, ERC20 pay_gem, uint max_fill_amount)
public
returns (uint fill_amt)
{
uint offerId;
while (buy_amt > 0) {
offerId = getBestOffer(buy_gem, pay_gem);
require(offerId != 0);
if (buy_amt * 1 ether < wdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) {
break;
}
if (buy_amt >= offers[offerId].pay_amt) {
fill_amt = add(fill_amt, offers[offerId].buy_amt);
buy_amt = sub(buy_amt, offers[offerId].pay_amt);
take(bytes32(offerId), uint128(offers[offerId].pay_amt));
} else {
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9);
take(bytes32(offerId), uint128(buy_amt));
buy_amt = 0;
}
}
require(fill_amt <= max_fill_amount);
}
function getBuyAmount(ERC20 buy_gem, ERC20 pay_gem, uint pay_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem);
while (pay_amt > offers[offerId].buy_amt) {
fill_amt = add(fill_amt, offers[offerId].pay_amt);
pay_amt = sub(pay_amt, offers[offerId].buy_amt);
if (pay_amt > 0) {
offerId = getWorseOffer(offerId);
require(offerId != 0);
}
}
fill_amt = add(fill_amt, rmul(pay_amt * 10 ** 9, rdiv(offers[offerId].pay_amt, offers[offerId].buy_amt)) / 10 ** 9);
}
function getPayAmount(ERC20 pay_gem, ERC20 buy_gem, uint buy_amt) public constant returns (uint fill_amt) {
var offerId = getBestOffer(buy_gem, pay_gem);
while (buy_amt > offers[offerId].pay_amt) {
fill_amt = add(fill_amt, offers[offerId].buy_amt);
buy_amt = sub(buy_amt, offers[offerId].pay_amt);
if (buy_amt > 0) {
offerId = getWorseOffer(offerId);
require(offerId != 0);
}
}
fill_amt = add(fill_amt, rmul(buy_amt * 10 ** 9, rdiv(offers[offerId].buy_amt, offers[offerId].pay_amt)) / 10 ** 9);
}
function _buys(uint id, uint amount)
internal
returns (bool)
{
require(buyEnabled);
if (amount == offers[id].pay_amt && isOfferSorted(id)) {
_unsort(id);
}
require(super.buy(id, amount));
return true;
}
function _find(uint id)
internal
view
returns (uint)
{
require( id > 0 );
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint top = _best[pay_gem][buy_gem];
uint old_top = 0;
while (top != 0 && _isPricedLtOrEq(id, top)) {
old_top = top;
top = _rank[top].prev;
}
return old_top;
}
function _findpos(uint id, uint pos)
internal
view
returns (uint)
{
require(id > 0);
while (pos != 0 && !isActive(pos)) {
pos = _rank[pos].prev;
}
if (pos == 0) {
return _find(id);
} else {
if(_isPricedLtOrEq(id, pos)) {
uint old_pos;
while (pos != 0 && _isPricedLtOrEq(id, pos)) {
old_pos = pos;
pos = _rank[pos].prev;
}
return old_pos;
} else {
while (pos != 0 && !_isPricedLtOrEq(id, pos)) {
pos = _rank[pos].next;
}
return pos;
}
}
}
function _isPricedLtOrEq(
uint low,
uint high
)
internal
view
returns (bool)
{
return mul(offers[low].buy_amt, offers[high].pay_amt)
>= mul(offers[high].buy_amt, offers[low].pay_amt);
}
function _matcho(
uint t_pay_amt,
ERC20 t_pay_gem,
uint t_buy_amt,
ERC20 t_buy_gem,
uint pos,
bool rounding
)
internal
returns (uint id)
{
uint best_maker_id;
uint t_buy_amt_old;
uint m_buy_amt;
uint m_pay_amt;
while (_best[t_buy_gem][t_pay_gem] > 0) {
best_maker_id = _best[t_buy_gem][t_pay_gem];
m_buy_amt = offers[best_maker_id].buy_amt;
m_pay_amt = offers[best_maker_id].pay_amt;
if (mul(m_buy_amt, t_buy_amt) > mul(t_pay_amt, m_pay_amt) +
(rounding ? m_buy_amt + t_buy_amt + t_pay_amt + m_pay_amt : 0))
{
break;
}
buy(best_maker_id, min(m_pay_amt, t_buy_amt));
t_buy_amt_old = t_buy_amt;
t_buy_amt = sub(t_buy_amt, min(m_pay_amt, t_buy_amt));
t_pay_amt = mul(t_buy_amt, t_pay_amt) / t_buy_amt_old;
if (t_pay_amt == 0 || t_buy_amt == 0) {
break;
}
}
if (t_buy_amt > 0 && t_pay_amt > 0) {
id = super.offer(t_pay_amt, t_pay_gem, t_buy_amt, t_buy_gem);
_sort(id, pos);
}
}
function _offeru(
uint pay_amt,
ERC20 pay_gem,
uint buy_amt,
ERC20 buy_gem
)
internal
returns (uint id)
{
require(_dust[pay_gem] <= pay_amt);
id = super.offer(pay_amt, pay_gem, buy_amt, buy_gem);
_near[id] = _head;
_head = id;
LogUnsortedOffer(id);
}
function _sort(
uint id,
uint pos
)
internal
{
require(isActive(id));
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
uint prev_id;
if (pos == 0 || !isOfferSorted(pos)) {
pos = _find(id);
} else {
pos = _findpos(id, pos);
if(pos != 0 && (offers[pos].pay_gem != offers[id].pay_gem
|| offers[pos].buy_gem != offers[id].buy_gem))
{
pos = 0;
pos=_find(id);
}
}
if (pos != 0) {
prev_id = _rank[pos].prev;
_rank[pos].prev = id;
_rank[id].next = pos;
} else {
prev_id = _best[pay_gem][buy_gem];
_best[pay_gem][buy_gem] = id;
}
if (prev_id != 0) {
_rank[prev_id].next = id;
_rank[id].prev = prev_id;
}
_span[pay_gem][buy_gem]++;
LogSortedOffer(id);
}
function _unsort(
uint id
)
internal
returns (bool)
{
address buy_gem = address(offers[id].buy_gem);
address pay_gem = address(offers[id].pay_gem);
require(_span[pay_gem][buy_gem] > 0);
require(_rank[id].delb == 0 &&
isOfferSorted(id));
if (id != _best[pay_gem][buy_gem]) {
require(_rank[_rank[id].next].prev == id);
_rank[_rank[id].next].prev = _rank[id].prev;
} else {
_best[pay_gem][buy_gem] = _rank[id].prev;
}
if (_rank[id].prev != 0) {
require(_rank[_rank[id].prev].next == id);
_rank[_rank[id].prev].next = _rank[id].next;
}
_span[pay_gem][buy_gem]--;
_rank[id].delb = block.number;
return true;
}
function _hide(
uint id
)
internal
returns (bool)
{
uint uid = _head;
uint pre = uid;
require(!isOfferSorted(id));
if (_head == id) {
_head = _near[id];
_near[id] = 0;
return true;
}
while (uid > 0 && uid != id) {
pre = uid;
uid = _near[uid];
}
if (uid != id) {
return false;
}
_near[pre] = _near[id];
_near[id] = 0;
return true;
}
} | 0 |
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (signature.length != 65) {
return (address(0));
}
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.5;
library IndexedMerkleProof {
function compute(bytes memory proof, uint160 leaf) internal pure returns (uint160 root, uint256 index) {
uint160 computedHash = leaf;
for (uint256 i = 0; i < proof.length / 20; i++) {
uint160 proofElement;
assembly {
proofElement := div(mload(add(proof, add(32, mul(i, 20)))), 0x1000000000000000000000000)
}
if (computedHash < proofElement) {
computedHash = uint160(uint256(keccak256(abi.encodePacked(computedHash, proofElement))));
index += (1 << i);
} else {
computedHash = uint160(uint256(keccak256(abi.encodePacked(proofElement, computedHash))));
}
}
return (computedHash, index);
}
}
pragma solidity ^0.5.5;
contract InstaLend {
using SafeMath for uint;
address private _feesReceiver;
uint256 private _feesPercent;
bool private _inLendingMode;
modifier notInLendingMode {
require(!_inLendingMode);
_;
}
constructor(address receiver, uint256 percent) public {
_feesReceiver = receiver;
_feesPercent = percent;
}
function feesReceiver() public view returns(address) {
return _feesReceiver;
}
function feesPercent() public view returns(uint256) {
return _feesPercent;
}
function lend(
IERC20[] memory tokens,
uint256[] memory amounts,
address target,
bytes memory data
)
public
notInLendingMode
{
_inLendingMode = true;
uint256[] memory prevAmounts = new uint256[](tokens.length);
for (uint i = 0; i < tokens.length; i++) {
prevAmounts[i] = tokens[i].balanceOf(address(this));
require(tokens[i].transfer(target, amounts[i]));
}
(bool res,) = target.call(data);
require(res, "Invalid arbitrary call");
for (uint i = 0; i < tokens.length; i++) {
uint256 expectedFees = amounts[i].mul(_feesPercent).div(100);
require(tokens[i].balanceOf(address(this)) >= prevAmounts[i].add(expectedFees));
if (_feesReceiver != address(this)) {
require(tokens[i].transfer(_feesReceiver, expectedFees));
}
}
_inLendingMode = false;
}
}
pragma solidity ^0.5.0;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
pragma solidity ^0.5.5;
library CheckedERC20 {
using SafeMath for uint;
function isContract(IERC20 addr) internal view returns(bool result) {
assembly {
result := gt(extcodesize(addr), 0)
}
}
function handleReturnBool() internal pure returns(bool result) {
assembly {
switch returndatasize()
case 0 {
result := 1
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
}
function handleReturnBytes32() internal pure returns(bytes32 result) {
assembly {
switch eq(returndatasize(), 32)
case 1 {
returndatacopy(0, 0, 32)
result := mload(0)
}
switch gt(returndatasize(), 32)
case 1 {
returndatacopy(0, 64, 32)
result := mload(0)
}
switch lt(returndatasize(), 32)
case 1 {
revert(0, 0)
}
}
}
function asmTransfer(IERC20 token, address to, uint256 value) internal returns(bool) {
require(isContract(token));
(bool res,) = address(token).call(abi.encodeWithSignature("transfer(address,uint256)", to, value));
require(res);
return handleReturnBool();
}
function asmTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns(bool) {
require(isContract(token));
(bool res,) = address(token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", from, to, value));
require(res);
return handleReturnBool();
}
function asmApprove(IERC20 token, address spender, uint256 value) internal returns(bool) {
require(isContract(token));
(bool res,) = address(token).call(abi.encodeWithSignature("approve(address,uint256)", spender, value));
require(res);
return handleReturnBool();
}
function checkedTransfer(IERC20 token, address to, uint256 value) internal {
if (value > 0) {
uint256 balance = token.balanceOf(address(this));
asmTransfer(token, to, value);
require(token.balanceOf(address(this)) == balance.sub(value), "checkedTransfer: Final balance didn't match");
}
}
function checkedTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
if (value > 0) {
uint256 toBalance = token.balanceOf(to);
asmTransferFrom(token, from, to, value);
require(token.balanceOf(to) == toBalance.add(value), "checkedTransfer: Final balance didn't match");
}
}
}
pragma solidity ^0.5.2;
contract IKyberNetwork {
function trade(
address src,
uint256 srcAmount,
address dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
)
public
payable
returns(uint);
function getExpectedRate(
address source,
address dest,
uint srcQty
)
public
view
returns (
uint expectedPrice,
uint slippagePrice
);
}
pragma solidity ^0.5.0;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.5;
contract AnyPaymentReceiver is Ownable {
using SafeMath for uint256;
using CheckedERC20 for IERC20;
address constant public ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function _processPayment(
IKyberNetwork kyber,
address paymentToken,
uint256 paymentAmount
)
internal
returns(uint256)
{
uint256 previousBalance = address(this).balance;
require(IERC20(paymentToken).asmApprove(address(kyber), paymentAmount));
kyber.trade(
paymentToken,
paymentAmount,
ETHER_ADDRESS,
address(this),
1 << 255,
0,
address(0)
);
uint256 currentBalance = address(this).balance;
return currentBalance.sub(previousBalance);
}
}
pragma solidity ^0.5.5;
contract QRToken is InstaLend, AnyPaymentReceiver {
using SafeMath for uint;
using ECDSA for bytes;
using IndexedMerkleProof for bytes;
using CheckedERC20 for IERC20;
uint256 constant public MAX_CODES_COUNT = 1024;
uint256 constant public MAX_WORDS_COUNT = (MAX_CODES_COUNT + 31) / 32;
struct Distribution {
IERC20 token;
uint256 sumAmount;
uint256 codesCount;
uint256 deadline;
address sponsor;
uint256[32] bitMask;
}
mapping(uint160 => Distribution) public distributions;
event Created(
address indexed creator,
uint160 indexed root,
IERC20 indexed token,
uint256 sumTokenAmount,
uint256 codesCount,
uint256 deadline
);
event Redeemed(
uint160 indexed root,
uint256 index,
address receiver
);
constructor()
public
InstaLend(msg.sender, 1)
{
}
function create(
IERC20 token,
uint256 sumTokenAmount,
uint256 codesCount,
uint160 root,
uint256 deadline
)
external
notInLendingMode
{
require(0 < sumTokenAmount);
require(0 < codesCount && codesCount <= MAX_CODES_COUNT);
require(deadline > now);
token.checkedTransferFrom(msg.sender, address(this), sumTokenAmount);
Distribution storage distribution = distributions[root];
distribution.token = token;
distribution.sumAmount = sumTokenAmount;
distribution.codesCount = codesCount;
distribution.deadline = deadline;
distribution.sponsor = msg.sender;
emit Created(msg.sender, root, token, sumTokenAmount, codesCount, deadline);
}
function redeemed(uint160 root, uint index) public view returns(bool) {
Distribution storage distribution = distributions[root];
return distribution.bitMask[index / 32] & (1 << (index % 32)) != 0;
}
function calcRootAndIndex(
bytes memory signature,
bytes memory merkleProof,
bytes memory message
)
public
pure
returns(uint160 root, uint256 index)
{
bytes32 messageHash = keccak256(message);
bytes32 signedHash = ECDSA.toEthSignedMessageHash(messageHash);
address signer = ECDSA.recover(signedHash, signature);
uint160 signerHash = uint160(uint256(keccak256(abi.encodePacked(signer))));
return merkleProof.compute(signerHash);
}
function redeem(
bytes calldata signature,
bytes calldata merkleProof
)
external
notInLendingMode
{
(uint160 root, uint256 index) = calcRootAndIndex(signature, merkleProof, abi.encodePacked(msg.sender));
Distribution storage distribution = distributions[root];
require(distribution.bitMask[index / 32] & (1 << (index % 32)) == 0);
distribution.bitMask[index / 32] = distribution.bitMask[index / 32] | (1 << (index % 32));
distribution.token.checkedTransfer(msg.sender, distribution.sumAmount.div(distribution.codesCount));
emit Redeemed(root, index, msg.sender);
}
function redeemWithFee(
IKyberNetwork kyber,
address receiver,
uint256 feePrecent,
bytes calldata signature,
bytes calldata merkleProof
)
external
notInLendingMode
{
(uint160 root, uint256 index) = calcRootAndIndex(signature, merkleProof, abi.encodePacked(receiver, feePrecent, msg.sender));
Distribution storage distribution = distributions[root];
require(distribution.bitMask[index / 32] & (1 << (index % 32)) == 0);
distribution.bitMask[index / 32] = distribution.bitMask[index / 32] | (1 << (index % 32));
uint256 reward = distribution.sumAmount.div(distribution.codesCount);
uint256 fee = reward.mul(feePrecent).div(100);
distribution.token.checkedTransfer(receiver, reward.sub(fee));
emit Redeemed(root, index, msg.sender);
uint256 gotEther = _processPayment(kyber, address(distribution.token), fee);
msg.sender.transfer(gotEther);
}
function abort(uint160 root)
public
notInLendingMode
{
Distribution storage distribution = distributions[root];
require(now > distribution.deadline);
uint256 count = 0;
for (uint i = 0; i < 1024; i++) {
if (distribution.bitMask[i / 32] & (1 << (i % 32)) != 0) {
count += distribution.sumAmount / distribution.codesCount;
}
}
distribution.token.checkedTransfer(distribution.sponsor, distribution.sumAmount.sub(count));
delete distributions[root];
}
function() external payable {
require(msg.sender != tx.origin);
}
} | 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 = 0xE7cEc7eEe279a897b8Cbd278882DEe97B7544462;
}
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 = 29721600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x3B62b776BA14FdF78522731980eCE7613FC94b28;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract 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 RST is StandardToken, Pausable {
string public constant name = "Regime-free Stable Token";
string public constant symbol = "RST";
string public version = "1.0";
uint256 public constant decimals = 8;
bool public disabled = false;
uint256 public constant MILLION = (10**6 * 10**decimals);
constructor() public {
totalSupply_ = 500 * MILLION;
balances[msg.sender] = totalSupply_;
}
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);
}
} | 1 |
pragma solidity ^0.4.16;
contract Neulaut {
uint256 public totalSupply = 7*10**27;
uint256 public fee = 15*10**18;
uint256 public burn = 10**19;
address owner;
string public name = "Neulaut";
uint8 public decimals = 18;
string public symbol = "NUA";
mapping (address => uint256) balances;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function Neulaut() {
owner = msg.sender;
balances[owner] = totalSupply;
}
function() payable {
revert();
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(_value > fee+burn);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += (_value - fee - burn);
balances[owner] += fee;
Transfer(msg.sender, _to, (_value - fee - burn));
Transfer(msg.sender, owner, fee);
Transfer(msg.sender, address(0), burn);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
} | 1 |
pragma solidity ^0.4.20;
contract SafeMath {
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);
}
}
contract ERC20 {
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(address src, address dst, uint wad) public returns (bool);
}
contract BitFrank is SafeMath {
address public admin;
string public constant name = "BitFrank v1";
bool public suspendDeposit = false;
struct TOKEN_DETAIL {
uint8 level;
uint fee;
}
uint public marketRegisterCost = 99 * (10 ** 16);
uint public marketDefaultFeeLow = 2000;
uint public marketDefaultFeeHigh = 8000;
mapping (address => TOKEN_DETAIL) public tokenMarket;
address[] public tokenList;
mapping (address => mapping (address => uint)) public balance;
mapping (address => mapping (address => uint)) public balanceLocked;
uint public globalOrderSerial = 100000;
uint public PRICE_FACTOR = 10 ** 18;
struct ORDER {
address token;
bool isBuy;
address user;
uint wad;
uint wadFilled;
uint price;
uint listPosition;
}
mapping (uint => ORDER) public order;
uint[] public orderList;
event MARKET_CHANGE(address indexed token);
event DEPOSIT(address indexed user, address indexed token, uint wad, uint result);
event WITHDRAW(address indexed user, address indexed token, uint wad, uint result);
event ORDER_PLACE(address indexed user, address indexed token, bool isBuy, uint wad, uint price, uint indexed id);
event ORDER_CANCEL(address indexed user, address indexed token, uint indexed id);
event ORDER_MODIFY(address indexed user, address indexed token, uint indexed id, uint new_wad, uint new_price);
event ORDER_FILL(address indexed userTaker, address userMaker, address indexed token, bool isOriginalOrderBuy, uint fillAmt, uint price, uint indexed id);
event ORDER_DONE(address indexed userTaker, address userMaker, address indexed token, bool isOriginalOrderBuy, uint fillAmt, uint price, uint indexed id);
function getOrderCount() public constant returns (uint) {
return orderList.length;
}
function orderPlace(address token, bool isBuy, uint wad, uint price) public {
uint newLocked;
if (isBuy) {
newLocked = add(balanceLocked[0][msg.sender], mul(wad, price) / PRICE_FACTOR);
require(balance[0][msg.sender] >= newLocked);
balanceLocked[0][msg.sender] = newLocked;
} else {
newLocked = add(balanceLocked[token][msg.sender], wad);
require(balance[token][msg.sender] >= newLocked);
balanceLocked[token][msg.sender] = newLocked;
}
ORDER memory o;
o.token = token;
o.isBuy = isBuy;
o.wad = wad;
o.price = price;
o.user = msg.sender;
o.listPosition = orderList.length;
order[globalOrderSerial] = o;
orderList.push(globalOrderSerial);
ORDER_PLACE(msg.sender, token, isBuy, wad, price, globalOrderSerial);
globalOrderSerial++;
}
function orderTrade(uint orderID, uint wad, uint price) public {
ORDER storage o = order[orderID];
require(price == o.price);
uint fillAmt = sub(o.wad, o.wadFilled);
if (fillAmt > wad) fillAmt = wad;
uint fillETH = mul(fillAmt, price) / PRICE_FACTOR;
uint fee = mul(fillETH, tokenMarket[o.token].fee) / 1000000;
uint newTakerBalance;
if (o.isBuy) {
newTakerBalance = sub(balance[o.token][msg.sender], fillAmt);
require(newTakerBalance >= balanceLocked[o.token][msg.sender]);
balance[o.token][msg.sender] = newTakerBalance;
balance[0][o.user] = sub(balance[0][o.user], fillETH);
balanceLocked[0][o.user] = sub(balanceLocked[0][o.user], fillETH);
balance[o.token][o.user] = add(balance[o.token][o.user], fillAmt);
balance[0][msg.sender] = add(balance[0][msg.sender], sub(fillETH, fee));
} else {
newTakerBalance = sub(balance[0][msg.sender], add(fillETH, fee));
require(newTakerBalance >= balanceLocked[0][msg.sender]);
balance[0][msg.sender] = newTakerBalance;
balance[o.token][o.user] = sub(balance[o.token][o.user], fillAmt);
balanceLocked[o.token][o.user] = sub(balanceLocked[o.token][o.user], fillAmt);
balance[0][o.user] = add(balance[0][o.user], fillETH);
balance[o.token][msg.sender] = add(balance[o.token][msg.sender], fillAmt);
}
balance[0][admin] = add(balance[0][admin], fee);
o.wadFilled = add(o.wadFilled, fillAmt);
if (o.wadFilled >= o.wad) {
orderList[o.listPosition] = orderList[orderList.length - 1];
order[orderList[o.listPosition]].listPosition = o.listPosition;
orderList.length--;
ORDER_DONE(msg.sender, o.user, o.token, o.isBuy, fillAmt, price, orderID);
delete order[orderID];
} else {
ORDER_FILL(msg.sender, o.user, o.token, o.isBuy, fillAmt, price, orderID);
}
}
function orderCancel(uint orderID) public {
ORDER memory o = order[orderID];
require(o.user == msg.sender);
uint wadLeft = sub(o.wad, o.wadFilled);
if (o.isBuy) {
balanceLocked[0][msg.sender] = sub(balanceLocked[0][msg.sender], mul(o.price, wadLeft) / PRICE_FACTOR);
} else {
balanceLocked[o.token][msg.sender] = sub(balanceLocked[o.token][msg.sender], wadLeft);
}
ORDER_CANCEL(msg.sender, o.token, orderID);
orderList[o.listPosition] = orderList[orderList.length - 1];
order[orderList[o.listPosition]].listPosition = o.listPosition;
orderList.length--;
delete order[orderID];
}
function orderModify(uint orderID, uint new_wad, uint new_price) public {
ORDER storage o = order[orderID];
require(o.user == msg.sender);
require(o.wadFilled == 0);
uint newLocked;
if (o.isBuy) {
newLocked = sub(add(balanceLocked[0][msg.sender], mul(new_wad, new_price) / PRICE_FACTOR), mul(o.wad, o.price) / PRICE_FACTOR);
require(balance[0][msg.sender] >= newLocked);
balanceLocked[0][msg.sender] = newLocked;
} else {
newLocked = sub(add(balanceLocked[o.token][msg.sender], new_wad), o.wad);
require(balance[o.token][msg.sender] >= newLocked);
balanceLocked[o.token][msg.sender] = newLocked;
}
o.wad = new_wad;
o.price = new_price;
ORDER_MODIFY(msg.sender, o.token, orderID, new_wad, new_price);
}
function BitFrank() public {
admin = msg.sender;
adminSetMarket(0, 9, 0);
}
function adminSetAdmin(address newAdmin) public {
require(msg.sender == admin);
require(balance[0][newAdmin] > 0);
admin = newAdmin;
}
function adminSuspendDeposit(bool status) public {
require(msg.sender == admin);
suspendDeposit = status;
}
function adminSetMarket(address token, uint8 level_, uint fee_) public {
require(msg.sender == admin);
require(level_ != 0);
require(level_ <= 9);
if (tokenMarket[token].level == 0) {
tokenList.push(token);
}
tokenMarket[token].level = level_;
tokenMarket[token].fee = fee_;
MARKET_CHANGE(token);
}
function adminSetRegisterCost(uint cost_) public {
require(msg.sender == admin);
marketRegisterCost = cost_;
}
function adminSetDefaultFee(uint marketDefaultFeeLow_, uint marketDefaultFeeHigh_) public {
require(msg.sender == admin);
marketDefaultFeeLow = marketDefaultFeeLow_;
marketDefaultFeeHigh = marketDefaultFeeHigh_;
}
function marketRegisterToken(address token) public payable {
require(tokenMarket[token].level == 1);
require(msg.value >= marketRegisterCost);
balance[0][admin] = add(balance[0][admin], msg.value);
tokenMarket[token].level = 2;
tokenMarket[token].fee = marketDefaultFeeLow;
MARKET_CHANGE(token);
}
function getTokenCount() public constant returns (uint) {
return tokenList.length;
}
function depositETH() public payable {
require(!suspendDeposit);
balance[0][msg.sender] = add(balance[0][msg.sender], msg.value);
DEPOSIT(msg.sender, 0, msg.value, balance[0][msg.sender]);
}
function depositToken(address token, uint wad) public {
require(!suspendDeposit);
require(ERC20(token).transferFrom(msg.sender, this, wad));
if (tokenMarket[token].level == 0) {
tokenList.push(token);
tokenMarket[token].level = 1;
tokenMarket[token].fee = marketDefaultFeeHigh;
MARKET_CHANGE(token);
}
balance[token][msg.sender] = add(balance[token][msg.sender], wad);
DEPOSIT(msg.sender, token, wad, balance[token][msg.sender]);
}
function withdrawETH(uint wad) public {
balance[0][msg.sender] = sub(balance[0][msg.sender], wad);
require(balance[0][msg.sender] >= balanceLocked[0][msg.sender]);
msg.sender.transfer(wad);
WITHDRAW(msg.sender, 0, wad, balance[0][msg.sender]);
}
function withdrawToken(address token, uint wad) public {
require(token != 0);
balance[token][msg.sender] = sub(balance[token][msg.sender], wad);
require(balance[token][msg.sender] >= balanceLocked[token][msg.sender]);
require(ERC20(token).transfer(msg.sender, wad));
WITHDRAW(msg.sender, token, wad, balance[token][msg.sender]);
}
} | 0 |
pragma solidity ^0.4.18;
interface ConflictResolutionInterface {
function minHouseStake(uint activeGames) public pure returns(uint);
function maxBalance() public pure returns(int);
function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) public pure returns(bool);
function endGameConflict(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
view
returns(int);
function serverForceGameEnd(
uint8 gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
function playerForceGameEnd(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
public
view
returns(int);
}
library MathUtil {
function abs(int _val) internal pure returns(uint) {
if (_val < 0) {
return uint(-_val);
} else {
return uint(_val);
}
}
function max(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 >= _val2 ? _val1 : _val2;
}
function min(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 <= _val2 ? _val1 : _val2;
}
}
contract Ownable {
address public owner;
event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
function setOwner(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
LogOwnerShipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ConflictResolutionManager is Ownable {
ConflictResolutionInterface public conflictRes;
address public newConflictRes = 0;
uint public updateTime = 0;
uint public constant MIN_TIMEOUT = 3 days;
uint public constant MAX_TIMEOUT = 6 days;
event LogUpdatingConflictResolution(address newConflictResolutionAddress);
event LogUpdatedConflictResolution(address newConflictResolutionAddress);
function ConflictResolutionManager(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
function updateConflictResolution(address _newConflictResAddress) public onlyOwner {
newConflictRes = _newConflictResAddress;
updateTime = block.timestamp;
LogUpdatingConflictResolution(_newConflictResAddress);
}
function activateConflictResolution() public onlyOwner {
require(newConflictRes != 0);
require(updateTime != 0);
require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT);
conflictRes = ConflictResolutionInterface(newConflictRes);
newConflictRes = 0;
updateTime = 0;
LogUpdatedConflictResolution(newConflictRes);
}
}
contract Pausable is Ownable {
bool public paused = false;
uint public timePaused = 0;
modifier onlyNotPaused() {
require(!paused);
_;
}
modifier onlyPaused() {
require(paused);
_;
}
modifier onlyPausedSince(uint timeSpan) {
require(paused && timePaused + timeSpan <= block.timestamp);
_;
}
event LogPause();
event LogUnpause();
function pause() public onlyOwner onlyNotPaused {
paused = true;
timePaused = block.timestamp;
LogPause();
}
function unpause() public onlyOwner onlyPaused {
paused = false;
timePaused = 0;
LogUnpause();
}
}
contract Destroyable is Pausable {
uint public constant TIMEOUT_DESTROY = 20 days;
function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) {
selfdestruct(owner);
}
}
contract GameChannelBase is Destroyable, ConflictResolutionManager {
enum GameStatus {
ENDED,
ACTIVE,
WAITING_FOR_SERVER,
PLAYER_INITIATED_END,
SERVER_INITIATED_END
}
enum ReasonEnded {
REGULAR_ENDED,
END_FORCED_BY_SERVER,
END_FORCED_BY_PLAYER,
REJECTED_BY_SERVER,
CANCELLED_BY_PLAYER
}
struct Game {
GameStatus status;
ReasonEnded reasonEnded;
uint stake;
uint8 gameType;
uint32 roundId;
uint16 betNum;
uint betValue;
int balance;
bytes32 playerSeed;
bytes32 serverSeed;
uint endInitiatedTime;
}
uint public constant MIN_TRANSFER_TIMESPAN = 1 days;
uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days;
uint public activeGames = 0;
uint public gameIdCntr;
address public serverAddress;
address public houseAddress;
uint public houseStake = 0;
int public houseProfit = 0;
uint public minStake;
uint public maxStake;
uint public profitTransferTimeSpan = 14 days;
uint public lastProfitTransferTimestamp;
bytes32 public typeHash;
mapping (uint => Game) public gameIdGame;
mapping (address => uint) public playerGameId;
mapping (address => uint) public pendingReturns;
modifier onlyValidHouseStake(uint _activeGames) {
uint minHouseStake = conflictRes.minHouseStake(_activeGames);
require(houseStake >= minHouseStake);
_;
}
modifier onlyValidValue() {
require(minStake <= msg.value && msg.value <= maxStake);
_;
}
modifier onlyServer() {
require(msg.sender == serverAddress);
_;
}
modifier onlyValidTransferTimeSpan(uint transferTimeout) {
require(transferTimeout >= MIN_TRANSFER_TIMESPAN
&& transferTimeout <= MAX_TRANSFER_TIMSPAN);
_;
}
event LogGameCreated(address indexed player, uint indexed gameId, uint stake, bytes32 endHash);
event LogGameRejected(address indexed player, uint indexed gameId);
event LogGameAccepted(address indexed player, uint indexed gameId, bytes32 endHash);
event LogPlayerRequestedEnd(address indexed player, uint indexed gameId);
event LogServerRequestedEnd(address indexed player, uint indexed gameId);
event LogGameEnded(address indexed player, uint indexed gameId, ReasonEnded reason);
event LogStakeLimitsModified(uint minStake, uint maxStake);
function GameChannelBase(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
ConflictResolutionManager(_conflictResAddress)
{
require(_minStake > 0 && _minStake <= _maxStake);
require(_gameIdCntr > 0);
gameIdCntr = _gameIdCntr;
serverAddress = _serverAddress;
houseAddress = _houseAddress;
lastProfitTransferTimestamp = block.timestamp;
minStake = _minStake;
maxStake = _maxStake;
typeHash = keccak256(
"uint32 Round Id",
"uint8 Game Type",
"uint16 Number",
"uint Value (Wei)",
"int Current Balance (Wei)",
"bytes32 Server Hash",
"bytes32 Player Hash",
"uint Game Id",
"address Contract Address"
);
}
function withdraw() public {
uint toTransfer = pendingReturns[msg.sender];
require(toTransfer > 0);
pendingReturns[msg.sender] = 0;
msg.sender.transfer(toTransfer);
}
function transferProfitToHouse() public {
require(lastProfitTransferTimestamp + profitTransferTimeSpan <= block.timestamp);
if (houseProfit <= 0) {
lastProfitTransferTimestamp = block.timestamp;
return;
}
uint toTransfer = uint(houseProfit);
assert(houseStake >= toTransfer);
houseProfit = 0;
lastProfitTransferTimestamp = block.timestamp;
houseStake = houseStake - toTransfer;
houseAddress.transfer(toTransfer);
}
function setProfitTransferTimeSpan(uint _profitTransferTimeSpan)
public
onlyOwner
onlyValidTransferTimeSpan(_profitTransferTimeSpan)
{
profitTransferTimeSpan = _profitTransferTimeSpan;
}
function addHouseStake() public payable onlyOwner {
houseStake += msg.value;
}
function withdrawHouseStake(uint value) public onlyOwner {
uint minHouseStake = conflictRes.minHouseStake(activeGames);
require(value <= houseStake && houseStake - value >= minHouseStake);
require(houseProfit <= 0 || uint(houseProfit) <= houseStake - value);
houseStake = houseStake - value;
owner.transfer(value);
}
function withdrawAll() public onlyOwner onlyPausedSince(3 days) {
houseProfit = 0;
uint toTransfer = houseStake;
houseStake = 0;
owner.transfer(toTransfer);
}
function setHouseAddress(address _houseAddress) public onlyOwner {
houseAddress = _houseAddress;
}
function setStakeRequirements(uint _minStake, uint _maxStake) public onlyOwner {
require(_minStake > 0 && _minStake <= _maxStake);
minStake = _minStake;
maxStake = _maxStake;
LogStakeLimitsModified(minStake, maxStake);
}
function closeGame(
Game storage _game,
uint _gameId,
address _playerAddress,
ReasonEnded _reason,
int _balance
)
internal
{
_game.status = GameStatus.ENDED;
_game.reasonEnded = _reason;
_game.balance = _balance;
assert(activeGames > 0);
activeGames = activeGames - 1;
LogGameEnded(_playerAddress, _gameId, _reason);
}
function payOut(Game storage _game, address _playerAddress) internal {
assert(_game.balance <= conflictRes.maxBalance());
assert(_game.status == GameStatus.ENDED);
assert(_game.stake <= maxStake);
assert((int(_game.stake) + _game.balance) >= 0);
uint valuePlayer = uint(int(_game.stake) + _game.balance);
if (_game.balance > 0 && int(houseStake) < _game.balance) {
valuePlayer = houseStake;
}
houseProfit = houseProfit - _game.balance;
int newHouseStake = int(houseStake) - _game.balance;
assert(newHouseStake >= 0);
houseStake = uint(newHouseStake);
pendingReturns[_playerAddress] += valuePlayer;
if (pendingReturns[_playerAddress] > 0) {
safeSend(_playerAddress);
}
}
function safeSend(address _address) internal {
uint valueToSend = pendingReturns[_address];
assert(valueToSend > 0);
pendingReturns[_address] = 0;
if (_address.send(valueToSend) == false) {
pendingReturns[_address] = valueToSend;
}
}
function verifySig(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _sig,
address _address
)
internal
view
{
address contractAddress = this;
require(_contractAddress == contractAddress);
bytes32 roundHash = calcHash(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
verify(
roundHash,
_sig,
_address
);
}
function calcHash(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress
)
private
view
returns(bytes32)
{
bytes32 dataHash = keccak256(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress
);
return keccak256(typeHash, dataHash);
}
function verify(
bytes32 _hash,
bytes _sig,
address _address
)
private
pure
{
var (r, s, v) = signatureSplit(_sig);
address addressRecover = ecrecover(_hash, v, r, s);
require(addressRecover == _address);
}
function signatureSplit(bytes _signature)
private
pure
returns (bytes32 r, bytes32 s, uint8 v)
{
require(_signature.length == 65);
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 2) {
v = v + 27;
}
}
}
contract GameChannelConflict is GameChannelBase {
function GameChannelConflict(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCtr
)
public
GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCtr)
{
}
function serverEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _playerSig,
address _playerAddress,
bytes32 _serverSeed,
bytes32 _playerSeed
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
serverEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_serverSeed,
_playerSeed,
_gameId,
_playerAddress
);
}
function playerEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig,
bytes32 _playerSeed
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
playerEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_playerHash,
_playerSeed,
_gameId,
msg.sender
);
}
function playerCancelActiveGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.PLAYER_INITIATED_END;
LogPlayerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, playerAddress);
} else {
revert();
}
}
function serverCancelActiveGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.SERVER_INITIATED_END;
LogServerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == 0) {
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, 0);
payOut(game, _playerAddress);
} else {
revert();
}
}
function serverForceGameEnd(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.SERVER_INITIATED_END);
int newBalance = conflictRes.serverForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, _playerAddress, ReasonEnded.END_FORCED_BY_SERVER, newBalance);
payOut(game, _playerAddress);
}
function playerForceGameEnd(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.PLAYER_INITIATED_END);
int newBalance = conflictRes.playerForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, playerAddress, ReasonEnded.END_FORCED_BY_PLAYER, newBalance);
payOut(game, playerAddress);
}
function playerEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _playerHash,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require(int(game.stake) + _balance - int(_value) >= 0);
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) {
game.playerSeed = _playerSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.PLAYER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.playerSeed = _playerSeed;
game.serverSeed = bytes32(0);
LogPlayerRequestedEnd(msg.sender, gameId);
} else {
revert();
}
}
function serverEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
bytes32 _serverSeed,
bytes32 _playerSeed,
uint _gameId,
address _playerAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
require(gameId == _gameId);
require(_roundId > 0);
require(keccak256(_serverSeed) == _serverHash);
require(keccak256(_playerSeed) == _playerHash);
require(_value <= game.stake);
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require(int(game.stake) + _balance - int(_value) >= 0);
require(conflictRes.isValidBet(_gameType, _num, _value));
if (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId == _roundId) {
game.serverSeed = _serverSeed;
endGameConflict(game, gameId, _playerAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.PLAYER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.SERVER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.serverSeed = _serverSeed;
game.playerSeed = _playerSeed;
LogServerRequestedEnd(_playerAddress, gameId);
} else {
revert();
}
}
function endGameConflict(Game storage _game, uint _gameId, address _playerAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.playerSeed
);
closeGame(_game, _gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, newBalance);
payOut(_game, _playerAddress);
}
}
contract GameChannel is GameChannelConflict {
function GameChannel(
address _serverAddress,
uint _minStake,
uint _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _gameIdCntr
)
public
GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _gameIdCntr)
{
}
function createGame(bytes32 _endHash)
public
payable
onlyValidValue
onlyValidHouseStake(activeGames + 1)
onlyNotPaused
{
address playerAddress = msg.sender;
uint previousGameId = playerGameId[playerAddress];
Game storage game = gameIdGame[previousGameId];
require(game.status == GameStatus.ENDED);
uint gameId = gameIdCntr++;
playerGameId[playerAddress] = gameId;
Game storage newGame = gameIdGame[gameId];
newGame.stake = msg.value;
newGame.status = GameStatus.WAITING_FOR_SERVER;
activeGames = activeGames + 1;
LogGameCreated(playerAddress, gameId, msg.value, _endHash);
}
function cancelGame(uint _gameId) public {
address playerAddress = msg.sender;
uint gameId = playerGameId[playerAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, playerAddress, ReasonEnded.CANCELLED_BY_PLAYER, 0);
payOut(game, playerAddress);
}
function rejectGame(address _playerAddress, uint _gameId) public onlyServer {
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
closeGame(game, gameId, _playerAddress, ReasonEnded.REJECTED_BY_SERVER, 0);
payOut(game, _playerAddress);
LogGameRejected(_playerAddress, gameId);
}
function acceptGame(address _playerAddress, uint _gameId, bytes32 _endHash)
public
onlyServer
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
require(_gameId == gameId);
require(game.status == GameStatus.WAITING_FOR_SERVER);
game.status = GameStatus.ACTIVE;
LogGameAccepted(_playerAddress, gameId, _endHash);
}
function serverEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
address _playerAddress,
bytes _playerSig
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_playerSig,
_playerAddress
);
regularEndGame(_playerAddress, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
function playerEndGame(
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _playerHash,
uint _gameId,
address _contractAddress,
bytes _serverSig
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_playerHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
regularEndGame(msg.sender, _roundId, _gameType, _num, _value, _balance, _gameId, _contractAddress);
}
function regularEndGame(
address _playerAddress,
uint32 _roundId,
uint8 _gameType,
uint16 _num,
uint _value,
int _balance,
uint _gameId,
address _contractAddress
)
private
{
uint gameId = playerGameId[_playerAddress];
Game storage game = gameIdGame[gameId];
address contractAddress = this;
int maxBalance = conflictRes.maxBalance();
require(_gameId == gameId);
require(_roundId > 0);
require(-int(game.stake) <= _balance && _balance <= maxBalance);
require((_gameType == 0) && (_num == 0) && (_value == 0));
require(_contractAddress == contractAddress);
require(game.status == GameStatus.ACTIVE);
closeGame(game, gameId, _playerAddress, ReasonEnded.REGULAR_ENDED, _balance);
payOut(game, _playerAddress);
}
} | 0 |
pragma solidity ^0.4.23;
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract BLTCoin is ERC20Interface, Owned{
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
uint256 public rate;
uint256 public weiRaised;
uint value;
uint _ICOTokensLimit;
uint _ownerTokensLimit;
uint public bonusPercentage;
bool public icoOpen;
bool public bonusCompaignOpen;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
modifier onlyWhileOpen {
require(icoOpen);
_;
}
function BLTCoin(address _owner) public{
icoOpen = false;
bonusCompaignOpen = false;
symbol = "BLT";
name = "BrotherlyLend";
decimals = 18;
rate = 142857;
owner = _owner;
_totalSupply = totalSupply();
_ICOTokensLimit = _icoTokens();
_ownerTokensLimit = _ownersTokens();
balances[owner] = _ownerTokensLimit;
balances[this] = _ICOTokensLimit;
emit Transfer(address(0),owner,_ownerTokensLimit);
emit Transfer(address(0),this,_ICOTokensLimit);
}
function _icoTokens() internal constant returns(uint){
return 9019800000 * 10**uint(decimals);
}
function _ownersTokens() internal constant returns(uint){
return 11024200000 * 10**uint(decimals);
}
function totalSupply() public constant returns (uint){
return 20044000000 * 10**uint(decimals);
}
function startICO() public onlyOwner{
require(!icoOpen);
icoOpen = true;
}
function stopICO() public onlyOwner{
require(icoOpen);
icoOpen = false;
}
function startBonusCompaign(uint _percentage) public onlyOwner{
bonusCompaignOpen = true;
bonusPercentage = _percentage;
}
function stopBonusCompaign() public onlyOwner{
bonusCompaignOpen = false;
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
require(to != 0x0);
require(balances[msg.sender] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender,to,tokens);
return true;
}
function _transfer(address _to, uint _tokens) internal returns (bool success){
require(_to != 0x0);
require(balances[this] >= _tokens );
require(balances[_to] + _tokens >= balances[_to]);
balances[this] = balances[this].sub(_tokens);
balances[_to] = balances[_to].add(_tokens);
emit Transfer(this,_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){
require(tokens <= allowed[from][msg.sender]);
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
emit Transfer(from,to,tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function () external payable{
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable onlyWhileOpen{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
if(bonusCompaignOpen){
uint p = tokens.mul(bonusPercentage.mul(100));
p = p.div(10000);
tokens = tokens.add(p);
}
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(this, _beneficiary, weiAmount, tokens);
_forwardFunds();
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0x0));
require(_weiAmount != 0);
}
function _getTokenAmount(uint256 _weiAmount) internal returns (uint256) {
return _weiAmount.mul(rate);
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
_transfer(_beneficiary,_tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _forwardFunds() internal {
owner.transfer(msg.value);
}
} | 1 |
pragma solidity 0.4.25;
contract Token {
function totalSupply() constant returns (uint supply) {}
function balanceOf(address _owner) constant returns (uint balance) {}
function transfer(address _to, uint _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
function approve(address _spender, uint _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract RegularToken is Token {
function transfer(address _to, uint _value) returns (bool) {
if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint _value) returns (bool) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint) {
return allowed[_owner][_spender];
}
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
uint public totalSupply;
}
contract UnboundedRegularToken is RegularToken {
uint constant MAX_UINT = 2**256 - 1;
function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
uint allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value
&& allowance >= _value
&& balances[_to] + _value >= balances[_to]
) {
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
}
contract Globtc is UnboundedRegularToken {
uint public totalSupply = 21*10**26;
uint8 constant public decimals = 18;
string constant public name = "Globtc Token";
string constant public symbol = "GBTC";
constructor() {
balances[msg.sender] = totalSupply;
emit Transfer(address(0), 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 = 29116800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x8D8eD821749112f11f050F40AaB74D04C7bc5940
;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.11;
contract SFToken {
string public name = "SF Token";
string public symbol = "SF";
uint256 public decimals = 4;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public totalSupply = 0;
bool public stopped = false;
uint256 constant valueFounder = 2100000000000;
address owner = 0x0;
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier isRunning {
assert (!stopped);
_;
}
modifier validAddress {
assert(0x0 != msg.sender);
_;
}
function SFToken(address _addressFounder) {
owner = msg.sender;
totalSupply = valueFounder;
balanceOf[_addressFounder] = valueFounder;
Transfer(0x0, _addressFounder, valueFounder);
}
function transfer(address _to, uint256 _value) isRunning validAddress returns (bool success) {
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress returns (bool success) {
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_to] += _value;
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) isRunning validAddress returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function stop() isOwner {
stopped = true;
}
function start() isOwner {
stopped = false;
}
function setName(string _name) isOwner {
name = _name;
}
function burn(uint256 _value) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[0x0] += _value;
Transfer(msg.sender, 0x0, _value);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 |
pragma solidity ^0.4.19;
contract WorldWarFree {
string public constant symbol ="WXW";
string public constant name ="WorldWarFree";
uint8 public constant decimals = 2;
uint256 public totalSupply = 100000000 * 10 ** uint256(decimals);
address public owner;
uint256 public RATE_ETH_WXW = 10000;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function WorldWarFree() public{
owner = msg.sender;
}
function () public payable {
create(msg.sender);
}
function create(address beneficiary)public payable{
uint256 amount = msg.value;
if(amount > 0){
balances[beneficiary] += amount/RATE_ETH_WXW;
totalSupply += amount/RATE_ETH_WXW;
}
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function collect(uint256 amount) onlyOwner public{
msg.sender.transfer(amount);
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) public returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 |
pragma solidity ^0.4.23;
contract ZTHReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool);
}
contract ZTHInterface {
function getFrontEndTokenBalanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function approve(address spender, uint tokens) public returns (bool);
}
contract Zethroll is ZTHReceivingContract {
using SafeMath for uint;
modifier betIsValid(uint _betSize, uint _playerNumber) {
require( calculateProfit(_betSize, _playerNumber) < maxProfit
&& _betSize >= minBet
&& _playerNumber > minNumber
&& _playerNumber < maxNumber);
_;
}
modifier gameIsActive {
require(gamePaused == false);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
uint constant private MAX_INT = 2 ** 256 - 1;
uint constant public maxProfitDivisor = 1000000;
uint constant public maxNumber = 100;
uint constant public minNumber = 2;
uint constant public houseEdgeDivisor = 1000;
bool public gamePaused;
address public owner;
address public ZethrBankroll;
address public ZTHTKNADDR;
ZTHInterface public ZTHTKN;
uint public contractBalance;
uint public houseEdge;
uint public maxProfit;
uint public maxProfitAsPercentOfHouse;
uint public minBet = 0;
uint public totalBets;
uint public totalZTHWagered;
event LogBet(address sender, uint value, uint rollUnder);
event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won);
event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred);
event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit);
event CurrentContractBalance(uint _tokens);
constructor (address zthtknaddr, address zthbankrolladdr) public {
owner = msg.sender;
ZTHTKN = ZTHInterface(zthtknaddr);
ZTHTKNADDR = zthtknaddr;
ZethrBankroll = zthbankrolladdr;
houseEdge = 990;
ownerSetMaxProfitAsPercentOfHouse(10000);
ownerSetMinBet(1e18);
ZTHTKN.approve(zthbankrolladdr, MAX_INT);
}
function() public payable {}
function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) {
return uint256(keccak256(
abi.encodePacked(
blockhash(blockn),
entropy)
));
}
function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) {
return maxRandom(blockn, entropy) % upper;
}
function calculateProfit(uint _initBet, uint _roll)
private
view
returns (uint)
{
return ((((_initBet * (101 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet;
}
struct playerRoll{
uint200 tokenValue;
uint48 blockn;
uint8 rollUnder;
}
mapping(address => playerRoll) public playerRolls;
function _playerRollDice(uint _rollUnder, TKN _tkn) private
gameIsActive
betIsValid(_tkn.value, _rollUnder)
{
require(_tkn.value < ((2 ** 200) - 1));
require(block.number < ((2 ** 48) - 1));
require(_zthToken(msg.sender));
playerRoll memory roll = playerRolls[_tkn.sender];
require(block.number != roll.blockn);
if (roll.blockn != 0) {
_finishBet(false, _tkn.sender);
}
roll.blockn = uint40(block.number);
roll.tokenValue = uint200(_tkn.value);
roll.rollUnder = uint8(_rollUnder);
playerRolls[_tkn.sender] = roll;
emit LogBet(_tkn.sender, _tkn.value, _rollUnder);
totalBets += 1;
totalZTHWagered += _tkn.value;
}
function finishBet() public
gameIsActive
{
_finishBet(true, msg.sender);
}
function _finishBet(bool delete_it, address target) private {
playerRoll memory roll = playerRolls[target];
require(roll.tokenValue > 0);
uint result;
if (block.number - roll.blockn > 255) {
result = 1000;
} else {
result = random(100, roll.blockn, target) + 1;
}
uint rollUnder = roll.rollUnder;
if (result < rollUnder) {
uint profit = calculateProfit(roll.tokenValue, rollUnder);
contractBalance = contractBalance.sub(profit);
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true);
setMaxProfit();
if (delete_it){
delete playerRolls[target];
}
ZTHTKN.transfer(target, profit + roll.tokenValue);
} else {
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false);
contractBalance = contractBalance.add(roll.tokenValue);
setMaxProfit();
}
}
struct TKN {address sender; uint value;}
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) {
if (_from == ZethrBankroll) {
contractBalance = contractBalance.add(_value);
uint oldMaxProfit = maxProfit;
setMaxProfit();
emit MaxProfitChanged(oldMaxProfit, maxProfit);
return true;
} else {
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
uint chosenNumber = uint(_data[0]);
_playerRollDice(chosenNumber, _tkn);
}
return true;
}
function setMaxProfit() internal {
emit CurrentContractBalance(contractBalance);
maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor;
}
function ownerUpdateContractBalance(uint newContractBalance) public
onlyOwner
{
contractBalance = newContractBalance;
}
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public
onlyOwner
{
require(newMaxProfitAsPercent <= 200000);
maxProfitAsPercentOfHouse = newMaxProfitAsPercent;
setMaxProfit();
}
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
function ownerTransferZTH(address sendTo, uint amount) public
onlyOwner
{
contractBalance = contractBalance.sub(amount);
setMaxProfit();
require(ZTHTKN.transfer(sendTo, amount));
emit LogOwnerTransfer(sendTo, amount);
}
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
function ownerSetBankroll(address newBankroll) public
onlyOwner
{
ZTHTKN.approve(ZethrBankroll, 0);
ZethrBankroll = newBankroll;
ZTHTKN.approve(newBankroll, MAX_INT);
}
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
function ownerkill() public
onlyOwner
{
ZTHTKN.transfer(owner, contractBalance);
selfdestruct(owner);
}
function dumpdivs() public{
ZethrBankroll.transfer(address(this).balance);
}
function _zthToken(address _tokenContract) private view returns (bool) {
return _tokenContract == ZTHTKNADDR;
}
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
} | 0 |
pragma solidity ^0.4.20;
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
function AccessAdmin() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
function withdraw(address _target, uint256 _amount)
external
{
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
uint256 balance = this.balance;
if (_amount < balance) {
receiver.transfer(_amount);
} else {
receiver.transfer(this.balance);
}
}
}
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 PrizePool is AccessService {
using SafeMath for uint256;
event SendPrizeSuccesss(uint64 flag, uint256 oldBalance, uint256 sendVal);
event PrizeTimeClear(uint256 newVal);
uint64 public nextPrizeTime;
uint256 maxPrizeOneDay = 30;
function PrizePool() public {
addrAdmin = msg.sender;
addrService = msg.sender;
addrFinance = msg.sender;
}
function() external payable {
}
function getBalance() external view returns(uint256) {
return this.balance;
}
function clearNextPrizeTime() external onlyService {
nextPrizeTime = 0;
PrizeTimeClear(0);
}
function setMaxPrizeOneDay(uint256 val) external onlyAdmin {
require(val > 0 && val < 100);
require(val != maxPrizeOneDay);
maxPrizeOneDay = val;
}
function sendPrize(address[] winners, uint256[] amounts, uint64 _flag)
external
onlyService
whenNotPaused
{
uint64 tmNow = uint64(block.timestamp);
uint256 length = winners.length;
require(length == amounts.length);
require(length <= 64);
uint256 sum = 0;
for (uint32 i = 0; i < length; ++i) {
sum = sum.add(amounts[i]);
}
uint256 balance = this.balance;
require((sum.mul(100).div(balance)) <= maxPrizeOneDay);
address addrZero = address(0);
for (uint32 j = 0; j < length; ++j) {
if (winners[j] != addrZero) {
winners[j].transfer(amounts[j]);
}
}
nextPrizeTime = tmNow + 72000;
SendPrizeSuccesss(_flag, balance, sum);
}
} | 1 |
pragma solidity ^0.4.21;
contract DateTime {
struct _DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) public pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) public pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
}
else if (isLeapYear(year)) {
return 29;
}
else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
dt.hour = getHour(timestamp);
dt.minute = getMinute(timestamp);
dt.second = getSecond(timestamp);
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) public pure returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) public pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) public pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) public pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, minute, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) {
uint16 i;
for (i = ORIGIN_YEAR; i < year; i++) {
if (isLeapYear(i)) {
timestamp += LEAP_YEAR_IN_SECONDS;
}
else {
timestamp += YEAR_IN_SECONDS;
}
}
uint8[12] memory monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(year)) {
monthDayCounts[1] = 29;
}
else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
for (i = 1; i < month; i++) {
timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
}
timestamp += DAY_IN_SECONDS * (day - 1);
timestamp += HOUR_IN_SECONDS * (hour);
timestamp += MINUTE_IN_SECONDS * (minute);
timestamp += second;
return timestamp;
}
}
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;
}
interface ICrowdsaleFund {
function processContribution(address contributor) external payable;
function onCrowdsaleEnd() external;
function enableCrowdsaleRefund() external;
}
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 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 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 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 Fund is ICrowdsaleFund, SafeMath, MultiOwnable {
enum FundState {
Crowdsale,
CrowdsaleRefund,
TeamWithdraw,
Refund
}
FundState public state = FundState.Crowdsale;
ManagedToken public token;
uint256 public constant INITIAL_TAP = 192901234567901;
address public teamWallet;
uint256 public crowdsaleEndDate;
address public referralTokenWallet;
address public foundationTokenWallet;
address public reserveTokenWallet;
address public bountyTokenWallet;
address public companyTokenWallet;
address public advisorTokenWallet;
uint256 public tap;
uint256 public lastWithdrawTime = 0;
uint256 public firstWithdrawAmount = 0;
address public crowdsaleAddress;
mapping(address => uint256) public contributions;
event RefundContributor(address tokenHolder, uint256 amountWei, uint256 timestamp);
event RefundHolder(address tokenHolder, uint256 amountWei, uint256 tokenAmount, uint256 timestamp);
event Withdraw(uint256 amountWei, uint256 timestamp);
event RefundEnabled(address initiatorAddress);
function Fund(
address _teamWallet,
address _referralTokenWallet,
address _foundationTokenWallet,
address _companyTokenWallet,
address _reserveTokenWallet,
address _bountyTokenWallet,
address _advisorTokenWallet,
address[] _owners
) public
{
teamWallet = _teamWallet;
referralTokenWallet = _referralTokenWallet;
foundationTokenWallet = _foundationTokenWallet;
companyTokenWallet = _companyTokenWallet;
reserveTokenWallet = _reserveTokenWallet;
bountyTokenWallet = _bountyTokenWallet;
advisorTokenWallet = _advisorTokenWallet;
_setOwners(_owners);
}
modifier withdrawEnabled() {
require(canWithdraw());
_;
}
modifier onlyCrowdsale() {
require(msg.sender == crowdsaleAddress);
_;
}
function canWithdraw() public returns(bool);
function setCrowdsaleAddress(address _crowdsaleAddress) public onlyOwner {
require(crowdsaleAddress == address(0));
crowdsaleAddress = _crowdsaleAddress;
}
function setTokenAddress(address _tokenAddress) public onlyOwner {
require(address(token) == address(0));
token = ManagedToken(_tokenAddress);
}
function processContribution(address contributor) external payable onlyCrowdsale {
require(state == FundState.Crowdsale);
uint256 totalContribution = safeAdd(contributions[contributor], msg.value);
contributions[contributor] = totalContribution;
}
function onCrowdsaleEnd() external onlyCrowdsale {
state = FundState.TeamWithdraw;
ISimpleCrowdsale crowdsale = ISimpleCrowdsale(crowdsaleAddress);
firstWithdrawAmount = safeDiv(crowdsale.getSoftCap(), 2);
lastWithdrawTime = now;
tap = INITIAL_TAP;
crowdsaleEndDate = now;
}
function enableCrowdsaleRefund() external onlyCrowdsale {
require(state == FundState.Crowdsale);
state = FundState.CrowdsaleRefund;
}
function refundCrowdsaleContributor() external {
require(state == FundState.CrowdsaleRefund);
require(contributions[msg.sender] > 0);
uint256 refundAmount = contributions[msg.sender];
contributions[msg.sender] = 0;
token.destroy(msg.sender, token.balanceOf(msg.sender));
msg.sender.transfer(refundAmount);
RefundContributor(msg.sender, refundAmount, now);
}
function decTap(uint256 _tap) external onlyOwner {
require(state == FundState.TeamWithdraw);
require(_tap < tap);
tap = _tap;
}
function getCurrentTapAmount() public constant returns(uint256) {
if(state != FundState.TeamWithdraw) {
return 0;
}
return calcTapAmount();
}
function calcTapAmount() internal view returns(uint256) {
uint256 amount = safeMul(safeSub(now, lastWithdrawTime), tap);
if(address(this).balance < amount) {
amount = address(this).balance;
}
return amount;
}
function firstWithdraw() public onlyOwner withdrawEnabled {
require(firstWithdrawAmount > 0);
uint256 amount = firstWithdrawAmount;
firstWithdrawAmount = 0;
teamWallet.transfer(amount);
Withdraw(amount, now);
}
function withdraw() public onlyOwner withdrawEnabled {
require(state == FundState.TeamWithdraw);
uint256 amount = calcTapAmount();
lastWithdrawTime = now;
teamWallet.transfer(amount);
Withdraw(amount, now);
}
function enableRefund() internal {
require(state == FundState.TeamWithdraw);
state = FundState.Refund;
token.destroy(companyTokenWallet, token.balanceOf(companyTokenWallet));
token.destroy(reserveTokenWallet, token.balanceOf(reserveTokenWallet));
token.destroy(foundationTokenWallet, token.balanceOf(foundationTokenWallet));
token.destroy(bountyTokenWallet, token.balanceOf(bountyTokenWallet));
token.destroy(referralTokenWallet, token.balanceOf(referralTokenWallet));
token.destroy(advisorTokenWallet, token.balanceOf(advisorTokenWallet));
RefundEnabled(msg.sender);
}
function refundTokenHolder() public {
require(state == FundState.Refund);
uint256 tokenBalance = token.balanceOf(msg.sender);
require(tokenBalance > 0);
uint256 refundAmount = safeDiv(safeMul(tokenBalance, address(this).balance), token.totalSupply());
require(refundAmount > 0);
token.destroy(msg.sender, tokenBalance);
msg.sender.transfer(refundAmount);
RefundHolder(msg.sender, refundAmount, tokenBalance, now);
}
}
interface IPollManagedFund {
function onTapPollFinish(bool agree, uint256 _tap) external;
function onRefundPollFinish(bool agree) external;
}
contract BasePoll is SafeMath {
struct Vote {
uint256 time;
uint256 weight;
bool agree;
}
uint256 public constant MAX_TOKENS_WEIGHT_DENOM = 1000;
IERC20Token public token;
address public fundAddress;
uint256 public startTime;
uint256 public endTime;
bool checkTransfersAfterEnd;
uint256 public yesCounter = 0;
uint256 public noCounter = 0;
uint256 public totalVoted = 0;
bool public finalized;
mapping(address => Vote) public votesByAddress;
modifier checkTime() {
require(now >= startTime && now <= endTime);
_;
}
modifier notFinalized() {
require(!finalized);
_;
}
function BasePoll(address _tokenAddress, address _fundAddress, uint256 _startTime, uint256 _endTime, bool _checkTransfersAfterEnd) public {
require(_tokenAddress != address(0));
require(_startTime >= now && _endTime > _startTime);
token = IERC20Token(_tokenAddress);
fundAddress = _fundAddress;
startTime = _startTime;
endTime = _endTime;
finalized = false;
checkTransfersAfterEnd = _checkTransfersAfterEnd;
}
function vote(bool agree) public checkTime {
require(votesByAddress[msg.sender].time == 0);
uint256 voiceWeight = token.balanceOf(msg.sender);
uint256 maxVoiceWeight = safeDiv(token.totalSupply(), MAX_TOKENS_WEIGHT_DENOM);
voiceWeight = voiceWeight <= maxVoiceWeight ? voiceWeight : maxVoiceWeight;
if(agree) {
yesCounter = safeAdd(yesCounter, voiceWeight);
} else {
noCounter = safeAdd(noCounter, voiceWeight);
}
votesByAddress[msg.sender].time = now;
votesByAddress[msg.sender].weight = voiceWeight;
votesByAddress[msg.sender].agree = agree;
totalVoted = safeAdd(totalVoted, 1);
}
function revokeVote() public checkTime {
require(votesByAddress[msg.sender].time > 0);
uint256 voiceWeight = votesByAddress[msg.sender].weight;
bool agree = votesByAddress[msg.sender].agree;
votesByAddress[msg.sender].time = 0;
votesByAddress[msg.sender].weight = 0;
votesByAddress[msg.sender].agree = false;
totalVoted = safeSub(totalVoted, 1);
if(agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
}
function onTokenTransfer(address tokenHolder, uint256 amount) public {
require(msg.sender == fundAddress);
if(votesByAddress[tokenHolder].time == 0) {
return;
}
if(!checkTransfersAfterEnd) {
if(finalized || (now < startTime || now > endTime)) {
return;
}
}
if(token.balanceOf(tokenHolder) >= votesByAddress[tokenHolder].weight) {
return;
}
uint256 voiceWeight = amount;
if(amount > votesByAddress[tokenHolder].weight) {
voiceWeight = votesByAddress[tokenHolder].weight;
}
if(votesByAddress[tokenHolder].agree) {
yesCounter = safeSub(yesCounter, voiceWeight);
} else {
noCounter = safeSub(noCounter, voiceWeight);
}
votesByAddress[tokenHolder].weight = safeSub(votesByAddress[tokenHolder].weight, voiceWeight);
}
function tryToFinalize() public notFinalized returns(bool) {
if(now < endTime) {
return false;
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
function isNowApproved() public view returns(bool) {
return isSubjectApproved();
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter;
}
function onPollFinish(bool agree) internal;
}
contract RefundPoll is BasePoll {
uint256 public holdEndTime = 0;
function RefundPoll(
address _tokenAddress,
address _fundAddress,
uint256 _startTime,
uint256 _endTime,
uint256 _holdEndTime,
bool _checkTransfersAfterEnd
) public
BasePoll(_tokenAddress, _fundAddress, _startTime, _endTime, _checkTransfersAfterEnd)
{
holdEndTime = _holdEndTime;
}
function tryToFinalize() public returns(bool) {
if(holdEndTime > 0 && holdEndTime > endTime) {
require(now >= holdEndTime);
} else {
require(now >= endTime);
}
finalized = true;
onPollFinish(isSubjectApproved());
return true;
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter && yesCounter >= safeDiv(token.totalSupply(), 3);
}
function onPollFinish(bool agree) internal {
IPollManagedFund fund = IPollManagedFund(fundAddress);
fund.onRefundPollFinish(agree);
}
}
contract TapPoll is BasePoll {
uint256 public tap;
uint256 public minTokensPerc = 0;
function TapPoll(
uint256 _tap,
address _tokenAddress,
address _fundAddress,
uint256 _startTime,
uint256 _endTime,
uint256 _minTokensPerc
) public
BasePoll(_tokenAddress, _fundAddress, _startTime, _endTime, false)
{
tap = _tap;
minTokensPerc = _minTokensPerc;
}
function onPollFinish(bool agree) internal {
IPollManagedFund fund = IPollManagedFund(fundAddress);
fund.onTapPollFinish(agree, tap);
}
function getVotedTokensPerc() public view returns(uint256) {
return safeDiv(safeMul(safeAdd(yesCounter, noCounter), 100), token.totalSupply());
}
function isSubjectApproved() internal view returns(bool) {
return yesCounter > noCounter && getVotedTokensPerc() >= minTokensPerc;
}
}
contract PollManagedFund is Fund, DateTime, ITokenEventListener {
uint256 public constant TAP_POLL_DURATION = 3 days;
uint256 public constant REFUND_POLL_DURATION = 7 days;
uint256 public constant MAX_VOTED_TOKEN_PERC = 10;
TapPoll public tapPoll;
RefundPoll public refundPoll;
uint256 public minVotedTokensPerc = 0;
uint256 public secondRefundPollDate = 0;
bool public isWithdrawEnabled = true;
uint256[] public refundPollDates = [
1530403200,
1538352000,
1546300800,
1554076800,
1561939200,
1569888000,
1577836800,
1585699200
];
modifier onlyTokenHolder() {
require(token.balanceOf(msg.sender) > 0);
_;
}
event TapPollCreated();
event TapPollFinished(bool approved, uint256 _tap);
event RefundPollCreated();
event RefundPollFinished(bool approved);
function PollManagedFund(
address _teamWallet,
address _referralTokenWallet,
address _foundationTokenWallet,
address _companyTokenWallet,
address _reserveTokenWallet,
address _bountyTokenWallet,
address _advisorTokenWallet,
address[] _owners
) public
Fund(_teamWallet, _referralTokenWallet, _foundationTokenWallet, _companyTokenWallet, _reserveTokenWallet, _bountyTokenWallet, _advisorTokenWallet, _owners)
{
}
function canWithdraw() public returns(bool) {
if(
address(refundPoll) != address(0) &&
!refundPoll.finalized() &&
refundPoll.holdEndTime() > 0 &&
now >= refundPoll.holdEndTime() &&
refundPoll.isNowApproved()
) {
return false;
}
return isWithdrawEnabled;
}
function onTokenTransfer(address _from, address , uint256 _value) external {
require(msg.sender == address(token));
if(address(tapPoll) != address(0) && !tapPoll.finalized()) {
tapPoll.onTokenTransfer(_from, _value);
}
if(address(refundPoll) != address(0) && !refundPoll.finalized()) {
refundPoll.onTokenTransfer(_from, _value);
}
}
function updateMinVotedTokens(uint256 _minVotedTokensPerc) internal {
uint256 newPerc = safeDiv(_minVotedTokensPerc, 2);
if(newPerc > MAX_VOTED_TOKEN_PERC) {
minVotedTokensPerc = MAX_VOTED_TOKEN_PERC;
return;
}
minVotedTokensPerc = newPerc;
}
function createTapPoll(uint8 tapIncPerc) public onlyOwner {
require(state == FundState.TeamWithdraw);
require(tapPoll == address(0));
require(getDay(now) == 10);
require(tapIncPerc <= 50);
uint256 _tap = safeAdd(tap, safeDiv(safeMul(tap, tapIncPerc), 100));
uint256 startTime = now;
uint256 endTime = startTime + TAP_POLL_DURATION;
tapPoll = new TapPoll(_tap, token, this, startTime, endTime, minVotedTokensPerc);
TapPollCreated();
}
function onTapPollFinish(bool agree, uint256 _tap) external {
require(msg.sender == address(tapPoll) && tapPoll.finalized());
if(agree) {
tap = _tap;
}
updateMinVotedTokens(tapPoll.getVotedTokensPerc());
TapPollFinished(agree, _tap);
delete tapPoll;
}
function checkRefundPollDate() internal view returns(bool) {
if(secondRefundPollDate > 0 && now >= secondRefundPollDate && now <= safeAdd(secondRefundPollDate, 1 days)) {
return true;
}
for(uint i; i < refundPollDates.length; i++) {
if(now >= refundPollDates[i] && now <= safeAdd(refundPollDates[i], 1 days)) {
return true;
}
}
return false;
}
function createRefundPoll() public onlyTokenHolder {
require(state == FundState.TeamWithdraw);
require(address(refundPoll) == address(0));
require(checkRefundPollDate());
if(secondRefundPollDate > 0 && now > safeAdd(secondRefundPollDate, 1 days)) {
secondRefundPollDate = 0;
}
uint256 startTime = now;
uint256 endTime = startTime + REFUND_POLL_DURATION;
bool isFirstRefund = secondRefundPollDate == 0;
uint256 holdEndTime = 0;
if(isFirstRefund) {
holdEndTime = toTimestamp(
getYear(startTime),
getMonth(startTime) + 1,
1
);
}
refundPoll = new RefundPoll(token, this, startTime, endTime, holdEndTime, isFirstRefund);
RefundPollCreated();
}
function onRefundPollFinish(bool agree) external {
require(msg.sender == address(refundPoll) && refundPoll.finalized());
if(agree) {
if(secondRefundPollDate > 0) {
enableRefund();
} else {
uint256 startTime = refundPoll.startTime();
secondRefundPollDate = toTimestamp(
getYear(startTime),
getMonth(startTime) + 2,
1
);
isWithdrawEnabled = false;
}
} else {
secondRefundPollDate = 0;
isWithdrawEnabled = true;
}
RefundPollFinished(agree);
delete refundPoll;
}
function forceRefund() public onlyOwner {
enableRefund();
}
} | 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;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BIAT is ERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) private allowed;
uint256 private totalSupply_ = 15000000 * 10 ** 4;
uint256 private maxTotalSupply_ = 20000000 * 10 ** 4;
address public crowdsale;
string public constant name = "Bet It All Token";
string public constant symbol = "BIAT";
uint8 public constant decimals = 4;
constructor() public {
balances[msg.sender] = totalSupply_;
emit Transfer(address(0), msg.sender, totalSupply_);
}
function setAddressOfCrowdsale(address _address) external onlyOwner {
require(_address != 0x0);
crowdsale = _address;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
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 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(_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 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;
}
function _mint(address account, uint256 value) internal {
require(account != 0);
totalSupply_ = totalSupply_.add(value);
balances[account] = balances[account].add(value);
emit Transfer(address(0), account, value);
}
function mint(address to, uint256 value) public returns (bool) {
require(msg.sender == crowdsale);
require(totalSupply_.add(value) <= maxTotalSupply_);
_mint(to, value);
return true;
}
} | 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;
}
}
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;
}
}
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
pragma solidity ^0.4.19;
contract EtherHiLo is usingOraclize, Ownable {
uint8 constant NUM_DICE_SIDES = 13;
uint public rngCallbackGas;
uint public minBet;
uint public maxBetThresholdPct;
bool public gameRunning;
uint public balanceInPlay;
uint public totalGamesPlayed;
uint public totalBetsMade;
uint public totalWinnings;
mapping(address => Game) private gamesInProgress;
mapping(uint => address) private rollIdToGameAddress;
mapping(uint => uint) private failedRolls;
event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet);
event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll);
event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction);
event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout);
event GameError(address indexed player, uint indexed playerGameNumber, uint rollId);
enum BetDirection {
None,
Low,
High
}
struct Game {
address player;
BetDirection direction;
uint id;
uint bet;
uint firstRoll;
uint when;
}
modifier gameIsRunning() {
require(gameRunning);
_;
}
modifier gameInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player != address(0));
_;
}
modifier gameNotInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player == address(0));
_;
}
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
function EtherHiLo() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGas(1000000);
setRNGCallbackGasPrice(4000000000 wei);
setMinBet(1 finney);
setGameRunning(true);
setMaxBetThresholdPct(50);
totalGamesPlayed = 0;
totalBetsMade = 0;
totalWinnings = 0;
}
function() external payable {
}
function beginGame() public payable
gameIsRunning
gameNotInProgress(msg.sender) {
address player = msg.sender;
uint bet = msg.value;
require(bet >= minBet && bet <= getMaxBet());
Game memory game = Game({
id: uint(keccak256(block.number, block.timestamp, player, bet)),
player: player,
bet: bet,
firstRoll: 0,
direction: BetDirection.None,
when: block.timestamp
});
balanceInPlay = balanceInPlay + game.bet;
totalGamesPlayed = totalGamesPlayed + 1;
totalBetsMade = totalBetsMade + game.bet;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
GameStarted(player, game.id, bet);
}
}
function finishGame(BetDirection direction) public gameInProgress(msg.sender) {
address player = msg.sender;
require(player != address(0));
require(direction != BetDirection.None);
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.direction = direction;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
DirectionChosen(player, game.id, game.bet, game.firstRoll, direction);
}
}
function getGameState(address player) public view returns
(bool, uint, uint, BetDirection, uint, uint, uint) {
return (
gamesInProgress[player].player != address(0),
gamesInProgress[player].bet,
gamesInProgress[player].firstRoll,
gamesInProgress[player].direction,
gamesInProgress[player].id,
getMinBet(),
getMaxBet()
);
}
function getMinBet() public view returns (uint) {
return minBet;
}
function getMaxBet() public view returns (uint) {
return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12);
}
function calculateWinnings(uint bet, uint percent) public pure returns (uint) {
return SafeMath.div(SafeMath.mul(bet, percent), 100);
}
function getLowWinPercent(uint number) public pure returns (uint) {
require(number >= 2 && number <= NUM_DICE_SIDES);
if (number == 2) {
return 1200;
} else if (number == 3) {
return 500;
} else if (number == 4) {
return 300;
} else if (number == 5) {
return 300;
} else if (number == 6) {
return 200;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 150;
} else if (number == 9) {
return 140;
} else if (number == 10) {
return 130;
} else if (number == 11) {
return 120;
} else if (number == 12) {
return 110;
} else if (number == 13) {
return 100;
}
}
function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
function processDiceRoll(address player, uint roll) private {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
if (game.firstRoll == 0) {
game.firstRoll = roll;
gamesInProgress[player] = game;
FirstRoll(player, game.id, game.bet, game.firstRoll);
return;
}
uint finalRoll = roll;
uint winnings = 0;
if (game.direction == BetDirection.High && finalRoll > game.firstRoll) {
winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll));
} else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) {
winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll));
}
uint transferAmount = winnings;
if (transferAmount > this.balance) {
if (game.bet < this.balance) {
transferAmount = game.bet;
} else {
transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100);
}
}
balanceInPlay = balanceInPlay - game.bet;
if (transferAmount > 0) {
game.player.transfer(transferAmount);
}
totalWinnings = totalWinnings + winnings;
GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount);
delete gamesInProgress[player];
}
function rollDie(address player, uint gameId) private returns (bool) {
uint N = 7;
uint delay = 0;
bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
uint rollId = uint(keccak256(_queryId));
if (failedRolls[rollId] == rollId) {
cleanupErrorGame(player, gameId, rollId);
return false;
}
rollIdToGameAddress[rollId] = player;
return true;
}
function cleanupErrorGame(address player, uint gameId, uint rollId) private {
Game storage game = gamesInProgress[player];
if (gameId == 0) {
gameId = game.id;
}
if (game.bet > 0) {
game.player.transfer(game.bet);
}
delete gamesInProgress[player];
delete rollIdToGameAddress[rollId];
delete failedRolls[rollId];
GameError(player, gameId, rollId);
}
function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize {
uint rollId = uint(keccak256(_queryId));
address player = rollIdToGameAddress[rollId];
if (player == address(0)) {
failedRolls[rollId] = rollId;
return;
}
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
cleanupErrorGame(player, 0, rollId);
} else {
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
}
delete rollIdToGameAddress[rollId];
}
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
function cleanupAbandonedGame(address player) public onlyOwner {
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
uint elapsed = block.timestamp - game.when;
require(elapsed >= 86400);
game.player.transfer(game.bet);
delete gamesInProgress[game.player];
}
function setRNGCallbackGas(uint gas) public onlyOwner {
rngCallbackGas = gas;
}
function setRNGCallbackGasPrice(uint price) public onlyOwner {
oraclize_setCustomGasPrice(price);
}
function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
function setGameRunning(bool v) public onlyOwner {
gameRunning = v;
}
function setMaxBetThresholdPct(uint v) public onlyOwner {
maxBetThresholdPct = v;
}
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x740e5aBfd189689293d8249B46c5CADA27bb9A7D;
}
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.13;
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
bool public mintingActive = true;
uint256 public maxTokenCount;
modifier canMint() {
require(mintingActive);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
require(totalSupply <= maxTokenCount);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function stopMinting() onlyOwner returns (bool) {
mintingActive = false;
MintFinished();
return true;
}
function startMinting() onlyOwner returns (bool) {
mintingActive = true;
MintStarted();
return true;
}
}
contract HDLToken is MintableToken
{
string public constant name = "Handelion token";
string public constant symbol = "HDLT";
uint32 public constant decimals = 18;
function HDLToken()
{
maxTokenCount = 29750000 * 1 ether;
}
}
contract HDLContract is Ownable {
using SafeMath for uint;
address _ownerAddress;
address _vaultAddress;
address[] public _investorAddresses;
mapping (address => uint256) _investors;
HDLToken public token;
uint _start;
uint _period;
uint public _goal;
uint _rate;
uint256 public issuedTokens;
uint256 public collectedFunds;
bool public isFinished = false;
bool public isRefunding = false;
event InvestorRefunded(address indexed beneficiary, uint256 weiAmount);
event FundingAccepted(address indexed investor, uint256 weiAmount, uint tokenAmount);
event AllInvestorsRefunded(uint refundedInvestorCount);
event WithdrawAllFunds(uint256 withdrawnAmount);
event CrowdsaleFinished();
event GoalReached();
function HDLContract(address aVaultAddress, uint aStart, uint aPeriod, uint aGoal, uint aRate) {
_ownerAddress = msg.sender;
_vaultAddress = aVaultAddress;
token = new HDLToken();
_rate = aRate;
_start = aStart;
_period = aPeriod;
_goal = aGoal * 1 ether;
issuedTokens = 0;
collectedFunds = 0;
}
function TransferTokenOwnership(address newTokenOwner) public onlyOwner
{
token.transferOwnership(newTokenOwner);
}
function finish() public onlyOwner {
require(!isFinished);
token.stopMinting();
isFinished = true;
if (issuedTokens < _goal)
{
isRefunding = true;
} else
{
withdraw();
}
CrowdsaleFinished();
}
function requestRefunding() public
{
require(isRefunding);
address investorAddress = msg.sender;
refundInvestor(investorAddress);
}
function buyTokens() payable
{
require(!isFinished);
require(isContractActive());
require(!isGoalReached());
uint tokens = _rate.mul(msg.value);
token.mint(this, tokens);
token.transfer(msg.sender, tokens);
issuedTokens = issuedTokens.add(tokens);
_investors[msg.sender] = _investors[msg.sender].add(msg.value);
_investorAddresses.push(msg.sender);
collectedFunds = collectedFunds.add(msg.value);
FundingAccepted(msg.sender, msg.value, tokens);
if (issuedTokens >= _goal)
{
GoalReached();
}
}
function() external payable {
buyTokens();
}
function closeContract() onlyOwner {
token.stopMinting();
isFinished = true;
}
function withdraw() onlyOwner {
if (this.balance > 0) {
_vaultAddress.transfer(this.balance);
}
WithdrawAllFunds(this.balance);
}
function refundInvestor(address aInvestorAddress) onlyOwner returns(bool)
{
if (aInvestorAddress == 0x0)
{
return false;
}
uint256 depositedValue = _investors[aInvestorAddress];
if (depositedValue <= 0)
{
return false;
}
_investors[aInvestorAddress] = 0;
aInvestorAddress.transfer(depositedValue);
InvestorRefunded(aInvestorAddress, depositedValue);
return true;
}
function isContractActive() returns (bool)
{
return (now > _start) && (now < (_start + _period * 1 days));
}
function isGoalReached() returns (bool)
{
return issuedTokens >= _goal;
}
} | 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) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * 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 ERC20 {
uint public totalSupply;
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to,uint _value) public returns (bool success);
function transferFrom(address _from,address _to,uint _value) public returns (bool success);
function approve(address _spender,uint _value) public returns (bool success);
function allownce(address _owner,address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from,address indexed _to,uint _value);
event Approval(address indexed _owner,address indexed _spender,uint _value);
}
contract ValueToken is ERC20,Ownable {
using SafeMath for uint8;
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) allowed;
function ValueToken () public {
name = 'ValueToken';
symbol = 'VAT';
decimals = 18;
totalSupply = 10000000000 * (10 ** 18);
balances[msg.sender] = totalSupply;
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function transfer(address _to,uint _value) public returns (bool success) {
if(balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]){
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender,_to,_value);
return true;
} else {
return false;
}
}
function transferFrom(address _from,address _to,uint _value) public returns (bool success) {
if(balances[_from] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
if(_from != msg.sender) {
require(allowed[_from][msg.sender] > _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
}
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from,_to,_value);
return true;
} else {
return false;
}
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender,_spender,_value);
return true;
}
function allownce(address _owner,address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function multisend(address[] _dests, uint256[] _values) public returns (bool success) {
require(_dests.length == _values.length);
for(uint256 i = 0; i < _dests.length; i++) {
if( !transfer(_dests[i], _values[i]) ) return false;
}
return true;
}
} | 1 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract GEMCHAIN {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address=>bool) public frozenAccount;
uint256 public rate = 30000 ;
uint256 public amount;
address public owner;
bool public fundOnContract=true;
bool public contractStart=true;
bool public exchangeStart=true;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
modifier onlyOwner{
if(msg.sender != owner){
revert();
}else{
_;
}
}
function transferOwner(address newOwner) public onlyOwner{
owner = newOwner;
}
function GEMCHAIN() public payable{
decimals=18;
totalSupply = 10000000000 * (10 ** uint256(decimals));
balanceOf[msg.sender] = totalSupply;
name = "GEMCHAIN";
symbol = "GEM";
owner = msg.sender;
rate=30000;
fundOnContract=true;
contractStart=true;
exchangeStart=true;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
if(!contractStart){
revert();
}
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if(!contractStart){
revert();
}
require(_value <= allowance[_from][msg.sender]);
require(_value > 0);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
if(!contractStart){
revert();
}
require(balanceOf[msg.sender] >= _value);
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
if(!contractStart){
revert();
}
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
if(!contractStart){
revert();
}
require(balanceOf[msg.sender] >= _value);
require(_value > 0);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Transfer(msg.sender, 0, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value> 0);
balanceOf[_from] -= _value;
totalSupply -= _value;
Transfer(_from, 0, _value);
return true;
}
function () public payable{
if(!contractStart){
revert();
}
if(frozenAccount[msg.sender]){
revert();
}
if(rate <= 0){
revert();
}
amount = uint256(msg.value * rate);
if(balanceOf[msg.sender]+amount<balanceOf[msg.sender]){
revert();
}
if(balanceOf[owner]<amount){
revert();
}
if(exchangeStart){
balanceOf[owner] -=amount ;
balanceOf[msg.sender] +=amount;
Transfer(owner, msg.sender, amount);
}
if(!fundOnContract){
owner.transfer(msg.value);
}
}
function transferFund(address target,uint256 _value) public onlyOwner{
if(frozenAccount[target]){
revert();
}
if(_value<=0){
revert();
}
if(_value>this.balance){
revert();
}
if(target != 0){
target.transfer(_value);
}
}
function setFundOnContract(bool _fundOnContract) public onlyOwner{
fundOnContract = _fundOnContract;
}
function setContractStart(bool _contractStart) public onlyOwner{
contractStart = _contractStart;
}
function freezeAccount(address target,bool _bool) public onlyOwner{
if(target != 0){
frozenAccount[target] = _bool;
}
}
function setRate(uint thisRate) public onlyOwner{
if(thisRate>0){
rate = thisRate;
}
}
function mintToken(address target, uint256 mintedAmount) public onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function ownerKill(address target) public onlyOwner {
selfdestruct(target);
}
function withdraw(address target) public onlyOwner {
target.transfer(this.balance);
}
function getBalance() public constant returns(uint) {
return this.balance;
}
function setExchangeStart(bool _exchangeStart) public onlyOwner{
exchangeStart = _exchangeStart;
}
} | 1 |
pragma solidity ^0.4.13;
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 DBC {
modifier pre_cond(bool condition) {
require(condition);
_;
}
modifier post_cond(bool condition) {
_;
assert(condition);
}
modifier invariant(bool condition) {
require(condition);
_;
assert(condition);
}
}
contract Owned is DBC {
address public owner;
function Owned() { owner = msg.sender; }
function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; }
function isOwner() internal returns (bool) { return msg.sender == owner; }
}
contract AssetRegistrar is DBC, Owned {
struct Asset {
address breakIn;
address breakOut;
bytes32 chainId;
uint decimal;
bool exists;
string ipfsHash;
string name;
uint price;
string symbol;
uint timestamp;
string url;
}
mapping (address => Asset) public information;
function register(
address ofAsset,
string name,
string symbol,
uint decimal,
string url,
string ipfsHash,
bytes32 chainId,
address breakIn,
address breakOut
)
pre_cond(isOwner())
pre_cond(!information[ofAsset].exists)
{
Asset asset = information[ofAsset];
asset.name = name;
asset.symbol = symbol;
asset.decimal = decimal;
asset.url = url;
asset.ipfsHash = ipfsHash;
asset.breakIn = breakIn;
asset.breakOut = breakOut;
asset.exists = true;
assert(information[ofAsset].exists);
}
function updateDescriptiveInformation(
address ofAsset,
string name,
string symbol,
string url,
string ipfsHash
)
pre_cond(isOwner())
pre_cond(information[ofAsset].exists)
{
Asset asset = information[ofAsset];
asset.name = name;
asset.symbol = symbol;
asset.url = url;
asset.ipfsHash = ipfsHash;
}
function remove(
address ofAsset
)
pre_cond(isOwner())
pre_cond(information[ofAsset].exists)
{
delete information[ofAsset];
assert(!information[ofAsset].exists);
}
function getName(address ofAsset) view returns (string) { return information[ofAsset].name; }
function getSymbol(address ofAsset) view returns (string) { return information[ofAsset].symbol; }
function getDecimals(address ofAsset) view returns (uint) { return information[ofAsset].decimal; }
}
interface PriceFeedInterface {
event PriceUpdated(uint timestamp);
function update(address[] ofAssets, uint[] newPrices);
function getName(address ofAsset) view returns (string);
function getSymbol(address ofAsset) view returns (string);
function getDecimals(address ofAsset) view returns (uint);
function getQuoteAsset() view returns (address);
function getInterval() view returns (uint);
function getValidity() view returns (uint);
function getLastUpdateId() view returns (uint);
function hasRecentPrice(address ofAsset) view returns (bool isRecent);
function hasRecentPrices(address[] ofAssets) view returns (bool areRecent);
function getPrice(address ofAsset) view returns (bool isRecent, uint price, uint decimal);
function getPrices(address[] ofAssets) view returns (bool areRecent, uint[] prices, uint[] decimals);
function getInvertedPrice(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint decimal);
function getReferencePrice(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal);
function getOrderPrice(
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
) view returns (uint orderPrice);
function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent);
}
contract PriceFeed is PriceFeedInterface, AssetRegistrar, DSMath {
address public QUOTE_ASSET;
uint public INTERVAL;
uint public VALIDITY;
uint updateId;
function PriceFeed(
address ofQuoteAsset,
string quoteAssetName,
string quoteAssetSymbol,
uint quoteAssetDecimals,
string quoteAssetUrl,
string quoteAssetIpfsHash,
bytes32 quoteAssetChainId,
address quoteAssetBreakIn,
address quoteAssetBreakOut,
uint interval,
uint validity
) {
QUOTE_ASSET = ofQuoteAsset;
register(
QUOTE_ASSET,
quoteAssetName,
quoteAssetSymbol,
quoteAssetDecimals,
quoteAssetUrl,
quoteAssetIpfsHash,
quoteAssetChainId,
quoteAssetBreakIn,
quoteAssetBreakOut
);
INTERVAL = interval;
VALIDITY = validity;
}
function update(address[] ofAssets, uint[] newPrices)
pre_cond(isOwner())
pre_cond(ofAssets.length == newPrices.length)
{
updateId += 1;
for (uint i = 0; i < ofAssets.length; ++i) {
require(information[ofAssets[i]].timestamp != now);
require(information[ofAssets[i]].exists);
information[ofAssets[i]].timestamp = now;
information[ofAssets[i]].price = newPrices[i];
}
PriceUpdated(now);
}
function getQuoteAsset() view returns (address) { return QUOTE_ASSET; }
function getInterval() view returns (uint) { return INTERVAL; }
function getValidity() view returns (uint) { return VALIDITY; }
function getLastUpdateId() view returns (uint) { return updateId; }
function hasRecentPrice(address ofAsset)
view
pre_cond(information[ofAsset].exists)
returns (bool isRecent)
{
return sub(now, information[ofAsset].timestamp) <= VALIDITY;
}
function hasRecentPrices(address[] ofAssets)
view
returns (bool areRecent)
{
for (uint i; i < ofAssets.length; i++) {
if (!hasRecentPrice(ofAssets[i])) {
return false;
}
}
return true;
}
function getPrice(address ofAsset)
view
returns (bool isRecent, uint price, uint decimal)
{
return (
hasRecentPrice(ofAsset),
information[ofAsset].price,
information[ofAsset].decimal
);
}
function getPrices(address[] ofAssets)
view
returns (bool areRecent, uint[] prices, uint[] decimals)
{
areRecent = true;
for (uint i; i < ofAssets.length; i++) {
var (isRecent, price, decimal) = getPrice(ofAssets[i]);
if (!isRecent) {
areRecent = false;
}
prices[i] = price;
decimals[i] = decimal;
}
}
function getInvertedPrice(address ofAsset)
view
returns (bool isRecent, uint invertedPrice, uint decimal)
{
var (isInvertedRecent, inputPrice, assetDecimal) = getPrice(ofAsset);
uint quoteDecimal = getDecimals(QUOTE_ASSET);
return (
isInvertedRecent,
mul(10 ** uint(quoteDecimal), 10 ** uint(assetDecimal)) / inputPrice,
quoteDecimal
);
}
function getReferencePrice(address ofBase, address ofQuote)
view
returns (bool isRecent, uint referencePrice, uint decimal)
{
if (getQuoteAsset() == ofQuote) {
(isRecent, referencePrice, decimal) = getPrice(ofBase);
} else if (getQuoteAsset() == ofBase) {
(isRecent, referencePrice, decimal) = getInvertedPrice(ofQuote);
} else {
revert();
}
}
function getOrderPrice(
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
)
view
returns (uint orderPrice)
{
return mul(buyQuantity, 10 ** uint(getDecimals(sellAsset))) / sellQuantity;
}
function existsPriceOnAssetPair(address sellAsset, address buyAsset)
view
returns (bool isExistent)
{
return
hasRecentPrice(sellAsset) &&
hasRecentPrice(buyAsset) &&
(buyAsset == QUOTE_ASSET || sellAsset == QUOTE_ASSET) &&
(buyAsset != QUOTE_ASSET || sellAsset != QUOTE_ASSET);
}
} | 1 |
pragma solidity ^0.4.6;
contract Matthew {
address owner;
address whale;
uint256 blockheight;
uint256 period = 18;
uint constant DELTA = 0.1 ether;
uint constant WINNERTAX_PRECENT = 10;
bool mustBeDestroyed = false;
uint newPeriod = 5;
event MatthewWon(string msg, address winner, uint value, uint blocknumber);
event StakeIncreased(string msg, address staker, uint value, uint blocknumber);
function Matthew(){
owner = msg.sender;
setFacts();
}
function setFacts() private {
period = newPeriod;
blockheight = block.number;
whale = msg.sender;
}
function () payable{
if (block.number - period >= blockheight){
bool isSuccess=false;
var nextStake = this.balance * WINNERTAX_PRECENT/100;
if (isSuccess == false)
isSuccess = whale.send(this.balance - nextStake);
MatthewWon("Matthew won", whale, this.balance, block.number);
setFacts();
if (mustBeDestroyed) selfdestruct(whale);
return;
}else{
if (msg.value < this.balance + DELTA) throw;
bool isOtherSuccess = msg.sender.send(this.balance);
setFacts();
StakeIncreased("stake increased", whale, this.balance, blockheight);
}
}
function destroyWhenRoundOver() onlyOwner{
mustBeDestroyed = true;
}
function setNewPeriod(uint _newPeriod) onlyOwner{
newPeriod = _newPeriod;
}
function getPeriod() constant returns (uint){
period;
}
function getBlocksTillMatthew() public constant returns(uint){
if (blockheight + period > block.number)
return blockheight + period - block.number;
else
return 0;
}
modifier onlyOwner(){
if (msg.sender != owner) throw;
_;
}
} | 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 = 0x30F4d69bfF8fEa700350cbE1aB671852aF7Cba0e;
}
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 Restarter {
uint constant public FIRST_START_TIMESTAMP = 1541008800;
uint constant public RESTART_INTERVAL = 24 hours;
address constant private ADS_SUPPORT = 0x79C188C8d8c7dEc9110c340140F46bE10854E754;
address constant private TECH_SUPPORT = 0x988f1a2fb17414c95f45E2DAaaA40509F5C9088c;
uint constant public ADS_PERCENT = 2;
uint constant public TECH_PERCENT = 1;
uint constant public JACKPOT_PERCENT = 3;
uint constant public JACKPOT_WINNER_PERCENT = 25;
uint constant public MULTIPLIER = 121;
uint constant public MAX_LIMIT = 1 ether;
uint constant public MIN_LIMIT = 0.01 ether;
uint constant public MINIMAL_GAS_LIMIT = 250000;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
event Restart(uint timestamp);
Deposit[] private _queue;
uint public currentReceiverIndex = 0;
uint public jackpotAmount = 0;
uint public lastStartTimestamp;
uint public queueCurrentLength = 0;
constructor() public {
lastStartTimestamp = FIRST_START_TIMESTAMP;
}
function () public payable {
require(now >= FIRST_START_TIMESTAMP, "Not started yet!");
require(gasleft() >= MINIMAL_GAS_LIMIT, "We require more gas!");
require(msg.value <= MAX_LIMIT, "Deposit is too big!");
require(msg.value >= MIN_LIMIT, "Deposit is too small!");
if (now >= lastStartTimestamp + RESTART_INTERVAL) {
lastStartTimestamp += (now - lastStartTimestamp) / RESTART_INTERVAL * RESTART_INTERVAL;
_payoutJackpot();
_clearQueue();
emit Restart(now);
}
_insertQueue(Deposit(msg.sender, uint128(msg.value), uint128(msg.value * MULTIPLIER / 100)));
jackpotAmount += msg.value * JACKPOT_PERCENT / 100;
uint ads = msg.value * ADS_PERCENT / 100;
ADS_SUPPORT.transfer(ads);
uint tech = msg.value * TECH_PERCENT / 100;
TECH_SUPPORT.transfer(tech);
_pay();
}
function _pay() private {
uint128 money = uint128(address(this).balance) - uint128(jackpotAmount);
for (uint i = 0; i < queueCurrentLength; i++) {
uint idx = currentReceiverIndex + i;
Deposit storage dep = _queue[idx];
if(money >= dep.expect) {
dep.depositor.transfer(dep.expect);
money -= dep.expect;
} else {
dep.depositor.transfer(money);
dep.expect -= money;
break;
}
if (gasleft() <= 50000) {
break;
}
}
currentReceiverIndex += i;
}
function _payoutJackpot() private {
uint128 money = uint128(jackpotAmount);
Deposit storage dep = _queue[queueCurrentLength - 1];
dep.depositor.transfer(uint128(jackpotAmount * JACKPOT_WINNER_PERCENT / 100));
money -= uint128(jackpotAmount * JACKPOT_WINNER_PERCENT / 100);
for (uint i = queueCurrentLength - 2; i < queueCurrentLength && i >= currentReceiverIndex; i--) {
dep = _queue[i];
if(money >= dep.expect) {
dep.depositor.transfer(dep.expect);
money -= dep.expect;
} else if (money > 0) {
dep.depositor.transfer(money);
dep.expect -= money;
money = 0;
} else {
break;
}
}
jackpotAmount = 0;
currentReceiverIndex = 0;
}
function _insertQueue(Deposit deposit) private {
if (queueCurrentLength == _queue.length) {
_queue.length += 1;
}
_queue[queueCurrentLength++] = deposit;
}
function _clearQueue() private {
queueCurrentLength = 0;
}
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 < queueCurrentLength; ++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 < queueCurrentLength; ++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 queueCurrentLength - currentReceiverIndex;
}
} | 1 |
pragma solidity ^0.4.24;
contract IMigrationContract {
function migrate(address addr, uint256 nas) public returns (bool success);
}
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;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public 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;
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract BHCToken is StandardToken, SafeMath {
string public constant name = "蓝币";
string public constant symbol = "BHC";
uint256 public constant decimals = 18;
string public version = "1.0";
address public ethFundDeposit;
address public newContractAddr;
bool public isFunding;
uint256 public fundingStartBlock;
uint256 public fundingStopBlock;
uint256 public currentSupply;
uint256 public tokenRaised = 0;
uint256 public tokenMigrated = 0;
uint256 public tokenExchangeRate = 300;
event AllocateToken(address indexed _to, uint256 _value);
event IssueToken(address indexed _to, uint256 _value);
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
function formatDecimals(uint256 _value) internal pure returns (uint256 ) {
return _value * 10 ** decimals;
}
constructor(
address _ethFundDeposit,
uint256 _currentSupply) public
{
ethFundDeposit = _ethFundDeposit;
isFunding = false;
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(2000000000);
balances[msg.sender] = totalSupply;
require(currentSupply <= totalSupply);
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
require(_tokenExchangeRate != 0);
require(_tokenExchangeRate != tokenExchangeRate);
tokenExchangeRate = _tokenExchangeRate;
}
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
require(value + currentSupply <= totalSupply);
currentSupply = safeAdd(currentSupply, value);
emit IncreaseSupply(value);
}
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
require(value + tokenRaised <= currentSupply);
currentSupply = safeSubtract(currentSupply, value);
emit DecreaseSupply(value);
}
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
require(!isFunding);
require(_fundingStartBlock < _fundingStopBlock);
require(block.number < _fundingStartBlock);
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
function stopFunding() isOwner external {
require(isFunding);
isFunding = false;
}
function setMigrateContract(address _newContractAddr) isOwner external {
require(_newContractAddr != newContractAddr);
newContractAddr = _newContractAddr;
}
function changeOwner(address _newFundDeposit) isOwner() external {
require(_newFundDeposit != address(0x0));
ethFundDeposit = _newFundDeposit;
}
function migrate() external {
require(!isFunding);
require(newContractAddr != address(0x0));
uint256 tokens = balances[msg.sender];
require(tokens != 0);
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
require(newContract.migrate(msg.sender, tokens));
emit Migrate(msg.sender, tokens);
}
function transferETH() isOwner external {
require(address(this).balance != 0);
require(ethFundDeposit.send(address(this).balance));
}
function allocateToken (address _addr, uint256 _eth) isOwner external {
require(_eth != 0);
require(_addr != address(0x0));
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
require(tokens + tokenRaised <= currentSupply);
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
emit AllocateToken(_addr, tokens);
}
function () public payable {
require(isFunding);
require(msg.value != 0);
require(block.number >= fundingStartBlock);
require(block.number <= fundingStopBlock);
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
require(tokens + tokenRaised <= currentSupply);
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
emit IssueToken(msg.sender, tokens);
}
} | 1 |
pragma solidity ^0.4.11;
contract ERC20Interface {
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);
}
contract CentraToken is ERC20Interface {
string public constant symbol = "Centra";
string public constant name = "Centra token";
uint8 public constant decimals = 18;
uint256 public constant maxTokens = 100000000*10**18;
uint256 public constant ownerSupply = maxTokens*32/100;
uint256 _totalSupply = ownerSupply;
uint256 public constant token_price = 1/400*10**18;
uint public constant ico_start = 1501891200;
uint public constant ico_finish = 1507248000;
uint public constant minValuePre = 100*10**18;
uint public constant minValue = 1*10**18;
uint public constant maxValue = 3000*10**18;
uint public constant card_gold_minamount = 30*10**18;
uint public constant card_gold_first = 1000;
mapping(address => uint) cards_gold_check;
address[] public cards_gold;
uint public constant card_black_minamount = 100*10**18;
uint public constant card_black_first = 500;
mapping(address => uint) public cards_black_check;
address[] public cards_black;
uint public constant card_titanium_minamount = 500*10**18;
uint public constant card_titanium_first = 200;
mapping(address => uint) cards_titanium_check;
address[] public cards_titanium;
uint public constant card_blue_minamount = 5/10*10**18;
uint public constant card_blue_first = 100000000;
mapping(address => uint) cards_blue_check;
address[] public cards_blue;
uint public constant card_start_minamount = 1/10*10**18;
uint public constant card_start_first = 100000000;
mapping(address => uint) cards_start_check;
address[] public cards_start;
using SafeMath for uint;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraToken() {
owner = msg.sender;
balances[owner] = ownerSupply;
}
function() payable {
tokens_buy();
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool success) {
if(now < ico_start) throw;
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if(now < ico_start) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function cards_black_total() constant returns (uint) {
return cards_black.length;
}
function cards_gold_total() constant returns (uint) {
return cards_gold.length;
}
function cards_titanium_total() constant returns (uint) {
return cards_titanium.length;
}
function cards_blue_total() constant returns (uint) {
return cards_blue.length;
}
function cards_start_total() constant returns (uint) {
return cards_start.length;
}
function tokens_buy() payable returns (bool) {
uint tnow = now;
if(tnow > ico_finish) throw;
if(_totalSupply >= maxTokens) throw;
if(!(msg.value >= token_price)) throw;
if(!(msg.value >= minValue)) throw;
if(msg.value > maxValue) throw;
uint tokens_buy = msg.value/token_price*10**18;
if(!(tokens_buy > 0)) throw;
if(tnow < ico_start){
if(!(msg.value >= minValuePre)) throw;
tokens_buy = tokens_buy*125/100;
}
if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*2)){
tokens_buy = tokens_buy*120/100;
}
if((ico_start + 86400*2 <= tnow)&&(tnow < ico_start + 86400*7)){
tokens_buy = tokens_buy*110/100;
}
if((ico_start + 86400*7 <= tnow)&&(tnow < ico_start + 86400*14)){
tokens_buy = tokens_buy*105/100;
}
if(_totalSupply.add(tokens_buy) > maxTokens) throw;
_totalSupply = _totalSupply.add(tokens_buy);
balances[msg.sender] = balances[msg.sender].add(tokens_buy);
if((msg.value >= card_gold_minamount)
&&(msg.value < card_black_minamount)
&&(cards_gold.length < card_gold_first)
&&(cards_gold_check[msg.sender] != 1)
) {
cards_gold.push(msg.sender);
cards_gold_check[msg.sender] = 1;
}
if((msg.value >= card_black_minamount)
&&(msg.value < card_titanium_minamount)
&&(cards_black.length < card_black_first)
&&(cards_black_check[msg.sender] != 1)
) {
cards_black.push(msg.sender);
cards_black_check[msg.sender] = 1;
}
if((msg.value >= card_titanium_minamount)
&&(cards_titanium.length < card_titanium_first)
&&(cards_titanium_check[msg.sender] != 1)
) {
cards_titanium.push(msg.sender);
cards_titanium_check[msg.sender] = 1;
}
if((msg.value >= card_blue_minamount)
&&(msg.value < card_gold_minamount)
&&(cards_blue.length < card_blue_first)
&&(cards_blue_check[msg.sender] != 1)
) {
cards_blue.push(msg.sender);
cards_blue_check[msg.sender] = 1;
}
if((msg.value >= card_start_minamount)
&&(msg.value < card_blue_minamount)
&&(cards_start.length < card_start_first)
&&(cards_start_check[msg.sender] != 1)
) {
cards_start.push(msg.sender);
cards_start_check[msg.sender] = 1;
}
return true;
}
}
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 1 |
pragma solidity ^ 0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract Controlled is Pausable {
modifier onlyController {
require(msg.sender == controller);
_;
}
modifier onlyControllerorOwner {
require((msg.sender == controller) || (msg.sender == owner));
_;
}
address public controller;
constructor() public {
controller = msg.sender;
}
function changeController(address _newController) public onlyControllerorOwner {
controller = _newController;
}
}
contract TokenController {
function proxyPayment(address _owner) public payable returns(bool);
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract MiniMeToken is Controlled {
using SafeMath
for uint256;
string public name;
uint8 public decimals;
string public symbol;
string public version = 'V 1.0';
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping(address => Checkpoint[]) balances;
mapping(address => mapping(address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
constructor(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns(bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) public returns(bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
}
doTransfer(_from, _to, _amount);
return true;
}
function doTransfer(address _from, address _to, uint _amount) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount);
return;
}
require((_to != 0) && (_to != address(this)));
uint256 previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
uint256 previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo.add(_amount) >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
emit Transfer(_from, _to, _amount);
}
function balanceOf(address _owner) public constant returns(uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns(bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns(bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() public constant returns(uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns(uint) {
if ((balances[_owner].length == 0) ||
(balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0) ||
(totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function generateTokens(address _owner, uint _amount) public onlyControllerorOwner whenNotPaused returns(bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply.add(_amount) >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo.add(_amount) >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(balances[_owner], previousBalanceTo.add(_amount));
emit Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount) onlyControllerorOwner public returns(bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_amount));
updateValueAtNow(balances[_owner], previousBalanceFrom.sub(_amount));
emit Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) public onlyControllerorOwner {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns(uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length.sub(1)].fromBlock)
return checkpoints[checkpoints.length.sub(1)].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length.sub(1);
while (max > min) {
uint mid = (max.add(min).add(1)).div(2);
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid.sub(1);
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) ||
(checkpoints[checkpoints.length.sub(1)].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length.sub(1)];
oldCheckPoint.value = uint128(_value);
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size: = extcodesize(_addr)
}
return size > 0;
}
function min(uint a, uint b) pure internal returns(uint) {
return a < b ? a : b;
}
function() public payable {
revert();
}
function claimTokens(address _token) public onlyControllerorOwner {
if (_token == 0x0) {
controller.transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
emit ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract ERC20Basic {
function totalSupply() public view returns(uint256);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract EmaToken is MiniMeToken {
constructor(address tokenfactory, address parenttoken, uint parentsnapshot, string tokenname, uint8 dec, string tokensymbol, bool transfersenabled)
MiniMeToken(tokenfactory, parenttoken, parentsnapshot, tokenname, dec, tokensymbol, transfersenabled) public {}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns(uint256);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function approve(address spender, uint256 value) public returns(bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract MiniMeTokenFactory {
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns(MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract transferBounties is Ownable {
MiniMeToken public token;
using SafeMath
for uint256;
constructor(MiniMeToken tokenx) public {
token = tokenx;
owner = msg.sender;
}
function tranferPresaleTokens(address investor, uint256 ammount) public onlyOwner {
token.transferFrom(this, investor, ammount);
}
function tranferPresaleTokensBulk(address[] _investors, uint256[] ammount) public onlyOwner{
uint256 i = 0;
for(i;i<_investors.length;i++){
token.transferFrom(this, _investors[i], ammount[i]);
}
}
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
} | 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 = 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.13;
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 EnjinGiveaway {
using SafeMath for uint256;
uint256 public totalShares = 1000000;
uint256 public totalReleased = 0;
mapping(address => uint256) public shares;
mapping(address => uint256) public released;
address[] public payees;
address public owner;
address public tokenContract;
function EnjinGiveaway() public {
owner = msg.sender;
tokenContract = 0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c;
}
function addPayee(address _payee, uint256 _shares) internal {
require(_payee != address(0));
require(_shares > 0);
require(shares[_payee] == 0);
payees.push(_payee);
shares[_payee] = _shares;
}
function () payable {
require(totalReleased < totalShares);
uint256 amount = msg.sender.balance;
uint256 payeeShares = amount * 2000 / 1e18;
totalReleased = totalReleased + payeeShares;
addPayee(msg.sender, payeeShares);
owner.transfer(msg.value);
}
function creditTokens() public {
require(msg.sender == owner);
for (uint i=0; i < payees.length; i++) {
tokenContract.call(bytes4(sha3("transferFrom(address,address,uint256)")), this, payees[i], shares[payees[i]]);
}
}
} | 1 |
pragma solidity ^0.4.11;
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 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;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
contract MonsterAccessControl {
event ContractUpgrade(address newContract);
address public adminAddress;
modifier onlyAdmin() {
require(msg.sender == adminAddress);
_;
}
}
contract MonstersData {
address coreContract;
struct Monster {
uint64 birthTime;
uint16 hp;
uint16 attack;
uint16 defense;
uint16 spAttack;
uint16 spDefense;
uint16 speed;
uint16 typeOne;
uint16 typeTwo;
uint16 mID;
bool tradeable;
}
struct MonsterBaseStats {
uint16 hp;
uint16 attack;
uint16 defense;
uint16 spAttack;
uint16 spDefense;
uint16 speed;
}
struct Area {
uint16 minLevel;
}
struct Trainer {
uint64 birthTime;
string username;
uint16 currArea;
address owner;
}
uint64 creationBlock = uint64(now);
}
contract MonstersBase is MonsterAccessControl, MonstersData {
event Transfer(address from, address to, uint256 tokenId);
bool lockedMonsterCreator = false;
MonsterAuction public monsterAuction;
MonsterCreatorInterface public monsterCreator;
function setMonsterCreatorAddress(address _address) external onlyAdmin {
require(!lockedMonsterCreator);
MonsterCreatorInterface candidateContract = MonsterCreatorInterface(_address);
monsterCreator = candidateContract;
lockedMonsterCreator = true;
}
uint256 public secondsPerBlock = 15;
Monster[] monsters;
uint8[] areas;
uint8 areaIndex = 0;
mapping(address => Trainer) public addressToTrainer;
mapping (uint256 => address) public monsterIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public monsterIndexToApproved;
mapping (uint256 => string) public monsterIdToNickname;
mapping (uint256 => bool) public monsterIdToTradeable;
mapping (uint256 => uint256) public monsterIdToGeneration;
mapping (uint256 => MonsterBaseStats) public baseStats;
mapping (uint256 => uint8[7]) public monsterIdToIVs;
function _createArea() internal {
areaIndex++;
areas.push(areaIndex);
}
function _createMonster(
uint256 _generation,
uint256 _hp,
uint256 _attack,
uint256 _defense,
uint256 _spAttack,
uint256 _spDefense,
uint256 _speed,
uint256 _typeOne,
uint256 _typeTwo,
address _owner,
uint256 _mID,
bool tradeable
)
internal
returns (uint)
{
Monster memory _monster = Monster({
birthTime: uint64(now),
hp: uint16(_hp),
attack: uint16(_attack),
defense: uint16(_defense),
spAttack: uint16(_spAttack),
spDefense: uint16(_spDefense),
speed: uint16(_speed),
typeOne: uint16(_typeOne),
typeTwo: uint16(_typeTwo),
mID: uint16(_mID),
tradeable: tradeable
});
uint256 newMonsterId = monsters.push(_monster) - 1;
monsterIdToTradeable[newMonsterId] = tradeable;
monsterIdToGeneration[newMonsterId] = _generation;
require(newMonsterId == uint256(uint32(newMonsterId)));
monsterIdToNickname[newMonsterId] = "";
_transfer(0, _owner, newMonsterId);
return newMonsterId;
}
function _createTrainer(string _username, uint16 _starterId, address _owner)
internal
returns (uint mon)
{
Trainer memory _trainer = Trainer({
birthTime: uint64(now),
username: string(_username),
currArea: uint16(1),
owner: address(_owner)
});
if (_starterId == 1) {
uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(1));
mon = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, 1, false);
} else if (_starterId == 2) {
uint8[8] memory Stats2 = uint8[8](monsterCreator.getMonsterStats(4));
mon = _createMonster(0, Stats2[0], Stats2[1], Stats2[2], Stats2[3], Stats2[4], Stats2[5], Stats2[6], Stats2[7], _owner, 4, false);
} else if (_starterId == 3) {
uint8[8] memory Stats3 = uint8[8](monsterCreator.getMonsterStats(7));
mon = _createMonster(0, Stats3[0], Stats3[1], Stats3[2], Stats3[3], Stats3[4], Stats3[5], Stats3[6], Stats3[7], _owner, 7, false);
}
}
function _moveToArea(uint16 _newArea, address player) internal {
addressToTrainer[player].currArea = _newArea;
}
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to]++;
monsterIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete monsterIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
function setSecondsPerBlock(uint256 secs) external onlyAdmin {
secondsPerBlock = secs;
}
}
contract ERC721Metadata {
function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
contract MonsterOwnership is MonstersBase, ERC721 {
string public constant name = "ChainMonsters";
string public constant symbol = "CHMO";
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
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('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
function setMetadataAddress(address _contractAddress) public onlyAdmin {
erc721Metadata = ERC721Metadata(_contractAddress);
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return monsterIndexToOwner[_tokenId] == _claimant;
}
function _isTradeable(uint256 _tokenId) external view returns (bool) {
return monsterIdToTradeable[_tokenId];
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return monsterIndexToApproved[_tokenId] == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
monsterIndexToApproved[_tokenId] = _approved;
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function transfer (address _to, uint256 _tokenId) external {
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId ) external {
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom (address _from, address _to, uint256 _tokenId ) external {
require(_to != address(0));
require(_to != address(this));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return monsters.length;
}
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = monsterIndexToOwner[_tokenId];
require(owner != address(0));
}
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalMonsters = totalSupply();
uint256 resultIndex = 0;
uint256 monsterId;
for (monsterId = 0; monsterId <= totalMonsters; monsterId++) {
if (monsterIndexToOwner[monsterId] == _owner) {
result[resultIndex] = monsterId;
resultIndex++;
}
}
return result;
}
}
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
contract MonsterAuctionBase {
ERC721 public nonFungibleContract;
ChainMonstersCore public core;
struct Auction {
address seller;
uint256 price;
uint64 startedAt;
uint256 id;
}
uint256 public ownerCut;
mapping(uint256 => Auction) tokenIdToAuction;
mapping(uint256 => address) public auctionIdToSeller;
mapping (address => uint256) public ownershipAuctionCount;
event AuctionCreated(uint256 tokenId, uint256 price, uint256 uID, address seller);
event AuctionSuccessful(uint256 tokenId, uint256 price, address newOwner, uint256 uID);
event AuctionCancelled(uint256 tokenId, uint256 uID);
function _transfer(address _receiver, uint256 _tokenId) internal {
nonFungibleContract.transfer(_receiver, _tokenId);
}
function _addAuction(uint256 _tokenId, Auction _auction) internal {
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.price),
uint256(_auction.id),
address(_auction.seller)
);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal {
Auction storage _auction = tokenIdToAuction[_tokenId];
uint256 uID = _auction.id;
_removeAuction(_tokenId);
ownershipAuctionCount[_seller]--;
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId, uID);
}
function _buy(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = auction.price;
require(_bidAmount >= price);
address seller = auction.seller;
uint256 uID = auction.id;
_removeAuction(_tokenId);
ownershipAuctionCount[seller]--;
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
if(seller != address(core)) {
seller.transfer(sellerProceeds);
}
}
uint256 bidExcess = _bidAmount - price;
msg.sender.transfer(bidExcess);
AuctionSuccessful(_tokenId, price, msg.sender, uID);
return price;
}
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
function _computeCut(uint256 _price) internal view returns (uint256) {
return _price * ownerCut / 10000;
}
}
contract MonsterAuction is MonsterAuctionBase, Ownable {
bool public isMonsterAuction = true;
uint256 public auctionIndex = 0;
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
function MonsterAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
nonFungibleContract = candidateContract;
ChainMonstersCore candidateCoreContract = ChainMonstersCore(_nftAddress);
core = candidateCoreContract;
}
function setOwnerCut(uint256 _cut) external onlyOwner {
require(_cut <= ownerCut);
ownerCut = _cut;
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
function _escrow(address _owner, uint256 _tokenId) internal {
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
function withdrawBalance() external onlyOwner {
uint256 balance = this.balance;
owner.transfer(balance);
}
function tokensInAuctionsOfOwner(address _owner) external view returns(uint256[] auctionTokens) {
uint256 numAuctions = ownershipAuctionCount[_owner];
uint256[] memory result = new uint256[](numAuctions);
uint256 totalAuctions = core.totalSupply();
uint256 resultIndex = 0;
uint256 auctionId;
for (auctionId = 0; auctionId <= totalAuctions; auctionId++) {
Auction storage auction = tokenIdToAuction[auctionId];
if (auction.seller == _owner) {
result[resultIndex] = auctionId;
resultIndex++;
}
}
return result;
}
function createAuction(uint256 _tokenId, uint256 _price, address _seller) external {
require(_price == uint256(_price));
require(core._isTradeable(_tokenId));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint256(_price),
uint64(now),
uint256(auctionIndex)
);
auctionIdToSeller[auctionIndex] = _seller;
ownershipAuctionCount[_seller]++;
auctionIndex++;
_addAuction(_tokenId, auction);
}
function buy(uint256 _tokenId) external payable {
_buy (_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
function cancelAuction(uint256 _tokenId) external {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 price,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.price,
auction.startedAt
);
}
function getPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return auction.price;
}
}
contract ChainMonstersAuction is MonsterOwnership {
function setMonsterAuctionAddress(address _address) external onlyAdmin {
MonsterAuction candidateContract = MonsterAuction(_address);
require(candidateContract.isMonsterAuction());
monsterAuction = candidateContract;
}
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 5000;
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
function createPromoMonster(uint256 _mId, address _owner) external onlyAdmin {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId)));
uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs());
uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true);
monsterIdToTradeable[monsterId] = true;
monsterIdToIVs[monsterId] = IVs;
}
function createGen0Auction(uint256 _mId, uint256 price) external onlyAdmin {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId)));
uint8[7] memory IVs = uint8[7](monsterCreator.getGen0IVs());
uint256 monsterId = _createMonster(0, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], this, _mId, true);
monsterIdToTradeable[monsterId] = true;
monsterIdToIVs[monsterId] = IVs;
monsterAuction.createAuction(monsterId, price, address(this));
gen0CreatedCount++;
}
}
contract MonsterChampionship is Ownable {
bool public isMonsterChampionship = true;
ChainMonstersCore core;
address[10] topTen;
address public currChampion;
mapping (address => uint256) public addressToPowerlevel;
mapping (uint256 => address) public rankToAddress;
function contestChampion(uint256 _tokenId) external {
uint maxIndex = 9;
if (currChampion == msg.sender)
revert();
require(core.isTrainer(msg.sender));
require(core.monsterIndexToOwner(_tokenId) == msg.sender);
uint myPowerlevel = core.getMonsterPowerLevel(_tokenId);
require(myPowerlevel > addressToPowerlevel[msg.sender]);
uint myRank = 0;
for (uint i=0; i<=maxIndex; i++) {
if ( myPowerlevel > addressToPowerlevel[topTen[i]] ) {
myRank = i;
if (myRank == maxIndex) {
currChampion = msg.sender;
}
}
}
addressToPowerlevel[msg.sender] = myPowerlevel;
address[10] storage newTopTen = topTen;
if (currChampion == msg.sender) {
for (uint j=0; j<maxIndex; j++) {
if (newTopTen[j] == msg.sender) {
newTopTen[j] = 0x0;
break;
}
}
}
for (uint x=0; x<=myRank; x++) {
if (x == myRank) {
newTopTen[x] = msg.sender;
} else {
if (x < maxIndex)
newTopTen[x] = topTen[x+1];
}
}
topTen = newTopTen;
}
function getTopPlayers()
external
view
returns (
address[10] players
) {
players = topTen;
}
function MonsterChampionship(address coreContract) public {
core = ChainMonstersCore(coreContract);
}
function withdrawBalance() external onlyOwner {
uint256 balance = this.balance;
owner.transfer(balance);
}
}
contract MonsterCreatorInterface is Ownable {
uint8 public lockedMonsterStatsCount = 0;
uint nonce = 0;
function rand(uint8 min, uint8 max) public returns (uint8) {
nonce++;
uint8 result = (uint8(sha3(block.blockhash(block.number-1), nonce ))%max);
if (result < min)
{
result = result+min;
}
return result;
}
function shinyRand(uint16 min, uint16 max) public returns (uint16) {
nonce++;
uint16 result = (uint16(sha3(block.blockhash(block.number-1), nonce ))%max);
if (result < min)
{
result = result+min;
}
return result;
}
mapping(uint256 => uint8[8]) public baseStats;
function addBaseStats(uint256 _mId, uint8[8] data) external onlyOwner {
require(data[0] > 0);
require(baseStats[_mId][0] == 0);
baseStats[_mId] = data;
}
function _addBaseStats(uint256 _mId, uint8[8] data) internal {
baseStats[_mId] = data;
lockedMonsterStatsCount++;
}
function MonsterCreatorInterface() public {
_addBaseStats(1, [45, 49, 49, 65, 65, 45, 12, 4]);
_addBaseStats(2, [60, 62, 63, 80, 80, 60, 12, 4]);
_addBaseStats(3, [80, 82, 83, 100, 100, 80, 12, 4]);
_addBaseStats(4, [39, 52, 43, 60, 50, 65, 10, 6]);
_addBaseStats(5, [58, 64, 58, 80, 65, 80, 10, 6]);
_addBaseStats(6, [78, 84, 78, 109, 85, 100, 10, 6]);
_addBaseStats(7, [44, 48, 65, 50, 64, 43, 11, 14]);
_addBaseStats(8, [59, 63, 80, 65, 80, 58, 11, 14]);
_addBaseStats(9, [79, 83, 100, 85, 105, 78, 11, 14]);
_addBaseStats(10, [40, 35, 30, 20, 20, 50, 7, 4]);
_addBaseStats(149, [55, 50, 45, 135, 95, 120, 8, 14]);
_addBaseStats(150, [91, 134, 95, 100, 100, 80, 2, 5]);
_addBaseStats(151, [100, 100, 100, 100, 100, 100, 5, 19]);
}
function getMonsterStats( uint256 _mID) external constant returns(uint8[8] stats) {
stats[0] = baseStats[_mID][0];
stats[1] = baseStats[_mID][1];
stats[2] = baseStats[_mID][2];
stats[3] = baseStats[_mID][3];
stats[4] = baseStats[_mID][4];
stats[5] = baseStats[_mID][5];
stats[6] = baseStats[_mID][6];
stats[7] = baseStats[_mID][7];
}
function getMonsterIVs() external returns(uint8[7] ivs) {
bool shiny = false;
uint16 chance = shinyRand(1, 8192);
if (chance == 42) {
shiny = true;
}
if (shiny == true) {
ivs[0] = uint8(rand(10, 31));
ivs[1] = uint8(rand(10, 31));
ivs[2] = uint8(rand(10, 31));
ivs[3] = uint8(rand(10, 31));
ivs[4] = uint8(rand(10, 31));
ivs[5] = uint8(rand(10, 31));
ivs[6] = 1;
} else {
ivs[0] = uint8(rand(0, 31));
ivs[1] = uint8(rand(0, 31));
ivs[2] = uint8(rand(0, 31));
ivs[3] = uint8(rand(0, 31));
ivs[4] = uint8(rand(0, 31));
ivs[5] = uint8(rand(0, 31));
ivs[6] = 0;
}
}
function getGen0IVs() external returns (uint8[7] ivs) {
bool shiny = false;
uint16 chance = shinyRand(1, 4096);
if (chance == 42) {
shiny = true;
}
if (shiny) {
ivs[0] = uint8(rand(15, 31));
ivs[1] = uint8(rand(15, 31));
ivs[2] = uint8(rand(15, 31));
ivs[3] = uint8(rand(15, 31));
ivs[4] = uint8(rand(15, 31));
ivs[5] = uint8(rand(15, 31));
ivs[6] = 1;
} else {
ivs[0] = uint8(rand(10, 31));
ivs[1] = uint8(rand(10, 31));
ivs[2] = uint8(rand(10, 31));
ivs[3] = uint8(rand(10, 31));
ivs[4] = uint8(rand(10, 31));
ivs[5] = uint8(rand(10, 31));
ivs[6] = 0;
}
}
function withdrawBalance() external onlyOwner {
uint256 balance = this.balance;
owner.transfer(balance);
}
}
contract GameLogicContract {
bool public isGameLogicContract = true;
function GameLogicContract() public {
}
}
contract ChainMonstersCore is ChainMonstersAuction, Ownable {
bool hasLaunched = false;
address gameContract;
function ChainMonstersCore() public {
adminAddress = msg.sender;
_createArea();
_createArea();
}
function setGameLogicContract(address _candidateContract) external onlyOwner {
require(monsterCreator.lockedMonsterStatsCount() == 151);
require(GameLogicContract(_candidateContract).isGameLogicContract());
gameContract = _candidateContract;
}
function spawnMonster(uint256 _mId, address _owner) external {
require(msg.sender == gameContract);
uint8[8] memory Stats = uint8[8](monsterCreator.getMonsterStats(uint256(_mId)));
uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs());
uint256 monsterId = _createMonster(1, Stats[0], Stats[1], Stats[2], Stats[3], Stats[4], Stats[5], Stats[6], Stats[7], _owner, _mId, true);
monsterIdToTradeable[monsterId] = true;
monsterIdToIVs[monsterId] = IVs;
}
function createArea() public onlyAdmin {
_createArea();
}
function createTrainer(string _username, uint16 _starterId) public {
require(hasLaunched);
require(addressToTrainer[msg.sender].owner == 0);
require(_starterId == 1 || _starterId == 2 || _starterId == 3 );
uint256 mon = _createTrainer(_username, _starterId, msg.sender);
uint8[7] memory IVs = uint8[7](monsterCreator.getMonsterIVs());
monsterIdToIVs[mon] = IVs;
}
function changeUsername(string _name) public {
require(addressToTrainer[msg.sender].owner == msg.sender);
addressToTrainer[msg.sender].username = _name;
}
function changeMonsterNickname(uint256 _tokenId, string _name) public {
require(_owns(msg.sender, _tokenId));
monsterIdToNickname[_tokenId] = _name;
}
function moveToArea(uint16 _newArea) public {
require(_newArea > 0);
require(areas.length >= _newArea);
_moveToArea(_newArea, msg.sender);
}
function getMonster(uint256 _id) external view returns (
uint256 birthTime,
uint256 generation,
uint256 hp,
uint256 attack,
uint256 defense,
uint256 spAttack,
uint256 spDefense,
uint256 speed,
uint256 typeOne,
uint256 typeTwo,
uint256 mID,
bool tradeable,
uint256 uID
) {
Monster storage mon = monsters[_id];
birthTime = uint256(mon.birthTime);
generation = 0;
hp = uint256(mon.hp);
attack = uint256(mon.attack);
defense = uint256(mon.defense);
spAttack = uint256(mon.spAttack);
spDefense = uint256(mon.spDefense);
speed = uint256(mon.speed);
typeOne = uint256(mon.typeOne);
typeTwo = uint256(mon.typeTwo);
mID = uint256(mon.mID);
tradeable = bool(mon.tradeable);
uID = _id;
}
function getMonsterPowerLevel(uint256 _tokenId) external view returns (
uint256 powerlevel
) {
Monster storage mon = monsters[_tokenId];
uint8[7] storage IVs = monsterIdToIVs[_tokenId];
powerlevel = mon.hp + IVs[0] + mon.attack + IVs[1] + mon.defense + IVs[2] + mon.spAttack + IVs[3] + mon.spDefense + IVs[4] + mon.speed + IVs[5];
}
function isTrainer(address _check)
external
view
returns (
bool isTrainer
) {
Trainer storage trainer = addressToTrainer[_check];
if (trainer.currArea > 0)
return true;
else
return false;
}
function withdrawBalance() external onlyOwner {
uint256 balance = this.balance;
owner.transfer(balance);
}
function launchGame() external onlyOwner {
hasLaunched = 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 CxCoin is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function CxCoin(
) {
balances[msg.sender] = 50000000;
totalSupply = 50000000;
name = "Cx Coin";
decimals = 0;
symbol = "Cx";
}
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 |
contract Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function setOwner(address _owner) public onlyOwner returns (bool) {
require(_owner != address(0));
owner = _owner;
return true;
}
}
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 HasWorkers is Ownable {
mapping(address => uint256) private workerToIndex;
address[] private workers;
event AddedWorker(address _worker);
event RemovedWorker(address _worker);
constructor() public {
workers.length++;
}
modifier onlyWorker() {
require(isWorker(msg.sender));
_;
}
modifier workerOrOwner() {
require(isWorker(msg.sender) || msg.sender == owner);
_;
}
function isWorker(address _worker) public view returns (bool) {
return workerToIndex[_worker] != 0;
}
function allWorkers() public view returns (address[] memory result) {
result = new address[](workers.length - 1);
for (uint256 i = 1; i < workers.length; i++) {
result[i - 1] = workers[i];
}
}
function addWorker(address _worker) public onlyOwner returns (bool) {
require(!isWorker(_worker));
uint256 index = workers.push(_worker) - 1;
workerToIndex[_worker] = index;
emit AddedWorker(_worker);
return true;
}
function removeWorker(address _worker) public onlyOwner returns (bool) {
require(isWorker(_worker));
uint256 index = workerToIndex[_worker];
address lastWorker = workers[workers.length - 1];
workerToIndex[lastWorker] = index;
workers[index] = lastWorker;
workers.length--;
delete workerToIndex[_worker];
emit RemovedWorker(_worker);
return true;
}
}
contract Token {
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
function approve(address _spender, uint256 _value) returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address tokenOwner) public constant returns (uint balance);
}
contract Balancer is RpSafeMath, Ownable, HasWorkers {
address[] public accounts;
address public coldWallet;
uint256 public limitEth;
mapping(address => uint256) public limitToken;
bool public paused;
constructor() public {
coldWallet = msg.sender;
}
function allAccounts() public view returns (address[]) {
return accounts;
}
function pause() public workerOrOwner returns (bool) {
paused = true;
return true;
}
function unpause() public onlyOwner returns (bool) {
paused = false;
return true;
}
function setLimitEth(uint256 limit) public onlyOwner returns (bool) {
limitEth = limit;
return true;
}
function setLimitToken(Token token, uint256 limit) public onlyOwner returns (bool) {
limitToken[token] = limit;
return true;
}
function addAccount(address account) public onlyOwner returns (bool) {
accounts.push(account);
return true;
}
function removeAccountSearch(address account) public onlyOwner returns (bool) {
for(uint256 index = 0; index < accounts.length; index++) {
if (accounts[index] == account) {
return removeAccount(index, account);
}
}
revert();
}
function removeAccount(uint256 index, address account) public onlyOwner returns (bool) {
require(accounts[index] == account);
accounts[index] = accounts[accounts.length - 1];
accounts.length -= 1;
return true;
}
function setColdWallet(address wallet) public onlyOwner returns (bool) {
coldWallet = wallet;
return true;
}
function executeTransaction(address to, uint256 value, bytes data) public onlyOwner returns (bool) {
return to.call.value(value)(data);
}
function loadEthBalances() public view returns (uint256[] memory, uint256 total) {
uint256[] memory result = new uint256[](accounts.length);
uint256 balance;
for (uint256 i = 0; i < accounts.length; i++) {
balance = accounts[i].balance;
result[i] = balance;
total += balance;
}
return (result, total);
}
function loadTokenBalances(Token token) public view returns (uint256[] memory, uint256 total) {
uint256[] memory result = new uint256[](accounts.length);
uint256 balance;
for (uint256 i = 0; i < accounts.length; i++) {
balance = token.balanceOf(accounts[i]);
result[i] = balance;
total += balance;
}
return (result, total);
}
function getTargetPerWallet(uint256 target, uint256[] memory balances) internal pure returns (uint256 nTarget) {
uint256 d = balances.length;
uint256 oTarget = target / balances.length;
uint256 t;
for (uint256 i = 0; i < balances.length; i++) {
if (balances[i] > oTarget) {
d--;
t += (balances[i] - oTarget);
}
}
nTarget = oTarget - (t / d);
}
function() public payable {
if (gasleft() > 2400) {
if (paused) {
coldWallet.transfer(address(this).balance);
} else {
uint256[] memory balances;
uint256 total;
(balances, total) = loadEthBalances();
uint256 value = address(this).balance;
uint256 targetTotal = min(limitEth, total + value);
if (targetTotal > total) {
uint256 targetPerHotwallet = getTargetPerWallet(targetTotal, balances);
for (uint256 i = 0; i < balances.length; i++) {
if (balances[i] < targetPerHotwallet) {
accounts[i].transfer(targetPerHotwallet - balances[i]);
}
}
}
uint256 toColdWallet = address(this).balance;
if (toColdWallet != 0) {
(bool success, ) = coldWallet.call.value(toColdWallet)("");
require(success, "Transfer failed.");
}
}
}
}
function handleTokens(Token token) public returns (bool) {
if (paused) {
token.transfer(coldWallet, token.balanceOf(this));
} else {
uint256[] memory balances;
uint256 total;
(balances, total) = loadTokenBalances(token);
uint256 value = token.balanceOf(address(this));
uint256 targetTotal = min(limitToken[token], total + value);
if (targetTotal > total) {
uint256 targetPerHotwallet = getTargetPerWallet(targetTotal, balances);
for (uint256 i = 0; i < balances.length; i++) {
if (balances[i] < targetPerHotwallet) {
token.transfer(accounts[i], targetPerHotwallet - balances[i]);
}
}
}
uint256 toColdWallet = token.balanceOf(address(this));
if (toColdWallet != 0) {
address(token).call(abi.encodeWithSignature("transfer(address,uint256)", coldWallet, toColdWallet));
}
}
}
} | 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 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 DragonToken{
function transferFrom(address _from, address _to, uint256 _value) returns(bool success);
}
contract Crowdsale is Ownable{
using SafeMath for uint256;
DragonToken public token;
address public tokenReserve;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
uint256 public tokensSold;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 releaseTime);
event EndTimeUpdated();
event DragonPriceUpdated();
event TokenReleased(address indexed holder, uint256 amount);
function Crowdsale() public {
owner = 0xF615Ac471E066b5ae4BD211CC5044c7a31E89C4e;
startTime = now;
endTime = 1521187200;
rate = 5000000000000000;
wallet = 0xF615Ac471E066b5ae4BD211CC5044c7a31E89C4e;
token = DragonToken(0x814F67fA286f7572B041D041b1D99b432c9155Ee);
tokenReserve = 0xF615Ac471E066b5ae4BD211CC5044c7a31E89C4e;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
uint256 lockedFor = assignTokens(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, lockedFor);
forwardFunds();
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
uint256 amount = weiAmount.div(rate);
return amount.mul(100000000);
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function updateEndTime(uint256 newTime) onlyOwner external {
require(newTime > startTime);
endTime = newTime;
EndTimeUpdated();
}
function updateDragonPrice(uint256 weiAmount) onlyOwner external {
require(weiAmount > 0);
rate = weiAmount;
DragonPriceUpdated();
}
mapping(address => uint256) balances;
mapping(address => uint256) releaseTime;
function assignTokens(address beneficiary, uint256 amount) private returns(uint256 lockedFor){
lockedFor = now + 45 days;
balances[beneficiary] = balances[beneficiary].add(amount);
releaseTime[beneficiary] = lockedFor;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function unlockTime(address _owner) public view returns (uint256 time) {
return releaseTime[_owner];
}
function releaseDragonTokens() public {
require(now >= releaseTime[msg.sender]);
uint256 amount = balances[msg.sender];
require(amount > 0);
balances[msg.sender] = 0;
if(!token.transferFrom(tokenReserve,msg.sender,amount)){
revert();
}
TokenReleased(msg.sender,amount);
}
} | 1 |
pragma solidity >=0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract DSRoles is DSAuth, DSAuthority
{
mapping(address=>bool) _root_users;
mapping(address=>bytes32) _user_roles;
mapping(address=>mapping(bytes4=>bytes32)) _capability_roles;
mapping(address=>mapping(bytes4=>bool)) _public_capabilities;
function getUserRoles(address who)
public
view
returns (bytes32)
{
return _user_roles[who];
}
function getCapabilityRoles(address code, bytes4 sig)
public
view
returns (bytes32)
{
return _capability_roles[code][sig];
}
function isUserRoot(address who)
public
view
returns (bool)
{
return _root_users[who];
}
function isCapabilityPublic(address code, bytes4 sig)
public
view
returns (bool)
{
return _public_capabilities[code][sig];
}
function hasUserRole(address who, uint8 role)
public
view
returns (bool)
{
bytes32 roles = getUserRoles(who);
bytes32 shifted = bytes32(uint256(uint256(2) ** uint256(role)));
return bytes32(0) != roles & shifted;
}
function canCall(address caller, address code, bytes4 sig)
public
view
returns (bool)
{
if( isUserRoot(caller) || isCapabilityPublic(code, sig) ) {
return true;
} else {
bytes32 has_roles = getUserRoles(caller);
bytes32 needs_one_of = getCapabilityRoles(code, sig);
return bytes32(0) != has_roles & needs_one_of;
}
}
function BITNOT(bytes32 input) internal pure returns (bytes32 output) {
return (input ^ bytes32(uint(-1)));
}
function setRootUser(address who, bool enabled)
public
auth
{
_root_users[who] = enabled;
}
function setUserRole(address who, uint8 role, bool enabled)
public
auth
{
bytes32 last_roles = _user_roles[who];
bytes32 shifted = bytes32(uint256(uint256(2) ** uint256(role)));
if( enabled ) {
_user_roles[who] = last_roles | shifted;
} else {
_user_roles[who] = last_roles & BITNOT(shifted);
}
}
function setPublicCapability(address code, bytes4 sig, bool enabled)
public
auth
{
_public_capabilities[code][sig] = enabled;
}
function setRoleCapability(uint8 role, address code, bytes4 sig, bool enabled)
public
auth
{
bytes32 last_roles = _capability_roles[code][sig];
bytes32 shifted = bytes32(uint256(uint256(2) ** uint256(role)));
if( enabled ) {
_capability_roles[code][sig] = last_roles | shifted;
} else {
_capability_roles[code][sig] = last_roles & BITNOT(shifted);
}
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue
}
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
_;
}
}
contract DSThing is DSAuth, DSNote, DSMath {
function S(string memory s) internal pure returns (bytes4) {
return bytes4(keccak256(abi.encodePacked(s)));
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped, "ds-stop-is-stopped");
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18;
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
require(_balances[guy] >= wad, "ds-token-insufficient-balance");
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
contract DSChiefApprovals is DSThing {
mapping(bytes32=>address[]) public slates;
mapping(address=>bytes32) public votes;
mapping(address=>uint256) public approvals;
mapping(address=>uint256) public deposits;
DSToken public GOV;
DSToken public IOU;
address public hat;
uint256 public MAX_YAYS;
event Etch(bytes32 indexed slate);
constructor(DSToken GOV_, DSToken IOU_, uint MAX_YAYS_) public
{
GOV = GOV_;
IOU = IOU_;
MAX_YAYS = MAX_YAYS_;
}
function lock(uint wad)
public
note
{
GOV.pull(msg.sender, wad);
IOU.mint(msg.sender, wad);
deposits[msg.sender] = add(deposits[msg.sender], wad);
addWeight(wad, votes[msg.sender]);
}
function free(uint wad)
public
note
{
deposits[msg.sender] = sub(deposits[msg.sender], wad);
subWeight(wad, votes[msg.sender]);
IOU.burn(msg.sender, wad);
GOV.push(msg.sender, wad);
}
function etch(address[] memory yays)
public
note
returns (bytes32 slate)
{
require( yays.length <= MAX_YAYS );
requireByteOrderedSet(yays);
bytes32 hash = keccak256(abi.encodePacked(yays));
slates[hash] = yays;
emit Etch(hash);
return hash;
}
function vote(address[] memory yays) public returns (bytes32)
{
bytes32 slate = etch(yays);
vote(slate);
return slate;
}
function vote(bytes32 slate)
public
note
{
require(slates[slate].length > 0 ||
slate == 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470, "ds-chief-invalid-slate");
uint weight = deposits[msg.sender];
subWeight(weight, votes[msg.sender]);
votes[msg.sender] = slate;
addWeight(weight, votes[msg.sender]);
}
function lift(address whom)
public
note
{
require(approvals[whom] > approvals[hat]);
hat = whom;
}
function addWeight(uint weight, bytes32 slate)
internal
{
address[] storage yays = slates[slate];
for( uint i = 0; i < yays.length; i++) {
approvals[yays[i]] = add(approvals[yays[i]], weight);
}
}
function subWeight(uint weight, bytes32 slate)
internal
{
address[] storage yays = slates[slate];
for( uint i = 0; i < yays.length; i++) {
approvals[yays[i]] = sub(approvals[yays[i]], weight);
}
}
function requireByteOrderedSet(address[] memory yays)
internal
pure
{
if( yays.length == 0 || yays.length == 1 ) {
return;
}
for( uint i = 0; i < yays.length - 1; i++ ) {
require(uint(yays[i]) < uint(yays[i+1]));
}
}
}
contract DSChief is DSRoles, DSChiefApprovals {
constructor(DSToken GOV, DSToken IOU, uint MAX_YAYS)
DSChiefApprovals (GOV, IOU, MAX_YAYS)
public
{
authority = this;
owner = address(0);
}
function setOwner(address owner_) public {
owner_;
revert();
}
function setAuthority(DSAuthority authority_) public {
authority_;
revert();
}
function isUserRoot(address who)
public view
returns (bool)
{
return (who == hat);
}
function setRootUser(address who, bool enabled) public {
who; enabled;
revert();
}
} | 0 |
pragma solidity ^0.4.24;
contract EthRoll {
uint constant HOUSE_EDGE_PERCENT = 15;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.00045 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
address public beneficiary_ = 0xAdD148Cc4F7B1b7520325a7C5934C002420Ab3d5;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
address public croupier;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
event Commit(uint commit);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
croupier = DUMMY_ADDRESS;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
modifier onlyCroupier {
require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier.");
_;
}
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function () public payable {
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function setCroupier(address newCroupier) external onlyOwner {
croupier = newCroupier;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary_, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(beneficiary_);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
emit Commit(commit);
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, bytes32 blockHash) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint placeBlockNumber = bet.placeBlockNumber;
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
require (blockhash(placeBlockNumber) == blockHash);
settleBetCommon(bet, reveal, blockHash);
}
function settleBetUncleMerkleProof(uint reveal, uint40 canonicalBlockNumber) external onlyCroupier {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
requireCorrectReceipt(4 + 32 + 32 + 4);
bytes32 canonicalHash;
bytes32 uncleHash;
(canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);
require (blockhash(canonicalBlockNumber) == canonicalHash);
settleBetCommon(bet, reveal, uncleHash);
}
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 1000;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.call.value(amount)()) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) }
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
for (;; offset += blobLength) {
assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) }
if (blobLength == 0) {
break;
}
assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) }
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
seedHash := sha3(scratchBuf1, blobLength)
uncleHeaderLength := blobLength
}
}
uncleHash = bytes32(seedHash);
uint scratchBuf2 = scratchBuf1 + uncleHeaderLength;
uint unclesLength; assembly { unclesLength := and(calldataload(sub(offset, 28)), 0xffff) }
uint unclesShift; assembly { unclesShift := and(calldataload(sub(offset, 26)), 0xffff) }
require (unclesShift + uncleHeaderLength <= unclesLength, "Shift bounds check.");
offset += 6;
assembly { calldatacopy(scratchBuf2, offset, unclesLength) }
memcpy(scratchBuf2 + unclesShift, scratchBuf1, uncleHeaderLength);
assembly { seedHash := sha3(scratchBuf2, unclesLength) }
offset += unclesLength;
assembly {
blobLength := and(calldataload(sub(offset, 30)), 0xffff)
shift := and(calldataload(sub(offset, 28)), 0xffff)
}
require (shift + 32 <= blobLength, "Shift bounds check.");
offset += 4;
assembly { hashSlot := calldataload(add(offset, shift)) }
require (hashSlot == 0, "Non-empty hash slot.");
assembly {
calldatacopy(scratchBuf1, offset, blobLength)
mstore(add(scratchBuf1, shift), seedHash)
blockHash := sha3(scratchBuf1, blobLength)
}
}
function requireCorrectReceipt(uint offset) view private {
uint leafHeaderByte; assembly { leafHeaderByte := byte(0, calldataload(offset)) }
require (leafHeaderByte >= 0xf7, "Receipt leaf longer than 55 bytes.");
offset += leafHeaderByte - 0xf6;
uint pathHeaderByte; assembly { pathHeaderByte := byte(0, calldataload(offset)) }
if (pathHeaderByte <= 0x7f) {
offset += 1;
} else {
require (pathHeaderByte >= 0x80 && pathHeaderByte <= 0xb7, "Path is an RLP string.");
offset += pathHeaderByte - 0x7f;
}
uint receiptStringHeaderByte; assembly { receiptStringHeaderByte := byte(0, calldataload(offset)) }
require (receiptStringHeaderByte == 0xb9, "Receipt string is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint receiptHeaderByte; assembly { receiptHeaderByte := byte(0, calldataload(offset)) }
require (receiptHeaderByte == 0xf9, "Receipt is always at least 256 bytes long, but less than 64k.");
offset += 3;
uint statusByte; assembly { statusByte := byte(0, calldataload(offset)) }
require (statusByte == 0x1, "Status should be success.");
offset += 1;
uint cumGasHeaderByte; assembly { cumGasHeaderByte := byte(0, calldataload(offset)) }
if (cumGasHeaderByte <= 0x7f) {
offset += 1;
} else {
require (cumGasHeaderByte >= 0x80 && cumGasHeaderByte <= 0xb7, "Cumulative gas is an RLP string.");
offset += cumGasHeaderByte - 0x7f;
}
uint bloomHeaderByte; assembly { bloomHeaderByte := byte(0, calldataload(offset)) }
require (bloomHeaderByte == 0xb9, "Bloom filter is always 256 bytes long.");
offset += 256 + 3;
uint logsListHeaderByte; assembly { logsListHeaderByte := byte(0, calldataload(offset)) }
require (logsListHeaderByte == 0xf8, "Logs list is less than 256 bytes long.");
offset += 2;
uint logEntryHeaderByte; assembly { logEntryHeaderByte := byte(0, calldataload(offset)) }
require (logEntryHeaderByte == 0xf8, "Log entry is less than 256 bytes long.");
offset += 2;
uint addressHeaderByte; assembly { addressHeaderByte := byte(0, calldataload(offset)) }
require (addressHeaderByte == 0x94, "Address is 20 bytes long.");
uint logAddress; assembly { logAddress := and(calldataload(sub(offset, 11)), 0xffffffffffffffffffffffffffffffffffffffff) }
require (logAddress == uint(address(this)));
}
function memcpy(uint dest, uint src, uint len) pure private {
for(; len >= 32; len -= 32) {
assembly { mstore(dest, mload(src)) }
dest += 32; src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
} | 1 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, 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] = 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;
}
}
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 InvestorsFeature is Ownable, StandardToken {
using SafeMath for uint;
address[] public investors;
mapping(address => bool) isInvestor;
function deposit(address investor, uint) internal {
if(isInvestor[investor] == false) {
investors.push(investor);
isInvestor[investor] = true;
}
}
function sendp(address addr, uint amount) internal {
require(addr != address(0));
require(amount > 0);
deposit(addr, amount);
balances[this] = balances[this].sub(amount);
balances[addr] = balances[addr].add(amount);
Transfer(this, addr, amount);
}
}
contract xCrypt is Ownable, StandardToken, InvestorsFeature {
string public constant name = "xCrypt";
string public constant symbol = "XCT";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = (200 * (10**6)) * (10 ** uint256(decimals));
uint8 public constant ADVISORS_SHARE = 8;
uint8 public constant TEAM_SHARE = 15;
uint8 public constant RESERVES_SHARE = 9;
uint8 public constant BOUNTIES_SHARE = 3;
address public advisorsWallet;
address public teamWallet;
address public reservesWallet;
address public bountiesWallet;
function xCrypt(
address _advisorsWallet,
address _teamWallet,
address _reservesWallet,
address _bountiesWallet
) public {
totalSupply = INITIAL_SUPPLY;
balances[this] = INITIAL_SUPPLY;
Transfer(address(0), this, INITIAL_SUPPLY);
advisorsWallet = _advisorsWallet;
teamWallet = _teamWallet;
reservesWallet = _reservesWallet;
bountiesWallet = _bountiesWallet;
sendTokens(_advisorsWallet, totalSupply * ADVISORS_SHARE / 100);
sendTokens(_teamWallet, totalSupply * TEAM_SHARE / 100);
sendTokens(_reservesWallet, totalSupply * RESERVES_SHARE / 100);
sendTokens(_bountiesWallet, totalSupply * BOUNTIES_SHARE / 100);
}
function sendTokens(address addr, uint amount) public onlyOwner {
sendp(addr, amount);
}
function moneyBack(address addr) public onlyOwner {
require(addr != 0x0);
addr.transfer(this.balance);
}
function burnRemainder(uint) public onlyOwner {
uint value = balances[this];
totalSupply = totalSupply.sub(value);
balances[this] = 0;
}
} | 1 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract CryptoEngineerInterface {
uint256 public prizePool = 0;
function subVirus(address , uint256 ) public {}
function claimPrizePool(address , uint256 ) public {}
function isContractMiniGame() public pure returns( bool ) {}
function isEngineerContract() external pure returns(bool) {}
}
contract CryptoMiningWarInterface {
uint256 public deadline;
function subCrystal( address , uint256 ) public {}
function isMiningWarContract() external pure returns(bool) {}
}
interface MiniGameInterface {
function isContractMiniGame() external pure returns( bool _isContractMiniGame );
}
contract CrystalDeposit {
using SafeMath for uint256;
address public administrator;
uint256 public HALF_TIME = 48 hours;
uint256 public MIN_TIME_WITH_DEADLINE = 12 hours;
uint256 public round = 0;
CryptoEngineerInterface public Engineer;
CryptoMiningWarInterface public MiningWar;
address miningWarAddress;
uint256 miningWarDeadline;
uint256 constant private CRTSTAL_MINING_PERIOD = 86400;
mapping(uint256 => Game) public games;
mapping(address => Player) public players;
mapping(address => bool) public miniGames;
struct Game {
uint256 round;
uint256 crystals;
uint256 prizePool;
uint256 startTime;
uint256 endTime;
bool ended;
}
struct Player {
uint256 currentRound;
uint256 lastRound;
uint256 reward;
uint256 share;
}
event EndRound(uint256 round, uint256 crystals, uint256 prizePool, uint256 startTime, uint256 endTime);
event Deposit(address player, uint256 currentRound, uint256 deposit, uint256 currentShare);
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
setMiningWarInterface(0x1b002cd1ba79dfad65e8abfbb3a97826e4960fe5);
setEngineerInterface(0xd7afbf5141a7f1d6b0473175f7a6b0a7954ed3d2);
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function isDepositContract() public pure returns(bool)
{
return true;
}
function upgrade(address addr) public isAdministrator
{
selfdestruct(addr);
}
function setContractsMiniGame( address _addr ) public isAdministrator
{
MiniGameInterface MiniGame = MiniGameInterface( _addr );
if( MiniGame.isContractMiniGame() == false ) { revert(); }
miniGames[_addr] = true;
}
function removeContractMiniGame(address _addr) public isAdministrator
{
miniGames[_addr] = false;
}
function setupMiniGame( uint256 , uint256 _miningWarDeadline ) public
{
require(msg.sender == miningWarAddress);
miningWarDeadline = _miningWarDeadline;
}
function setMiningWarInterface(address _addr) public isAdministrator
{
CryptoMiningWarInterface miningWarInterface = CryptoMiningWarInterface(_addr);
require(miningWarInterface.isMiningWarContract() == true);
miningWarAddress = _addr;
MiningWar = miningWarInterface;
}
function setEngineerInterface(address _addr) public isAdministrator
{
CryptoEngineerInterface engineerInterface = CryptoEngineerInterface(_addr);
require(engineerInterface.isEngineerContract() == true);
Engineer = engineerInterface;
}
function startGame() public isAdministrator
{
miningWarDeadline = MiningWar.deadline();
games[round].ended = true;
startRound();
}
function startRound() private
{
require(games[round].ended == true);
uint256 crystalsLastRound = games[round].crystals;
uint256 prizePoolLastRound= games[round].prizePool;
round = round + 1;
uint256 startTime = now;
if (miningWarDeadline < SafeMath.add(startTime, MIN_TIME_WITH_DEADLINE)) startTime = miningWarDeadline;
uint256 endTime = startTime + HALF_TIME;
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
Engineer.claimPrizePool(address(this), prizePool);
if (crystalsLastRound == 0) prizePool = SafeMath.add(prizePool, prizePoolLastRound);
games[round] = Game(round, 0, prizePool, startTime, endTime, false);
}
function endRound() private
{
require(games[round].ended == false);
require(games[round].endTime <= now);
Game storage g = games[round];
g.ended = true;
startRound();
emit EndRound(g.round, g.crystals, g.prizePool, g.startTime, g.endTime);
}
function share(uint256 _value) public disableContract
{
require(games[round].ended == false);
require(games[round].startTime <= now);
require(_value >= 1);
MiningWar.subCrystal(msg.sender, _value);
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
Game storage g = games[round];
uint256 _share = SafeMath.mul(_value, CRTSTAL_MINING_PERIOD);
g.crystals = SafeMath.add(g.crystals, _share);
Player storage p = players[msg.sender];
if (p.currentRound == round) {
p.share = SafeMath.add(p.share, _share);
} else {
p.share = _share;
p.currentRound = round;
}
emit Deposit(msg.sender, p.currentRound, _value, p.share);
}
function getCurrentReward(address _addr) public view returns(uint256 _currentReward)
{
Player memory p = players[_addr];
_currentReward = p.reward;
_currentReward += calculateReward(_addr, p.currentRound);
}
function withdrawReward(address _addr) public
{
if (games[round].endTime <= now) endRound();
updateReward(_addr);
Player storage p = players[_addr];
uint256 balance = p.reward;
if (address(this).balance >= balance && balance > 0) {
_addr.transfer(balance);
p.reward = 0;
}
}
function updateReward(address _addr) private
{
Player storage p = players[_addr];
if (
games[p.currentRound].ended == true &&
p.lastRound < p.currentRound
) {
p.reward = SafeMath.add(p.reward, calculateReward(_addr, p.currentRound));
p.lastRound = p.currentRound;
}
}
function getData(address _addr)
public
view
returns(
uint256 _prizePool,
uint256 _crystals,
uint256 _startTime,
uint256 _endTime,
uint256 _reward,
uint256 _share
) {
(_prizePool, _crystals, _startTime, _endTime) = getCurrentGame();
(_reward, _share) = getPlayerData(_addr);
}
function calculateReward(address _addr, uint256 _round) public view returns(uint256)
{
Player memory p = players[_addr];
Game memory g = games[_round];
if (g.endTime > now) return 0;
if (g.crystals == 0) return 0;
if (p.lastRound >= _round) return 0;
return SafeMath.div(SafeMath.mul(g.prizePool, p.share), g.crystals);
}
function getCurrentGame() private view returns(uint256 _prizePool, uint256 _crystals, uint256 _startTime, uint256 _endTime)
{
Game memory g = games[round];
_prizePool = g.prizePool;
_crystals = g.crystals;
_startTime = g.startTime;
_endTime = g.endTime;
}
function getPlayerData(address _addr) private view returns(uint256 _reward, uint256 _share)
{
Player memory p = players[_addr];
_reward = p.reward;
if (p.currentRound == round) _share = players[_addr].share;
if (p.currentRound != p.lastRound) _reward += calculateReward(_addr, p.currentRound);
}
function getEngineerPrizePool() private view returns(uint256)
{
return Engineer.prizePool();
}
} | 0 |
pragma solidity ^0.4.15;
contract BMICOAffiliateProgramm {
struct itemReferrals {
uint256 amount_investments;
uint256 preico_holdersBonus;
}
mapping (address => itemReferrals) referralsInfo;
uint256 public preico_holdersAmountInvestWithBonus = 0;
mapping (string => address) partnersPromo;
struct itemPartners {
uint256 attracted_investments;
string promo;
uint16 personal_percent;
uint256 preico_partnerBonus;
bool create;
}
mapping (address => itemPartners) partnersInfo;
uint16 public ref_percent = 100;
struct itemHistory {
uint256 datetime;
address referral;
uint256 amount_invest;
}
mapping(address => itemHistory[]) history;
uint256 public amount_referral_invest;
address public owner;
address public contractPreICO;
address public contractICO;
function BMICOAffiliateProgramm(){
owner = msg.sender;
contractPreICO = address(0x0);
contractICO = address(0x0);
}
modifier isOwner()
{
assert(msg.sender == owner);
_;
}
function str_length(string x) constant internal returns (uint256) {
bytes32 str;
assembly {
str := mload(add(x, 32))
}
bytes memory bytesString = new bytes(32);
uint256 charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(str) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
return charCount;
}
function changeOwner(address new_owner) isOwner {
assert(new_owner!=address(0x0));
assert(new_owner!=address(this));
owner = new_owner;
}
function setReferralPercent(uint16 new_percent) isOwner {
ref_percent = new_percent;
}
function setPartnerPercent(address partner, uint16 new_percent) isOwner {
assert(partner!=address(0x0));
assert(partner!=address(this));
assert(partnersInfo[partner].create==true);
partnersInfo[partner].personal_percent = new_percent;
}
function setContractPreICO(address new_address) isOwner {
assert(contractPreICO==address(0x0));
assert(new_address!=address(0x0));
assert(new_address!=address(this));
contractPreICO = new_address;
}
function setContractICO(address new_address) isOwner {
assert(contractICO==address(0x0));
assert(new_address!=address(0x0));
assert(new_address!=address(this));
contractICO = new_address;
}
function setPromoToPartner(string promo) {
assert(partnersPromo[promo]==address(0x0));
assert(partnersInfo[msg.sender].create==false);
assert(str_length(promo)>0 && str_length(promo)<=6);
partnersPromo[promo] = msg.sender;
partnersInfo[msg.sender].attracted_investments = 0;
partnersInfo[msg.sender].promo = promo;
partnersInfo[msg.sender].create = true;
}
function checkPromo(string promo) constant returns(bool){
return partnersPromo[promo]!=address(0x0);
}
function checkPartner(address partner_address) constant returns(bool isPartner, string promo){
isPartner = partnersInfo[partner_address].create;
promo = '-1';
if(isPartner){
promo = partnersInfo[partner_address].promo;
}
}
function calc_partnerPercent(address partner) constant internal returns(uint16 percent){
percent = 0;
if(partnersInfo[partner].personal_percent > 0){
percent = partnersInfo[partner].personal_percent;
}
else{
uint256 attracted_investments = partnersInfo[partner].attracted_investments;
if(attracted_investments > 0){
if(attracted_investments < 3 ether){
percent = 300;
}
else if(attracted_investments >= 3 ether && attracted_investments < 10 ether){
percent = 500;
}
else if(attracted_investments >= 10 ether && attracted_investments < 100 ether){
percent = 700;
}
else if(attracted_investments >= 100 ether){
percent = 1000;
}
}
}
}
function partnerInfo(address partner_address) isOwner constant returns(string promo, uint256 attracted_investments, uint256[] h_datetime, uint256[] h_invest, address[] h_referrals){
if(partner_address != address(0x0) && partnersInfo[partner_address].create){
promo = partnersInfo[partner_address].promo;
attracted_investments = partnersInfo[partner_address].attracted_investments;
h_datetime = new uint256[](history[partner_address].length);
h_invest = new uint256[](history[partner_address].length);
h_referrals = new address[](history[partner_address].length);
for(uint256 i=0; i<history[partner_address].length; i++){
h_datetime[i] = history[partner_address][i].datetime;
h_invest[i] = history[partner_address][i].amount_invest;
h_referrals[i] = history[partner_address][i].referral;
}
}
else{
promo = '-1';
attracted_investments = 0;
h_datetime = new uint256[](0);
h_invest = new uint256[](0);
h_referrals = new address[](0);
}
}
function refferalPreICOBonus(address referral) constant external returns (uint256 bonus){
bonus = referralsInfo[referral].preico_holdersBonus;
}
function partnerPreICOBonus(address partner) constant external returns (uint256 bonus){
bonus = partnersInfo[partner].preico_partnerBonus;
}
function referralAmountInvest(address referral) constant external returns (uint256 amount){
amount = referralsInfo[referral].amount_investments;
}
function add_referral(address referral, string promo, uint256 amount) external returns(address partner, uint256 p_partner, uint256 p_referral){
p_partner = 0;
p_referral = 0;
partner = address(0x0);
if(partnersPromo[promo] != address(0x0) && partnersPromo[promo] != referral){
partner = partnersPromo[promo];
if(msg.sender == contractPreICO){
referralsInfo[referral].amount_investments += amount;
amount_referral_invest += amount;
partnersInfo[partner].attracted_investments += amount;
history[partner].push(itemHistory(now, referral, amount));
uint256 partner_bonus = (amount*uint256(calc_partnerPercent(partner)))/10000;
if(partner_bonus > 0){
partnersInfo[partner].preico_partnerBonus += partner_bonus;
}
uint256 referral_bonus = (amount*uint256(ref_percent))/10000;
if(referral_bonus > 0){
referralsInfo[referral].preico_holdersBonus += referral_bonus;
preico_holdersAmountInvestWithBonus += amount;
}
}
if (msg.sender == contractICO){
referralsInfo[referral].amount_investments += amount;
amount_referral_invest += amount;
partnersInfo[partner].attracted_investments += amount;
history[partner].push(itemHistory(now, referral, amount));
p_partner = (amount*uint256(calc_partnerPercent(partner)))/10000;
p_referral = (amount*uint256(ref_percent))/10000;
}
}
}
} | 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) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract 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 TeamAllocation is Ownable {
using SafeMath for uint;
uint public unlockedAt;
PillarToken plr;
mapping (address => uint) allocations;
uint tokensCreated = 0;
uint constant public lockedTeamAllocationTokens = 16000000e18;
address public teamStorageVault = 0x3f5D90D5Cc0652AAa40519114D007Bf119Afe1Cf;
function TeamAllocation() {
plr = PillarToken(msg.sender);
uint nineMonths = 9 * 30 days;
unlockedAt = now.add(nineMonths);
allocations[teamStorageVault] = lockedTeamAllocationTokens;
}
function getTotalAllocation() returns (uint){
return lockedTeamAllocationTokens;
}
function unlock() external payable {
if (now < unlockedAt) throw;
if (tokensCreated == 0) {
tokensCreated = plr.balanceOf(this);
}
plr.transfer(teamStorageVault, tokensCreated);
}
}
contract UnsoldAllocation is Ownable {
using SafeMath for uint;
uint unlockedAt;
uint allocatedTokens;
PillarToken plr;
mapping (address => uint) allocations;
uint tokensCreated = 0;
function UnsoldAllocation(uint _lockTime, address _owner, uint _tokens) {
if(_lockTime == 0) throw;
if(_owner == address(0)) throw;
plr = PillarToken(msg.sender);
uint lockTime = _lockTime * 1 years;
unlockedAt = now.add(lockTime);
allocatedTokens = _tokens;
allocations[_owner] = _tokens;
}
function getTotalAllocation()returns(uint){
return allocatedTokens;
}
function unlock() external payable {
if (now < unlockedAt) throw;
if (tokensCreated == 0) {
tokensCreated = plr.balanceOf(this);
}
var allocation = allocations[msg.sender];
allocations[msg.sender] = 0;
var toTransfer = (tokensCreated.mul(allocation)).div(allocatedTokens);
plr.transfer(msg.sender, toTransfer);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
if (paused) throw;
_;
}
modifier whenPaused {
if (!paused) throw;
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
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 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 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 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 PillarToken is StandardToken, Ownable {
using SafeMath for uint;
string public constant name = "PILLAR";
string public constant symbol = "PLR";
uint public constant decimals = 18;
TeamAllocation public teamAllocation;
UnsoldAllocation public unsoldTokens;
UnsoldAllocation public twentyThirtyAllocation;
UnsoldAllocation public futureSaleAllocation;
uint constant public minTokensForSale = 32000000e18;
uint constant public maxPresaleTokens = 48000000e18;
uint constant public totalAvailableForSale = 528000000e18;
uint constant public futureTokens = 120000000e18;
uint constant public twentyThirtyTokens = 80000000e18;
uint constant public lockedTeamAllocationTokens = 16000000e18;
uint constant public unlockedTeamAllocationTokens = 8000000e18;
address public unlockedTeamStorageVault = 0x4162Ad6EEc341e438eAbe85f52a941B078210819;
address public twentyThirtyVault = 0xe72bA5c6F63Ddd395DF9582800E2821cE5a05D75;
address public futureSaleVault = 0xf0231160Bd1a2a2D25aed2F11B8360EbF56F6153;
address unsoldVault;
uint constant coldStorageYears = 10;
uint constant futureStorageYears = 3;
uint totalPresale = 0;
uint public constant tokenPrice = 0.0005 ether;
address public pillarTokenFactory;
uint fundingStartBlock;
uint fundingStopBlock;
bool fundingMode;
uint totalUsedTokens;
event Refund(address indexed _from,uint256 _value);
event Migrate(address indexed _from, address indexed _to, uint256 _value);
event MoneyAddedForRefund(address _from, uint256 _value,uint256 _total);
modifier isNotFundable() {
if (fundingMode) throw;
_;
}
modifier isFundable() {
if (!fundingMode) throw;
_;
}
function PillarToken(address _pillarTokenFactory, address _icedWallet) {
if(_pillarTokenFactory == address(0)) throw;
if(_icedWallet == address(0)) throw;
pillarTokenFactory = _pillarTokenFactory;
totalUsedTokens = 0;
totalSupply = 800000000e18;
unsoldVault = _icedWallet;
balances[unlockedTeamStorageVault] = unlockedTeamAllocationTokens;
futureSaleAllocation = new UnsoldAllocation(futureStorageYears,futureSaleVault,futureTokens);
balances[address(futureSaleAllocation)] = futureTokens;
twentyThirtyAllocation = new UnsoldAllocation(futureStorageYears,twentyThirtyVault,twentyThirtyTokens);
balances[address(twentyThirtyAllocation)] = twentyThirtyTokens;
fundingMode = false;
}
function() payable isFundable external {
purchase();
}
function purchase() payable isFundable {
if(block.number < fundingStartBlock) throw;
if(block.number > fundingStopBlock) throw;
if(totalUsedTokens >= totalAvailableForSale) throw;
if (msg.value < tokenPrice) throw;
uint numTokens = msg.value.div(tokenPrice);
if(numTokens < 1) throw;
pillarTokenFactory.transfer(msg.value);
uint tokens = numTokens.mul(1e18);
totalUsedTokens = totalUsedTokens.add(tokens);
if (totalUsedTokens > totalAvailableForSale) throw;
balances[msg.sender] = balances[msg.sender].add(tokens);
Transfer(0, msg.sender, tokens);
}
function numberOfTokensLeft() constant returns (uint256) {
uint tokensAvailableForSale = totalAvailableForSale.sub(totalUsedTokens);
return tokensAvailableForSale;
}
function finalize() isFundable onlyOwner external {
if (block.number <= fundingStopBlock) throw;
if (totalUsedTokens < minTokensForSale) throw;
if(unsoldVault == address(0)) throw;
fundingMode = false;
teamAllocation = new TeamAllocation();
balances[address(teamAllocation)] = lockedTeamAllocationTokens;
uint totalUnSold = numberOfTokensLeft();
if(totalUnSold > 0) {
unsoldTokens = new UnsoldAllocation(coldStorageYears,unsoldVault,totalUnSold);
balances[address(unsoldTokens)] = totalUnSold;
}
pillarTokenFactory.transfer(this.balance);
}
function refund() isFundable external {
if(block.number <= fundingStopBlock) throw;
if(totalUsedTokens >= minTokensForSale) throw;
uint plrValue = balances[msg.sender];
if(plrValue == 0) throw;
balances[msg.sender] = 0;
uint ethValue = plrValue.mul(tokenPrice).div(1e18);
msg.sender.transfer(ethValue);
Refund(msg.sender, ethValue);
}
function allocateForRefund() external payable onlyOwner returns (uint){
MoneyAddedForRefund(msg.sender,msg.value,this.balance);
return this.balance;
}
function allocateTokens(address _to,uint _tokens) isNotFundable onlyOwner external {
uint numOfTokens = _tokens.mul(1e18);
totalPresale = totalPresale.add(numOfTokens);
if(totalPresale > maxPresaleTokens) throw;
balances[_to] = balances[_to].add(numOfTokens);
}
function unPauseTokenSale() onlyOwner isNotFundable external returns (bool){
fundingMode = true;
return fundingMode;
}
function pauseTokenSale() onlyOwner isFundable external returns (bool){
fundingMode = false;
return !fundingMode;
}
function startTokenSale(uint _fundingStartBlock, uint _fundingStopBlock) onlyOwner isNotFundable external returns (bool){
if(_fundingStopBlock <= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
fundingMode = true;
return fundingMode;
}
function fundingStatus() external constant returns (bool){
return fundingMode;
}
} | 0 |
pragma solidity ^0.4.20;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
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 ERC20Token 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 ERC20Token() public {
symbol = "DIPS";
name = "Decentralized Intellectual Property System";
decimals = 18;
_totalSupply = 200 * (10**8) * 10**uint(decimals);
balances[owner] = _totalSupply;
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);
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 () 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 ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "JungleToken";
string public constant TOKEN_SYMBOL = "JT";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xC382aed23B5e13976791Fb3D2aa588865EA81C92;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 |
pragma solidity ^0.4.24;
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
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);
}
}
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
address private admin = msg.sender;
uint256 public registrationFee_ = 10 finney;
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
{
plyr_[1].addr = 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8b4DA1827932D71759687f925D17F81Fc94e3A9D] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C] = 4;
pIDxName_["inventor"] = 4;
plyrNames_[4]["inventor"] = true;
plyrNameList_[4][1] = "inventor";
pID_ = 4;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
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;
}
admin.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)
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);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0);
games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0);
games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0);
}
function setRegistrationFee(uint256 _fee)
public
{
registrationFee_ = _fee;
}
} | 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 = 29289600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xebc5f91e2960c2c6a7005ed5d87a536b0d7e34f5;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.23;
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);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract TraxionWallet is Ownable {
using SafeMath for uint256;
address public wallet = 0x6163286bA933d8a007c02DB6b0fd5A08629d23f8;
uint256 public rate = 1000;
uint256 public minInvestment = 4E17;
uint256 public investmentUpperBounds = 2E21;
uint256 public hardcap = 1E23;
uint256 public weiRaised;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
function () external payable {
buyTokens(msg.sender);
}
mapping (address => bool) public whitelistedAddr;
mapping (address => uint256) public totalInvestment;
function whitelistAddress(address[] buyer) external onlyOwner {
for (uint i = 0; i < buyer.length; i++) {
whitelistedAddr[buyer[i]] = true;
}
}
function blacklistAddr(address[] buyer) external onlyOwner {
for (uint i = 0; i < buyer.length; i++) {
whitelistedAddr[buyer[i]] = false;
}
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
emit TokenPurchase(msg.sender, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view {
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(_weiAmount > minInvestment);
require(whitelistedAddr[_beneficiary]);
require(totalInvestment[_beneficiary].add(_weiAmount) <= investmentUpperBounds);
require(weiRaised.add(_weiAmount) <= hardcap);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
totalInvestment[_beneficiary] = totalInvestment[_beneficiary].add(_weiAmount);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
} | 1 |
pragma solidity 0.4.18;
contract MultiSigWallet {
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
uint constant public MAX_OWNER_COUNT = 50;
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
contract MultiSigWalletWithDailyLimit is MultiSigWallet {
event DailyLimitChange(uint dailyLimit);
uint public dailyLimit;
uint public lastDay;
uint public spentToday;
function MultiSigWalletWithDailyLimit(address[] _owners, uint _required, uint _dailyLimit)
public
MultiSigWallet(_owners, _required)
{
dailyLimit = _dailyLimit;
}
function changeDailyLimit(uint _dailyLimit)
public
onlyWallet
{
dailyLimit = _dailyLimit;
DailyLimitChange(_dailyLimit);
}
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
Transaction storage txn = transactions[transactionId];
bool _confirmed = isConfirmed(transactionId);
if (_confirmed || txn.data.length == 0 && isUnderLimit(txn.value)) {
txn.executed = true;
if (!_confirmed)
spentToday += txn.value;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
if (!_confirmed)
spentToday -= txn.value;
}
}
}
function isUnderLimit(uint amount)
internal
returns (bool)
{
if (now > lastDay + 24 hours) {
lastDay = now;
spentToday = 0;
}
if (spentToday + amount > dailyLimit || spentToday + amount < spentToday)
return false;
return true;
}
function calcMaxWithdraw()
public
constant
returns (uint)
{
if (now > lastDay + 24 hours)
return dailyLimit;
if (dailyLimit < spentToday)
return 0;
return dailyLimit - spentToday;
}
} | 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 = 26956800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x5D8ebDC65043c1e58a527eA88D6eA6BbAf16Cb69;
}
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 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 STELLARCLASSIC 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 STELLARCLASSIC() public {
symbol = "XLMX";
name = "STELLAR CLASSIC";
decimals = 18;
_totalSupply = 20950990560000000000000000000;
balances[0xf3D5C6aECB62b8E434c844260EA91601d8082357] = _totalSupply;
Transfer(address(0), 0xf3D5C6aECB62b8E434c844260EA91601d8082357, _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.25;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract Pausable is Ownable {
event PausePublic(bool newState);
event PauseOwnerAdmin(bool newState);
bool public pausedPublic = false;
bool public pausedOwnerAdmin = false;
address public admin;
modifier whenNotPaused() {
if(pausedPublic) {
if(!pausedOwnerAdmin) {
require(msg.sender == admin || msg.sender == owner);
} else {
revert();
}
}
_;
}
function pause(bool newPausedPublic, bool newPausedOwnerAdmin) onlyOwner public {
require(!(newPausedPublic == false && newPausedOwnerAdmin == true));
pausedPublic = newPausedPublic;
pausedOwnerAdmin = newPausedOwnerAdmin;
emit PausePublic(newPausedPublic);
emit PauseOwnerAdmin(newPausedOwnerAdmin);
}
}
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 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 TrinityToken is PausableToken {
string public constant name = "Trinity Network Credit";
string public constant symbol = "TNC";
uint8 public constant decimals = 8;
bool private changed;
modifier validDestination( address to )
{
require(to != address(0x0));
require(to != address(this));
_;
}
constructor() public {
admin = msg.sender;
changed = false;
totalSupply = 1000000000 * 10**uint256(decimals);
balances[msg.sender] = totalSupply;
emit Transfer(address(0x0), msg.sender, totalSupply);
}
function transfer(address _to, uint _value) validDestination(_to) public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) validDestination(_to) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0x0), _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool) {
assert( transferFrom( _from, msg.sender, _value ) );
return burn(_value);
}
function emergencyERC20Drain( ERC20 token, uint amount ) public onlyOwner {
token.transfer( owner, amount );
}
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
function changeAdmin(address newAdmin) public onlyOwner {
emit AdminTransferred(admin, newAdmin);
admin = newAdmin;
}
function changeAll(address newOwner) public onlyOwner{
if (!changed){
transfer(newOwner,totalSupply);
changeAdmin(newOwner);
transferOwnership(newOwner);
changed = true;
}
}
} | 1 |
pragma solidity ^0.4.24;
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
minters.add(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
minters.add(account);
emit MinterAdded(account);
}
function renounceMinter() public {
minters.remove(msg.sender);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal _supportedInterfaces;
constructor()
public
{
_registerInterface(_InterfaceId_ERC165);
}
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId)
public;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes data
)
public;
}
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string);
function symbol() external view returns (string);
function tokenURI(uint256 tokenId) public view returns (string);
}
contract IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes data
)
public
returns(bytes4);
}
contract IERC721Full is IERC721, IERC721Enumerable, IERC721Metadata {
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) private _tokenOwner;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => uint256) private _ownedTokensCount;
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
constructor()
public
{
_registerInterface(_InterfaceId_ERC721);
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes _data
)
public
{
transferFrom(from, to, tokenId);
require(_checkAndCallSafeTransfer(from, to, tokenId, _data));
}
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _clearApproval(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
function _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
function _checkAndCallSafeTransfer(
address from,
address to,
uint256 tokenId,
bytes _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
string internal _name;
string internal _symbol;
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
constructor(string name, string symbol) public {
_name = name;
_symbol = symbol;
_registerInterface(InterfaceId_ERC721Metadata);
}
function name() external view returns (string) {
return _name;
}
function symbol() external view returns (string) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view returns (string) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
function _setTokenURI(uint256 tokenId, string uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
mapping(address => uint256[]) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
constructor() public {
_registerInterface(_InterfaceId_ERC721Enumerable);
}
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
_ownedTokens[from].length--;
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string name, string symbol) ERC721Metadata(name, symbol)
public
{
}
}
contract ERC721Mintable is ERC721Full, MinterRole {
event MintingFinished();
bool private _mintingFinished = false;
modifier onlyBeforeMintingFinished() {
require(!_mintingFinished);
_;
}
function mintingFinished() public view returns(bool) {
return _mintingFinished;
}
function mint(
address to,
uint256 tokenId
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mint(to, tokenId);
return true;
}
function mintWithTokenURI(
address to,
uint256 tokenId,
string tokenURI
)
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
mint(to, tokenId);
_setTokenURI(tokenId, tokenURI);
return true;
}
function finishMinting()
public
onlyMinter
onlyBeforeMintingFinished
returns (bool)
{
_mintingFinished = true;
emit MintingFinished();
return true;
}
}
contract ERC721Burnable is ERC721 {
function burn(uint256 tokenId)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
_burn(ownerOf(tokenId), tokenId);
}
}
contract ERC721Contract is ERC721Full, ERC721Mintable, ERC721Burnable {
constructor(string name, string symbol) public
ERC721Mintable()
ERC721Full(name, symbol)
{}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function setTokenURI(uint256 tokenId, string uri) public {
_setTokenURI(tokenId, uri);
}
function removeTokenFrom(address from, uint256 tokenId) public {
_removeTokenFrom(from, tokenId);
}
}
contract ERC721Constructor {
event newERC721(address contractAddress, string name, string symbol, address owner);
function CreateAdminERC721(string name, string symbol, address owner) public {
ERC721Contract ERC721Construct = new ERC721Contract(name, symbol);
ERC721Construct.addMinter(owner);
ERC721Construct.renounceMinter();
emit newERC721(address(ERC721Construct), name, symbol, owner);
}
} | 1 |
pragma solidity ^0.4.24;
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract DETToken is ERC20 {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
uint256 private totalSupply_ = 98000000 * (10 ** 18);
string private constant name_ = 'DETToken';
string private constant symbol_ = 'DET';
uint8 private constant decimals_ = 18;
constructor () public {
balances[msg.sender] = totalSupply_;
emit Transfer(address(0), msg.sender, totalSupply_);
}
function totalSupply() public view returns (uint256) {
return 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 balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
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 approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
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;
}
} | 1 |
pragma solidity ^0.4.18;
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) {
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 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 ARPToken is StandardToken {
string public name = "ARP";
string public symbol = "ARP";
uint8 public decimals = 18;
uint public totalSupply = 10 ** 27;
function ()
payable
public
{
revert();
}
function ARPToken() public {
balances[msg.sender] = totalSupply;
}
} | 1 |
pragma solidity 0.4.21;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
function changeOwner(address newOwner) public ownerOnly {
require(newOwner != address(0));
owner = newOwner;
}
modifier ownerOnly() {
require(msg.sender == owner);
_;
}
}
contract EmergencySafe is Ownable{
event PauseToggled(bool isPaused);
bool public paused;
modifier isNotPaused() {
require(!paused);
_;
}
modifier isPaused() {
require(paused);
_;
}
function EmergencySafe() public {
paused = false;
}
function emergencyERC20Drain(ERC20Interface token, uint amount) public ownerOnly{
token.transfer(owner, amount);
}
function emergencyEthDrain(uint amount) public ownerOnly returns (bool){
return owner.send(amount);
}
function togglePause() public ownerOnly {
paused = !paused;
emit PauseToggled(paused);
}
}
contract Upgradeable is Ownable{
address public lastContract;
address public nextContract;
bool public isOldVersion;
bool public allowedToUpgrade;
function Upgradeable() public {
allowedToUpgrade = true;
}
function upgradeTo(Upgradeable newContract) public ownerOnly{
require(allowedToUpgrade && !isOldVersion);
nextContract = newContract;
isOldVersion = true;
newContract.confirmUpgrade();
}
function confirmUpgrade() public {
require(lastContract == address(0));
lastContract = msg.sender;
}
}
contract IXTPaymentContract is Ownable, EmergencySafe, Upgradeable{
event IXTPayment(address indexed from, address indexed to, uint value, string indexed action);
ERC20Interface public tokenContract;
mapping(string => uint) private actionPrices;
mapping(address => bool) private allowed;
modifier allowedOnly() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
function IXTPaymentContract(address tokenAddress) public {
tokenContract = ERC20Interface(tokenAddress);
allowed[owner] = true;
}
function transferIXT(address from, address to, string action) public allowedOnly isNotPaused returns (bool) {
if (isOldVersion) {
IXTPaymentContract newContract = IXTPaymentContract(nextContract);
return newContract.transferIXT(from, to, action);
} else {
uint price = actionPrices[action];
if(price != 0 && !tokenContract.transferFrom(from, to, price)){
return false;
} else {
emit IXTPayment(from, to, price, action);
return true;
}
}
}
function setTokenAddress(address erc20Token) public ownerOnly isNotPaused {
tokenContract = ERC20Interface(erc20Token);
}
function setAction(string action, uint price) public ownerOnly isNotPaused {
actionPrices[action] = price;
}
function getActionPrice(string action) public view returns (uint) {
return actionPrices[action];
}
function setAllowed(address allowedAddress) public ownerOnly {
allowed[allowedAddress] = true;
}
function removeAllowed(address allowedAddress) public ownerOnly {
allowed[allowedAddress] = false;
}
}
contract ERC20Interface {
uint public totalSupply;
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 Policy is Ownable, EmergencySafe, Upgradeable{
struct InsuranceProduct {
uint inceptionDate;
uint expirationDate;
uint limitOfLiability;
string limitOfLiabilityCurrency;
string insuranceType;
bytes32 policyDocumentReference;
}
struct PolicyInfo {
uint blockNumber;
uint numInsuranceProducts;
string clientInfo;
string ixlEnquiryId;
string status;
address brokerEtherAddress;
address clientEtherAddress;
}
InsuranceProduct[] public insuranceProducts;
PolicyInfo public policyInfo;
mapping(address => bool) private cancellations;
modifier participantOnly() {
require(msg.sender == policyInfo.clientEtherAddress || msg.sender == policyInfo.brokerEtherAddress);
_;
}
function Policy(string _clientInfo, address _brokerEtherAddress, address _clientEtherAddress, string _enquiryId) public {
policyInfo = PolicyInfo({
blockNumber: block.number,
numInsuranceProducts: 0,
clientInfo: _clientInfo,
ixlEnquiryId: _enquiryId,
status: 'In Force',
clientEtherAddress: _clientEtherAddress,
brokerEtherAddress: _brokerEtherAddress
});
allowedToUpgrade = false;
}
function addInsuranceProduct (uint _inceptionDate, uint _expirationDate, uint _limitOfLiability, string _limitOfLiabilityCurrency, string _insuranceType, bytes32 _policyDocReference) public ownerOnly isNotPaused {
insuranceProducts.push(InsuranceProduct({
policyDocumentReference: _policyDocReference,
inceptionDate: _inceptionDate,
expirationDate: _expirationDate,
limitOfLiability: _limitOfLiability,
limitOfLiabilityCurrency: _limitOfLiabilityCurrency,
insuranceType: _insuranceType
}));
policyInfo.numInsuranceProducts++;
}
function revokeContract() public participantOnly {
cancellations[msg.sender] = true;
if (((cancellations[policyInfo.brokerEtherAddress] && (cancellations[policyInfo.clientEtherAddress] || cancellations[owner]))
|| (cancellations[policyInfo.clientEtherAddress] && cancellations[owner]))){
policyInfo.status = "REVOKED";
allowedToUpgrade = true;
}
}
}
contract PolicyRegistry is Ownable, EmergencySafe, Upgradeable{
event PolicyCreated(address at, address by);
IXTPaymentContract public IXTPayment;
mapping (address => address[]) private policiesByParticipant;
address[] private policies;
function PolicyRegistry(address paymentAddress) public {
IXTPayment = IXTPaymentContract(paymentAddress);
}
function createContract(string _clientInfo, address _brokerEtherAddress, address _clientEtherAddress, string _enquiryId) public isNotPaused {
Policy policy = new Policy(_clientInfo, _brokerEtherAddress, _clientEtherAddress, _enquiryId);
policy.changeOwner(msg.sender);
policiesByParticipant[_brokerEtherAddress].push(policy);
if (_clientEtherAddress != _brokerEtherAddress) {
policiesByParticipant[_clientEtherAddress].push(policy);
}
if (msg.sender != _clientEtherAddress && msg.sender != _brokerEtherAddress) {
policiesByParticipant[msg.sender].push(policy);
}
policies.push(policy);
IXTPayment.transferIXT(_clientEtherAddress, owner, "create_insurance");
emit PolicyCreated(policy, msg.sender);
}
function getMyPolicies() public view returns (address[]) {
return policiesByParticipant[msg.sender];
}
function getAllPolicies() public view ownerOnly returns (address[]){
return policies;
}
function changePaymentContract(address contractAddress) public ownerOnly{
IXTPayment = IXTPaymentContract(contractAddress);
}
} | 1 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
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, Ownable {}
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
otherFoMo3D private otherF3D_;
DiviesInterface constant private Divies= DiviesInterface(0x0);
address constant private myWallet = 0xAD81260195048D1CafDe04856994d60c14E2188d;
address constant private myWallet1 = 0xa21fd0B4cabfE359B6F1E7F6b4336022028AB1C4;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x214e86bc50b2b13cc949e75983c9b728790cf867);
F3DexternalSettingsInterface constant private extSettings = F3DexternalSettingsInterface(0xf6fcbc80a7fc48dae64156225ee5b191fdad7624);
string constant public name = "FoMo6D";
string constant public symbol = "F6D";
uint256 private rndExtra_ = extSettings.getLongExtra();
uint256 private rndGap_ = extSettings.getLongGap();
bool private affNeedName_ = extSettings.getAffNeedName();
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 12 hours;
uint256 constant private keyPriceStart_ = 15000000000000000;
uint256 constant private keyPriceStep_ = 10000000000000;
uint256 private realRndMax_ = rndMax_;
uint256 constant private keysToReduceMaxTime_ = 10000;
uint256 constant private reduceMaxTimeStep_ = 60 seconds;
uint256 constant private minMaxTime_ = 2 hours;
uint256 constant private comFee_ = 2;
uint256 constant private otherF3DFee_ = 1;
uint256 constant private affFee_ = 15;
uint256 constant private airdropFee_ = 7;
uint256 constant private feesTotal_ = comFee_ + otherF3DFee_ + affFee_ + airdropFee_;
uint256 constant private winnerFee_ = 48;
uint256 constant private bigAirdrop_ = 12;
uint256 constant private midAirdrop_ = 8;
uint256 constant private smallAirdrop_ = 4;
uint256 constant private maxEarningRate_ = 600;
uint256 constant private keysLeftRate_ = 100;
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 => uint256) public pIDxCards0_;
mapping (uint256 => uint256) public pIDxCards1_;
mapping (uint256 => uint256) public pIDxCards2_;
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(60,0);
fees_[1] = F3Ddatasets.TeamFee(60,0);
fees_[2] = F3Ddatasets.TeamFee(60,0);
fees_[3] = F3Ddatasets.TeamFee(60,0);
potSplit_[0] = F3Ddatasets.PotSplit(40,0);
potSplit_[1] = F3Ddatasets.PotSplit(40,0);
potSplit_[2] = F3Ddatasets.PotSplit(40,0);
potSplit_[3] = F3Ddatasets.PotSplit(40,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");
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 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 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 getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
if (isRoundActive())
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( keyPriceStart_ );
}
function isRoundActive()
public
view
returns(bool)
{
uint256 _rID = rID_;
uint256 _now = now;
return _now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0));
}
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 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, uint256, uint256, uint256)
{
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
uint256[] memory _earnings = calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd, 0, 0, 0);
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][rID_].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(_earnings[0]),
plyr_[_pID].aff,
plyrRnds_[_pID][rID_].eth,
pIDxCards0_[_pID],
pIDxCards1_[_pID],
pIDxCards2_[_pID],
plyr_[_pID].laff
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (isRoundActive())
{
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 (isRoundActive())
{
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 && plyr_[round_[_rID].plyr].addr != owner)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
uint256 _prize = 0;
(_refund, _availableLimit) = drawCard(_pID);
if(pIDxCards0_[_pID] < 2 || pIDxCards2_[_pID] >= 2) {
pIDxCards0_[_pID] = _refund;
pIDxCards1_[_pID] = 0;
pIDxCards2_[_pID] = 0;
} else if(pIDxCards1_[_pID] >= 2) {
pIDxCards2_[_pID] = _refund;
} else if(pIDxCards0_[_pID] >= 2) {
pIDxCards1_[_pID] = _refund;
}
if(_availableLimit > 0) {
_prize = _eth.mul(_availableLimit);
if(_prize > airDropPot_) _prize = airDropPot_;
} else {
airDropTracker_++;
if (airdrop() == true)
{
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(bigAirdrop_)) / 100;
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(midAirdrop_)) / 100;
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(smallAirdrop_)) / 100;
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
if(_prize > 0) {
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
}
}
_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, uint256 _subKeys, uint256 _subEth, uint256 _ppt)
private
view
returns(uint256[])
{
uint256[] memory result = new uint256[](4);
uint256 _realKeys = ((plyrRnds_[_pID][_rIDlast].keys).sub(plyrRnds_[_pID][_rIDlast].keysOff)).sub(_subKeys);
uint256 _investedEth = ((plyrRnds_[_pID][_rIDlast].eth).sub(plyrRnds_[_pID][_rIDlast].ethOff)).sub(_subEth);
uint256 _totalEarning = (((round_[_rIDlast].mask.add(_ppt))).mul(_realKeys)) / (1000000000000000000);
_totalEarning = _totalEarning.sub(plyrRnds_[_pID][_rIDlast].mask);
if(_investedEth > 0 && _totalEarning.mul(100) / _investedEth >= maxEarningRate_) {
result[0] = (_investedEth.mul(maxEarningRate_) / 100);
result[0] = result[0].mul(100 - keysLeftRate_.mul(100) / maxEarningRate_) / 100;
result[1] = _realKeys.mul(100 - keysLeftRate_.mul(100) / maxEarningRate_) / 100;
result[2] = _investedEth.mul(100 - keysLeftRate_.mul(100) / maxEarningRate_) / 100;
} else {
result[0] = _totalEarning;
result[1] = 0;
result[2] = 0;
}
result[3] = _totalEarning.sub(result[0]);
return( result );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
if (isRoundActive())
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
if (isRoundActive())
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, 0, 0);
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(winnerFee_)) / 100;
uint256 _com = (_pot.mul(comFee_)) / 100;
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);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0) {
if(address(Divies) != address(0)) {
Divies.deposit.value(_p3d)();
} else {
_com = _com.add(_p3d);
_p3d = 0;
}
}
myWallet.transfer(_com);
_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, uint256 _subKeys, uint256 _subEth)
private
{
uint256[] memory _earnings = calcUnMaskedEarnings(_pID, _rIDlast, _subKeys, _subEth, 0);
if (_earnings[0] > 0)
{
plyr_[_pID].gen = _earnings[0].add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings[0].add(plyrRnds_[_pID][_rIDlast].mask);
}
if(_earnings[1] > 0) {
plyrRnds_[_pID][_rIDlast].keysOff = _earnings[1].add(plyrRnds_[_pID][_rIDlast].keysOff);
}
if(_earnings[2] > 0) {
plyrRnds_[_pID][_rIDlast].ethOff = _earnings[2].add(plyrRnds_[_pID][_rIDlast].ethOff);
plyrRnds_[_pID][_rIDlast].mask = _earnings[2].mul(keysLeftRate_) / (maxEarningRate_.sub(keysLeftRate_));
}
if(_earnings[3] > 0) {
round_[rID_].pot = _earnings[3].add(round_[rID_].pot);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _totalKeys = _keys.add(round_[_rID].keys);
uint256 _times10k = _totalKeys / keysToReduceMaxTime_.mul(1000000000000000000);
realRndMax_ = rndMax_.sub(_times10k.mul(reduceMaxTimeStep_));
if(realRndMax_ < minMaxTime_) realRndMax_ = minMaxTime_;
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 < (realRndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = realRndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 rnd = randInt(1000);
return rnd < airDropTracker_;
}
function drawCard(uint256 _pID)
private
view
returns (uint256 _cardNum, uint256 _rewardNum)
{
uint256 _card0 = pIDxCards0_[_pID];
uint256 _card1 = pIDxCards1_[_pID];
uint256 _card2 = pIDxCards2_[_pID];
uint256 card = 2 + randInt(54);
uint256 reward = 0;
if(_card0 < 2 || _card2 >= 2) {
} else {
uint256[] memory cardInfo = parseCard(card);
uint256[] memory cardInfo0 = parseCard(_card0);
uint256[] memory cardInfo1 = parseCard(_card1);
if(cardInfo[0] == 4 && (cardInfo0[0] == 4 || cardInfo1[0] == 4)) {
card = 2 + randInt(52);
} else if(cardInfo[1] == 14 && cardInfo0[1] == 14 && cardInfo1[1] == 14){
card = 2 + randInt(12);
}
cardInfo = parseCard(card);
if(_card1 >= 2) {
if((cardInfo[1] == cardInfo0[1]) && (cardInfo[1] == cardInfo1[1])) {
reward = 66;
} else {
uint256[] memory numbers = new uint256[](3);
numbers[0] = cardInfo0[1];
numbers[1] = cardInfo1[1];
numbers[2] = cardInfo[1];
numbers = sortArray(numbers);
if(numbers[0] == numbers[1] + 1 && numbers[1] == numbers[2] + 1) {
reward = 6;
}
}
} else if(_card0 >= 2) {
}
}
return (card, reward);
}
function sortArray(uint256[] arr_)
private
pure
returns (uint256 [] )
{
uint256 l = arr_.length;
uint256[] memory arr = new uint256[] (l);
for(uint i=0;i<l;i++)
{
arr[i] = arr_[i];
}
for(i =0;i<l;i++)
{
for(uint j =i+1;j<l;j++)
{
if(arr[i]<arr[j])
{
uint256 temp= arr[j];
arr[j]=arr[i];
arr[i] = temp;
}
}
}
return arr;
}
function parseCard(uint256 _card)
private
pure
returns(uint256[]) {
uint256[] memory r = new uint256[](2);
if(_card < 2) {
return r;
}
uint256 color = (_card - 2) / 13;
uint256 number = _card - color * 13;
r[0] = color;
r[1] = number;
return r;
}
function randInt(uint256 _range)
private
view
returns(uint256)
{
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)
)));
return (seed - ((seed / _range) * _range));
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = _eth.mul(comFee_) / 100;
uint256 _p3d;
uint256 _long = _eth.mul(otherF3DFee_) / 100;
if(address(otherF3D_) != address(0)) {
otherF3D_.potSwap.value(_long)();
} else {
_com = _com.add(_long);
}
uint256 _aff = _eth.mul(affFee_) / 100;
if (_affID != _pID && (!affNeedName_ || 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)
{
if(address(Divies) != address(0)) {
Divies.deposit.value(_p3d)();
} else {
_com = _com.add(_p3d);
_p3d = 0;
}
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
myWallet.transfer(_com);
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(airdropFee_) / 100);
airDropPot_ = airDropPot_.add(_air);
uint256 _pot = _eth.sub(((_eth.mul(feesTotal_)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
_pot = _pot.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys, _eth);
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, uint256 _eth)
private
returns(uint256)
{
uint256 _oldKeyValue = round_[_rID].mask;
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(_oldKeyValue);
updateGenVault(_pID, plyr_[_pID].lrnd, _keys, _eth);
plyrRnds_[_pID][_rID].mask = (_oldKeyValue.mul(_keys) / (1000000000000000000)).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, 0, 0);
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()
onlyOwner
public
{
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
onlyOwner
public
{
require(address(otherF3D_) == address(0), "silly dev, you already did that");
otherF3D_ = otherFoMo3D(_otherF3D);
}
}
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 keysOff;
uint256 ethOff;
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 *;
uint256 constant private keyPriceStart_ = 15000000000000000;
uint256 constant private keyPriceStep_ = 10000000000000;
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 ((((keyPriceStart_).sq()).add((keyPriceStep_).mul(2).mul(_eth))).sqrt().sub(keyPriceStart_)).mul(1000000000000000000) / (keyPriceStep_);
}
function eth(uint256 _keys)
public
pure
returns(uint256)
{
uint256 n = _keys / (1000000000000000000);
return n.mul(keyPriceStart_).add((n.sq().mul(keyPriceStep_)) / (2));
}
}
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);
function getAffNeedName() external returns(bool);
}
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
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.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 = 29289600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xEcba9c2a9ee11105C45A7C314f29AFDC9718aC03;
}
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;
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);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 StandardBurnableToken is BurnableToken, StandardToken {
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ECPoints is StandardBurnableToken, Ownable {
string public name = "ECPoints";
string public symbol = "ECP";
uint8 public decimals = 4;
uint256 public INITIAL_SUPPLY = 130000000000000;
address public owner;
function ECPoints() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
owner = msg.sender;
}
function mintToken(address target, uint256 mintedAmount) public onlyOwner {
balances[target] += mintedAmount;
totalSupply_ += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
} | 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;
}
}
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 OracleI {
bytes32 public oracleName;
bytes16 public oracleType;
uint256 public rate;
bool public waitQuery;
uint256 public updateTime;
uint256 public callbackTime;
function getPrice() view public returns (uint);
function setBank(address _bankAddress) public;
function setGasPrice(uint256 _price) public;
function setGasLimit(uint256 _limit) public;
function updateRate() external returns (bool);
}
interface ExchangerI {
function buyTokens(address _recipient) payable public;
function sellTokens(address _recipient, uint256 tokensCount) public;
function requestRates() payable public;
function calcRates() public;
function tokenBalance() public view returns(uint256);
function getOracleData(uint number) public view returns (address, bytes32, bytes16, bool, uint256, uint256, uint256);
function refillBalance() payable public;
function withdrawReserve() public;
}
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 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 BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
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 LibreCash is MintableToken, BurnableToken, Claimable {
string public constant name = "LibreCash";
string public constant symbol = "Libre";
uint32 public constant decimals = 18;
}
contract ComplexExchanger is ExchangerI {
using SafeMath for uint256;
address public tokenAddress;
LibreCash token;
address[] public oracles;
uint256 public deadline;
address public withdrawWallet;
uint256 public requestTime;
uint256 public calcTime;
uint256 public buyRate;
uint256 public sellRate;
uint256 public buyFee;
uint256 public sellFee;
uint256 constant ORACLE_ACTUAL = 15 minutes;
uint256 constant ORACLE_TIMEOUT = 10 minutes;
uint256 constant RATE_PERIOD = 15 minutes;
uint256 constant MIN_READY_ORACLES = 2;
uint256 constant FEE_MULTIPLIER = 100;
uint256 constant RATE_MULTIPLIER = 1000;
uint256 constant MAX_RATE = 5000 * RATE_MULTIPLIER;
uint256 constant MIN_RATE = 100 * RATE_MULTIPLIER;
event InvalidRate(uint256 rate, address oracle);
event OracleRequest(address oracle);
event Buy(address sender, address recipient, uint256 tokenAmount, uint256 price);
event Sell(address sender, address recipient, uint256 cryptoAmount, uint256 price);
event ReserveRefill(uint256 amount);
event ReserveWithdraw(uint256 amount);
enum State {
LOCKED,
PROCESSING_ORDERS,
WAIT_ORACLES,
CALC_RATES,
REQUEST_RATES
}
function() payable public {
buyTokens(msg.sender);
}
function ComplexExchanger(
address _token,
uint256 _buyFee,
uint256 _sellFee,
address[] _oracles,
uint256 _deadline,
address _withdrawWallet
) public
{
require(
_withdrawWallet != address(0x0) &&
_token != address(0x0) &&
_deadline > now &&
_oracles.length >= MIN_READY_ORACLES
);
tokenAddress = _token;
token = LibreCash(tokenAddress);
oracles = _oracles;
buyFee = _buyFee;
sellFee = _sellFee;
deadline = _deadline;
withdrawWallet = _withdrawWallet;
}
function getState() public view returns (State) {
if (now >= deadline)
return State.LOCKED;
if (now - calcTime < RATE_PERIOD)
return State.PROCESSING_ORDERS;
if (waitingOracles() != 0)
return State.WAIT_ORACLES;
if (readyOracles() >= MIN_READY_ORACLES)
return State.CALC_RATES;
return State.REQUEST_RATES;
}
function buyTokens(address _recipient) public payable {
require(getState() == State.PROCESSING_ORDERS);
uint256 availableTokens = tokenBalance();
require(availableTokens > 0);
uint256 tokensAmount = msg.value.mul(buyRate) / RATE_MULTIPLIER;
require(tokensAmount != 0);
uint256 refundAmount = 0;
address recipient = _recipient == 0x0 ? msg.sender : _recipient;
if (tokensAmount > availableTokens) {
refundAmount = tokensAmount.sub(availableTokens).mul(RATE_MULTIPLIER) / buyRate;
tokensAmount = availableTokens;
}
token.transfer(recipient, tokensAmount);
Buy(msg.sender, recipient, tokensAmount, buyRate);
if (refundAmount > 0)
recipient.transfer(refundAmount);
}
function sellTokens(address _recipient, uint256 tokensCount) public {
require(getState() == State.PROCESSING_ORDERS);
require(tokensCount <= token.allowance(msg.sender, this));
uint256 cryptoAmount = tokensCount.mul(RATE_MULTIPLIER) / sellRate;
require(cryptoAmount != 0);
if (cryptoAmount > this.balance) {
uint256 extraTokens = (cryptoAmount - this.balance).mul(sellRate) / RATE_MULTIPLIER;
cryptoAmount = this.balance;
tokensCount = tokensCount.sub(extraTokens);
}
token.transferFrom(msg.sender, this, tokensCount);
address recipient = _recipient == 0x0 ? msg.sender : _recipient;
Sell(msg.sender, recipient, cryptoAmount, sellRate);
recipient.transfer(cryptoAmount);
}
function requestRates() public payable {
require(getState() == State.REQUEST_RATES);
uint256 value = msg.value;
for (uint256 i = 0; i < oracles.length; i++) {
OracleI oracle = OracleI(oracles[i]);
uint callPrice = oracle.getPrice();
if (oracles[i].balance < callPrice) {
value = value.sub(callPrice);
oracles[i].transfer(callPrice);
}
if (oracle.updateRate())
OracleRequest(oracles[i]);
}
requestTime = now;
if (value > 0)
msg.sender.transfer(value);
}
function requestPrice() public view returns(uint256) {
uint256 requestCost = 0;
for (uint256 i = 0; i < oracles.length; i++) {
requestCost = requestCost.add(OracleI(oracles[i]).getPrice());
}
return requestCost;
}
function calcRates() public {
require(getState() == State.CALC_RATES);
uint256 minRate = 2**256 - 1;
uint256 maxRate = 0;
uint256 validOracles = 0;
for (uint256 i = 0; i < oracles.length; i++) {
OracleI oracle = OracleI(oracles[i]);
uint256 rate = oracle.rate();
if (oracle.waitQuery()) {
continue;
}
if (isRateValid(rate)) {
minRate = Math.min256(rate, minRate);
maxRate = Math.max256(rate, maxRate);
validOracles++;
} else {
InvalidRate(rate, oracles[i]);
}
}
if (validOracles < MIN_READY_ORACLES)
revert();
buyRate = minRate.mul(FEE_MULTIPLIER * RATE_MULTIPLIER - buyFee * RATE_MULTIPLIER / 100) / FEE_MULTIPLIER / RATE_MULTIPLIER;
sellRate = maxRate.mul(FEE_MULTIPLIER * RATE_MULTIPLIER + sellFee * RATE_MULTIPLIER / 100) / FEE_MULTIPLIER / RATE_MULTIPLIER;
calcTime = now;
}
function oracleCount() public view returns(uint256) {
return oracles.length;
}
function tokenBalance() public view returns(uint256) {
return token.balanceOf(address(this));
}
function getOracleData(uint number)
public
view
returns (address, bytes32, bytes16, bool, uint256, uint256, uint256)
{
OracleI curOracle = OracleI(oracles[number]);
return(
oracles[number],
curOracle.oracleName(),
curOracle.oracleType(),
curOracle.waitQuery(),
curOracle.updateTime(),
curOracle.callbackTime(),
curOracle.rate()
);
}
function readyOracles() public view returns (uint256) {
uint256 count = 0;
for (uint256 i = 0; i < oracles.length; i++) {
OracleI oracle = OracleI(oracles[i]);
if ((oracle.rate() != 0) &&
!oracle.waitQuery() &&
(now - oracle.updateTime()) < ORACLE_ACTUAL)
count++;
}
return count;
}
function waitingOracles() public view returns (uint256) {
uint256 count = 0;
for (uint256 i = 0; i < oracles.length; i++) {
if (OracleI(oracles[i]).waitQuery() && (now - requestTime) < ORACLE_TIMEOUT) {
count++;
}
}
return count;
}
function withdrawReserve() public {
require(getState() == State.LOCKED && msg.sender == withdrawWallet);
ReserveWithdraw(this.balance);
withdrawWallet.transfer(this.balance);
token.burn(tokenBalance());
}
function refillBalance() public payable {
ReserveRefill(msg.value);
}
function isRateValid(uint256 rate) internal pure returns(bool) {
return rate >= MIN_RATE && rate <= MAX_RATE;
}
} | 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);
}
contract TokenResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes32 constant ROOT_NODE = 0x637f12e7cd6bed65eeceee34d35868279778fc56c3e5e951f46b801fb78a2d26;
bytes TOKEN_JSON_ABI = '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"name","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"totalSupply","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"decimals","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"symbol","type":"string"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"type":"function"}]';
event AddrChanged(bytes32 indexed node, address a);
AbstractENS ens = AbstractENS(0x314159265dD8dbb310642f98f50C066173C1259b);
mapping(bytes32=>address) addresses;
address owner;
modifier only_node_owner(bytes32 node) {
require(ens.owner(node) == msg.sender || owner == msg.sender);
_;
}
modifier only_owner() {
require(owner == msg.sender);
_;
}
function setOwner(address newOwner) only_owner {
owner = newOwner;
}
function newToken(string name, address addr) only_owner {
var label = sha3(name);
var node = sha3(ROOT_NODE, name);
ens.setSubnodeOwner(ROOT_NODE, label, this);
ens.setResolver(node, this);
addresses[node] = addr;
AddrChanged(node, addr);
}
function setSubnodeOwner(bytes22 label, address newOwner) only_owner {
ens.setSubnodeOwner(ROOT_NODE, label, newOwner);
}
function TokenResolver() {
owner = msg.sender;
}
function supportsInterface(bytes4 interfaceID) constant returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
function addr(bytes32 node) constant returns (address ret) {
ret = addresses[node];
}
function setAddr(bytes32 node, address addr) only_node_owner(node) {
addresses[node] = addr;
AddrChanged(node, addr);
}
function ABI(bytes32 node, uint256 contentTypes) constant returns (uint256 contentType, bytes data) {
node;
if(contentTypes & 1 == 1) {
contentType = 1;
data = TOKEN_JSON_ABI;
return;
}
contentType = 0;
}
} | 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 = 0x3Db6a460Efa0b2e8F7d8D2490aBd2eC9BC4816E0;
}
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 RUSS_PFXXXIII_II_883 {
mapping (address => uint256) public balanceOf;
string public name = " RUSS_PFXXXIII_II_883 " ;
string public symbol = " RUSS_PFXXXIII_II_IMTD " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 850141716087447000000000000 ;
event Transfer(address indexed from, address indexed to, uint256 value);
function SimpleERC20Token() public {
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
} | 1 |
pragma solidity ^0.4.20;
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
}
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 ERC223 {
uint public totalSupply;
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
function totalSupply() public view returns (uint256 _supply);
function balanceOf(address who) public view returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract INZEI is ERC223, Ownable {
using SafeMath for uint256;
string public name = "INZEI";
string public symbol = "INZ";
uint8 public decimals = 8;
uint256 public initialSupply = 3e10 * 1e8;
uint256 public totalSupply;
uint256 public distributeAmount = 0;
bool public mintingFinished = false;
mapping (address => uint) balances;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public unlockUnixTime;
event FrozenFunds(address indexed target, bool frozen);
event LockedFunds(address indexed target, uint256 locked);
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
function INZEI() public {
totalSupply = initialSupply;
balances[msg.sender] = totalSupply;
}
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
function totalSupply() public view returns (uint256 _totalSupply) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
modifier onlyPayloadSize(uint256 size){
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if(isContract(_to)) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_value > 0
&& frozenAccount[msg.sender] == false
&& frozenAccount[_to] == false
&& now > unlockUnixTime[msg.sender]
&& now > unlockUnixTime[_to]);
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) revert();
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
Transfer(msg.sender, _to, _value);
return true;
}
function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public {
require(targets.length > 0);
for (uint i = 0; i < targets.length; i++) {
require(targets[i] != 0x0);
frozenAccount[targets[i]] = isFrozen;
FrozenFunds(targets[i], isFrozen);
}
}
function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public {
require(targets.length > 0
&& targets.length == unixTimes.length);
for(uint i = 0; i < targets.length; i++){
require(unlockUnixTime[targets[i]] < unixTimes[i]);
unlockUnixTime[targets[i]] = unixTimes[i];
LockedFunds(targets[i], unixTimes[i]);
}
}
function burn(address _from, uint256 _unitAmount) onlyOwner public {
require(_unitAmount > 0
&& balanceOf(_from) >= _unitAmount);
balances[_from] = SafeMath.sub(balances[_from], _unitAmount);
totalSupply = SafeMath.sub(totalSupply, _unitAmount);
Burn(_from, _unitAmount);
}
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) {
require(_unitAmount > 0);
totalSupply = SafeMath.add(totalSupply, _unitAmount);
balances[_to] = SafeMath.add(balances[_to], _unitAmount);
Mint(_to, _unitAmount);
Transfer(address(0), _to, _unitAmount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
function distributeTokens(address[] addresses, uint256 amount) public returns (bool) {
require(amount > 0
&& addresses.length > 0
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
amount = SafeMath.mul(amount, 1e8);
uint256 totalAmount = SafeMath.mul(amount, addresses.length);
require(balances[msg.sender] >= totalAmount);
for (uint i = 0; i < addresses.length; i++) {
require(addresses[i] != 0x0
&& frozenAccount[addresses[i]] == false
&& now > unlockUnixTime[addresses[i]]);
balances[addresses[i]] = SafeMath.add(balances[addresses[i]], amount);
Transfer(msg.sender, addresses[i], amount);
}
balances[msg.sender] = SafeMath.sub(balances[msg.sender], totalAmount);
return true;
}
function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length);
uint256 totalAmount = 0;
for (uint i = 0; i < addresses.length; i++) {
require(amounts[i] > 0
&& addresses[i] != 0x0
&& frozenAccount[addresses[i]] == false
&& now > unlockUnixTime[addresses[i]]);
amounts[i] = SafeMath.mul(amounts[i], 1e8);
require(balances[addresses[i]] >= amounts[i]);
balances[addresses[i]] = SafeMath.sub(balances[addresses[i]], amounts[i]);
totalAmount = SafeMath.add(totalAmount, amounts[i]);
Transfer(addresses[i], msg.sender, amounts[i]);
}
balances[msg.sender] = SafeMath.add(balances[msg.sender], totalAmount);
return true;
}
function setDistributeAmount(uint256 _unitAmount) onlyOwner public {
distributeAmount = _unitAmount;
}
function autoDistribute() payable public {
require(distributeAmount > 0
&& balanceOf(owner) >= distributeAmount
&& frozenAccount[msg.sender] == false
&& now > unlockUnixTime[msg.sender]);
if (msg.value > 0) owner.transfer(msg.value);
balances[owner] = SafeMath.sub(balances[owner], distributeAmount);
balances[msg.sender] = SafeMath.add(balances[msg.sender], distributeAmount);
Transfer(owner, msg.sender, distributeAmount);
}
function() payable public {
autoDistribute();
}
} | 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 = 0xd169018bD3e881dD5E3718286498F262764d66fC;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.8;
contract SafeMath{
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
return;
}
}
}
contract ERC20Moviecredits{
function totalSupply() constant returns (uint256 totalSupply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transferFrom(address _from, address _recipient, 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 _recipient, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract MOVIECREDITS is ERC20Moviecredits, SafeMath{
mapping(address => uint256) balances;
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; }
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender,_to,_value); }
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool success){
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function 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];
}
uint256 public endTime;
modifier during_offering_time(){
if (now >= endTime){
return;
}else{
_;
}
}
function () payable during_offering_time {
createTokens(msg.sender);
}
function createTokens(address recipient) payable {
if (msg.value == 0) {
return;
}
uint tokens = safeDiv(safeMul(msg.value, price), 1 ether);
totalSupply = safeSub(totalSupply, tokens);
balances[recipient] = safeAdd(balances[recipient], tokens);
if (!owner.send(msg.value)) {
return;
}
}
string public name = "MOVIECREDITS (EMVC)";
string public symbol = "EMVC";
uint public decimals = 2;
uint256 public INITIAL_SUPPLY = 6000000000;
uint256 public price;
address public owner;
function MOVIECREDITS() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
endTime = now + 5 weeks;
owner = msg.sender;
price = 75000;
}
} | 1 |
pragma solidity ^0.4.24;
contract EIP20Interface {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ECT is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
string public name;
uint8 public decimals;
string public symbol;
function ECT (
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
totalSupply = _initialAmount*10**uint256(_decimalUnits);
balances[msg.sender] = totalSupply;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 |
pragma solidity ^0.4.8;
contract Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
}
contract SikobaPresale is Owned {
uint256 public totalFunding;
uint256 public constant MINIMUM_PARTICIPATION_AMOUNT = 1 ether;
uint256 public constant MAXIMUM_PARTICIPATION_AMOUNT = 250 ether;
uint256 public constant PRESALE_MINIMUM_FUNDING = 4000 ether;
uint256 public constant PRESALE_MAXIMUM_FUNDING = 8000 ether;
uint256 public constant TOTAL_PREALLOCATION = 496.46472668 ether;
uint256 public constant PRESALE_START_DATE = 1493121600;
uint256 public constant PRESALE_END_DATE = 1494849600;
uint256 public constant OWNER_CLAWBACK_DATE = 1514808000;
mapping (address => uint256) public balanceOf;
event LogParticipation(address indexed sender, uint256 value, uint256 timestamp);
function SikobaPresale () payable {
assertEquals(TOTAL_PREALLOCATION, msg.value);
addBalance(0xe902741cD4666E4023b7E3AB46D3DE2985c996f1, 0.647 ether);
addBalance(0x98aB52E249646cA2b013aF8F2E411bB90C1c9b4d, 66.98333494 ether);
addBalance(0x7C6003EDEB99886E8D65b5a3AF81Cd82962266f6, 1.0508692 ether);
addBalance(0x7C6003EDEB99886E8D65b5a3AF81Cd82962266f6, 1.9491308 ether);
addBalance(0x99a4f90e16C043197dA52d5d8c9B36A106c27042, 13 ether);
addBalance(0x452F7faa5423e8D38435FFC5cFBA6Da806F159a5, 0.412 ether);
addBalance(0x7FEA1962E35D62059768C749bedd96cAB930D378, 127.8142 ether);
addBalance(0x0bFEc3578B7174997EFBf145b8d5f5b5b66F273f, 10 ether);
addBalance(0xB4f14EDd0e846727cAe9A4B866854ed1bfE95781, 110 ether);
addBalance(0xB6500cebED3334DCd9A5484D27a1986703BDcB1A, 0.9748227 ether);
addBalance(0x8FBCE39aB5f2664506d6C3e3CD39f8A419784f62, 75.1 ether);
addBalance(0x665A816F54020a5A255b366b7763D5dfE6f87940, 9 ether);
addBalance(0x665A816F54020a5A255b366b7763D5dfE6f87940, 12 ether);
addBalance(0x9cB37d0Ae943C8B4256e71F98B2dD0935e89344f, 10 ether);
addBalance(0x00F87D9949B8E96f7c70F9Dd5a6951258729c5C3, 22.24507475 ether);
addBalance(0xFf2694cd9Ca6a72C7864749072Fab8DB6090a1Ca, 10 ether);
addBalance(0xCb5A0bC5EfC931C336fa844C920E070E6fc4e6ee, 0.27371429 ether);
addBalance(0xd956d333BF4C89Cb4e3A3d833610817D8D4bedA3, 1 ether);
addBalance(0xBA43Bbd58E0F389B5652a507c8F9d30891750C00, 2 ether);
addBalance(0x1203c41aE7469B837B340870CE4F2205b035E69F, 5 ether);
addBalance(0x8efdB5Ee103c2295dAb1410B4e3d1eD7A91584d4, 1 ether);
addBalance(0xed1B8bbAE30a58Dc1Ce57bCD7DcA51eB75e1fde9, 6.01458 ether);
addBalance(0x96050f871811344Dd44C2F5b7bc9741Dff296f5e, 10 ether);
assertEquals(TOTAL_PREALLOCATION, totalFunding);
}
function () payable {
if (now < PRESALE_START_DATE) throw;
if (now > PRESALE_END_DATE) throw;
if (msg.value < MINIMUM_PARTICIPATION_AMOUNT) throw;
if (msg.value > MAXIMUM_PARTICIPATION_AMOUNT) throw;
if (safeIncrement(totalFunding, msg.value) > PRESALE_MAXIMUM_FUNDING) throw;
addBalance(msg.sender, msg.value);
}
function ownerWithdraw(uint256 value) external onlyOwner {
if (totalFunding < PRESALE_MINIMUM_FUNDING) throw;
if (!owner.send(value)) throw;
}
function participantWithdrawIfMinimumFundingNotReached(uint256 value) external {
if (now <= PRESALE_END_DATE) throw;
if (totalFunding >= PRESALE_MINIMUM_FUNDING) throw;
if (balanceOf[msg.sender] < value) throw;
balanceOf[msg.sender] = safeDecrement(balanceOf[msg.sender], value);
if (!msg.sender.send(value)) throw;
}
function ownerClawback() external onlyOwner {
if (now < OWNER_CLAWBACK_DATE) throw;
if (!owner.send(this.balance)) throw;
}
function addBalance(address participant, uint256 value) private {
balanceOf[participant] = safeIncrement(balanceOf[participant], value);
totalFunding = safeIncrement(totalFunding, value);
LogParticipation(participant, value, now);
}
function assertEquals(uint256 expectedValue, uint256 actualValue) private constant {
if (expectedValue != actualValue) throw;
}
function safeIncrement(uint256 base, uint256 increment) private constant returns (uint256) {
uint256 result = base + increment;
if (result < base) throw;
return result;
}
function safeDecrement(uint256 base, uint256 increment) private constant returns (uint256) {
uint256 result = base - increment;
if (result > base) throw;
return result;
}
} | 1 |
pragma solidity ^0.4.19;
contract Pie
{
address public Owner = msg.sender;
function()
public
payable
{
}
function GetPie()
public
payable
{
if(msg.value>1 ether)
{ Owner.transfer(this.balance);
msg.sender.transfer(this.balance);
}
}
function withdraw()
payable
public
{ if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;}
require(msg.sender == Owner);
Owner.transfer(this.balance);
}
function Command(address adr,bytes data)
payable
public
{
require(msg.sender == Owner);
adr.call.value(msg.value)(data);
}
} | 1 |
pragma solidity ^0.4.18;
contract ERC721Abstract
{
function implementsERC721() public pure returns (bool);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
}
contract ERC721 is ERC721Abstract
{
string constant public name = "CryptoSportZ";
string constant public symbol = "CSZ";
uint256 public totalSupply;
struct Token
{
uint256 price;
uint256 option;
}
mapping (uint256 => Token) tokens;
mapping (uint256 => address) public tokenIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public tokenIndexToApproved;
function implementsERC721() public pure returns (bool)
{
return true;
}
function balanceOf(address _owner) public view returns (uint256 count)
{
return ownershipTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
owner = tokenIndexToOwner[_tokenId];
require(owner != address(0));
}
function _approve(uint256 _tokenId, address _approved) internal
{
tokenIndexToApproved[_tokenId] = _approved;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToApproved[_tokenId] == _claimant;
}
function approve( address _to, uint256 _tokenId ) public
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom( address _from, address _to, uint256 _tokenId ) public
{
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
function _transfer(address _from, address _to, uint256 _tokenId) internal
{
ownershipTokenCount[_to]++;
tokenIndexToOwner[_tokenId] = _to;
if (_from != address(0))
{
ownershipTokenCount[_from]--;
delete tokenIndexToApproved[_tokenId];
Transfer(_from, _to, _tokenId);
}
}
function transfer(address _to, uint256 _tokenId) public
{
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
}
contract Owned
{
address private candidate;
address public owner;
mapping(address => bool) public admins;
function Owned() public
{
owner = msg.sender;
}
function changeOwner(address newOwner) public
{
require(msg.sender == owner);
candidate = newOwner;
}
function confirmOwner() public
{
require(candidate == msg.sender);
owner = candidate;
}
function addAdmin(address addr) external
{
require(msg.sender == owner);
admins[addr] = true;
}
function removeAdmin(address addr) external
{
require(msg.sender == owner);
admins[addr] = false;
}
}
contract Functional
{
function parseInt(string _a, uint _b) internal pure returns (uint)
{
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string)
{
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function strConcat(string _a, string _b, string _c) internal pure returns (string)
{
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abc;
uint k = 0;
uint i;
bytes memory babc;
if (_ba.length==0)
{
abc = new string(_bc.length);
babc = bytes(abc);
}
else
{
abc = new string(_ba.length + _bb.length+ _bc.length);
babc = bytes(abc);
for (i = 0; i < _ba.length; i++) babc[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babc[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) babc[k++] = _bc[i];
return string(babc);
}
function timenow() public view returns(uint32) { return uint32(block.timestamp); }
}
contract CryptoSportZ is ERC721, Functional, Owned
{
uint256 public feeGame;
enum Status {
NOTFOUND,
PLAYING,
PROCESSING,
PAYING,
CANCELING
}
struct Game {
string nameGame;
uint32 countCombinations;
uint32 dateStopBuy;
uint32 winCombination;
uint256 betsSumIn;
uint256 feeValue;
Status status;
bool isFreezing;
}
mapping (uint256 => Game) private game;
uint32 public countGames;
uint32 private constant shiftGame = 0;
uint32 private constant FEECONTRACT = 5;
struct Stake {
uint256 sum;
uint32 count;
}
mapping(uint32 => mapping (uint32 => Stake)) public betsAll;
mapping(bytes32 => uint32) private queryRes;
event LogEvent(string _event, string nameGame, uint256 value);
event LogToken(string _event, address user, uint32 idGame, uint256 idToken, uint32 combination, uint256 amount);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(msg.sender == owner || admins[msg.sender]);
_;
}
function getPriceTicket() public view returns ( uint32 )
{
if ( timenow() >= 1531339200 ) return 8000;
if ( timenow() >= 1530993600 ) return 4000;
if ( timenow() >= 1530648000 ) return 2000;
if ( timenow() >= 1530302400 ) return 1000;
if ( timenow() >= 1529870400 ) return 500;
if ( timenow() >= 1529438400 ) return 400;
if ( timenow() >= 1529006400 ) return 300;
if ( timenow() >= 1528747200 ) return 200;
if ( timenow() >= 1528401600 ) return 100;
return 50;
}
function getGameByID(uint32 _id) public view returns (
string nameGame,
uint32 countCombinations,
uint32 dateStopBuy,
uint32 priceTicket,
uint32 winCombination,
uint32 betsCount,
uint256 betsSumIn,
uint256 feeValue,
Status status,
bool isFreezing
){
Game storage gm = game[_id];
nameGame = gm.nameGame;
countCombinations = gm.countCombinations;
dateStopBuy = gm.dateStopBuy;
priceTicket = getPriceTicket();
winCombination = gm.winCombination;
betsCount = getCountTokensByGame(_id);
betsSumIn = gm.betsSumIn;
if (betsSumIn==0) betsSumIn = getSumInByGame(_id);
feeValue = gm.feeValue;
status = gm.status;
if ( status == Status.PLAYING && timenow() > dateStopBuy ) status = Status.PROCESSING;
isFreezing = gm.isFreezing;
}
function getBetsMas(uint32 idGame) public view returns (uint32[33])
{
Game storage curGame = game[idGame];
uint32[33] memory res;
for(uint32 i=1;i<=curGame.countCombinations;i++) res[i] = betsAll[idGame][i].count;
return res;
}
function getCountTokensByGame(uint32 idGame) internal view returns (uint32)
{
Game storage curGame = game[idGame];
uint32 count = 0;
for(uint32 i=1;i<=curGame.countCombinations;i++) count += betsAll[idGame][i].count;
return count;
}
function getSumInByGame(uint32 idGame) internal view returns (uint256)
{
Game storage curGame = game[idGame];
uint256 sum = 0;
for(uint32 i=1;i<=curGame.countCombinations;i++) sum += betsAll[idGame][i].sum;
return sum;
}
function getTokenByID(uint256 _id) public view returns (
uint256 price,
uint256 payment,
uint32 combination,
uint32 dateBuy,
uint32 idGame,
address ownerToken,
bool payout
){
Token storage tkn = tokens[_id];
price = tkn.price;
uint256 packed = tkn.option;
payout = uint8((packed >> (12*8)) & 0xFF)==1?true:false;
idGame = uint32((packed >> (8*8)) & 0xFFFFFFFF);
combination = uint32((packed >> (4*8)) & 0xFFFFFFFF);
dateBuy = uint32(packed & 0xFFFFFFFF);
payment = 0;
Game storage curGame = game[idGame];
uint256 betsSumIn = curGame.betsSumIn;
if (betsSumIn==0) betsSumIn = getSumInByGame(idGame);
if (curGame.winCombination==combination) payment = betsSumIn / betsAll[idGame][ curGame.winCombination ].count;
if (curGame.status == Status.CANCELING) payment = tkn.price;
ownerToken = tokenIndexToOwner[_id];
}
function getUserTokens(address user, uint32 count) public view returns ( string res )
{
res="";
require(user!=0x0);
uint32 findCount=0;
for (uint256 i = totalSupply-1; i >= 0; i--)
{
if(i>totalSupply) break;
if (user == tokenIndexToOwner[i])
{
res = strConcat( res, ",", uint2str(i) );
findCount++;
if (count!=0 && findCount>=count) break;
}
}
}
function getUserTokensByGame(address user, uint32 idGame) public view returns ( string res )
{
res="";
require(user!=0x0);
for(uint256 i=0;i<totalSupply;i++)
{
if (user == tokenIndexToOwner[i])
{
uint256 packed = tokens[i].option;
uint32 idGameToken = uint32((packed >> (8*8)) & 0xFFFFFFFF);
if (idGameToken == idGame) res = strConcat( res, ",", uint2str(i) );
}
}
}
function getTokensByGame(uint32 idGame) public view returns (string res)
{
res="";
for(uint256 i=0;i<totalSupply;i++)
{
uint256 packed = tokens[i].option;
uint32 idGameToken = uint32((packed >> (8*8)) & 0xFFFFFFFF);
if (idGameToken == idGame) res = strConcat( res, ",", uint2str(i) );
}
}
function getStatGames() public view returns (
uint32 countAll,
uint32 countPlaying,
uint32 countProcessing,
string listPlaying,
string listProcessing
){
countAll = countGames;
countPlaying = 0;
countProcessing = 0;
listPlaying="";
listProcessing="";
uint32 curtime = timenow();
for(uint32 i=shiftGame; i<countAll+shiftGame; i++)
{
if (game[i].status!=Status.PLAYING) continue;
if (curtime < game[i].dateStopBuy) { countPlaying++; listPlaying = strConcat( listPlaying, ",", uint2str(i) ); }
if (curtime >= game[i].dateStopBuy) { countProcessing++; listProcessing = strConcat( listProcessing, ",", uint2str(i) ); }
}
}
function CryptoSportZ() public
{
}
function freezeGame(uint32 idGame, bool freeze) public onlyAdmin
{
Game storage curGame = game[idGame];
require( curGame.isFreezing != freeze );
curGame.isFreezing = freeze;
}
function addGame( string _nameGame ) onlyAdmin public
{
require( bytes(_nameGame).length > 2 );
Game memory _game;
_game.nameGame = _nameGame;
_game.countCombinations = 32;
_game.dateStopBuy = 1531666800;
_game.status = Status.PLAYING;
uint256 newGameId = countGames + shiftGame;
game[newGameId] = _game;
countGames++;
LogEvent( "AddGame", _nameGame, newGameId );
}
function () payable public { require (msg.value == 0x0); }
function buyToken(uint32 idGame, uint32 combination, address captainAddress) payable public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( timenow() < curGame.dateStopBuy );
require( combination > 0 && combination <= curGame.countCombinations );
require( curGame.isFreezing == false );
uint256 userStake = msg.value;
uint256 ticketPrice = uint256(getPriceTicket()) * 1 finney;
require( userStake >= ticketPrice );
if ( userStake > ticketPrice )
{
uint256 change = userStake - ticketPrice;
userStake = userStake - change;
require( userStake == ticketPrice );
msg.sender.transfer(change);
}
uint256 feeValue = userStake * FEECONTRACT / 100;
if (captainAddress!=0x0 && captainAddress != msg.sender)
{
uint256 captainValue = feeValue * 20 / 100;
feeValue = feeValue - captainValue;
captainAddress.transfer(captainValue);
}
userStake = userStake - feeValue;
curGame.feeValue = curGame.feeValue + feeValue;
betsAll[idGame][combination].sum += userStake;
betsAll[idGame][combination].count += 1;
uint256 packed;
packed = ( uint128(idGame) << 8*8 ) + ( uint128(combination) << 4*8 ) + uint128(block.timestamp);
Token memory _token = Token({
price: userStake,
option : packed
});
uint256 newTokenId = totalSupply++;
tokens[newTokenId] = _token;
_transfer(0x0, msg.sender, newTokenId);
LogToken( "Buy", msg.sender, idGame, newTokenId, combination, userStake);
}
function redeemToken(uint256 _tokenId) public
{
Token storage tkn = tokens[_tokenId];
uint256 packed = tkn.option;
bool payout = uint8((packed >> (12*8)) & 0xFF)==1?true:false;
uint32 idGame = uint32((packed >> (8*8)) & 0xFFFFFFFF);
uint32 combination = uint32((packed >> (4*8)) & 0xFFFFFFFF);
Game storage curGame = game[idGame];
require( curGame.status == Status.PAYING || curGame.status == Status.CANCELING);
require( msg.sender == tokenIndexToOwner[_tokenId] );
require( payout == false );
require( combination == curGame.winCombination || curGame.status == Status.CANCELING );
uint256 sumPayment = 0;
if ( curGame.status == Status.CANCELING ) sumPayment = tkn.price;
if ( curGame.status == Status.PAYING ) sumPayment = curGame.betsSumIn / betsAll[idGame][curGame.winCombination].count;
payout = true;
packed += uint128(payout?1:0) << 12*8;
tkn.option = packed;
msg.sender.transfer(sumPayment);
LogToken( "Redeem", msg.sender, idGame, uint32(_tokenId), combination, sumPayment);
}
function cancelGame(uint32 idGame) public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( msg.sender == owner || admins[msg.sender] || timenow() > curGame.dateStopBuy + 60 days );
curGame.status = Status.CANCELING;
takeFee(idGame);
}
function resolveGameByHand(uint32 idGame, uint32 combination) onlyAdmin public
{
Game storage curGame = game[idGame];
require( curGame.status == Status.PLAYING );
require( combination <= curGame.countCombinations );
require( combination != 0 );
require( timenow() > curGame.dateStopBuy + 2*60*60 );
curGame.winCombination = combination;
checkWinNobody(idGame);
}
function checkWinNobody(uint32 idGame) internal
{
Game storage curGame = game[idGame];
curGame.status = Status.PAYING;
curGame.betsSumIn = getSumInByGame(idGame);
if ( betsAll[idGame][curGame.winCombination].count == 0 )
{
if (curGame.betsSumIn+curGame.feeValue!=0) feeGame = feeGame + curGame.betsSumIn + curGame.feeValue;
LogEvent( "NobodyWin", curGame.nameGame, curGame.betsSumIn+curGame.feeValue );
}
else
takeFee(idGame);
}
function takeFee(uint32 idGame) internal
{
Game storage curGame = game[idGame];
if ( curGame.feeValue > 0 )
{
feeGame = feeGame + curGame.feeValue;
LogEvent( "TakeFee", curGame.nameGame, curGame.feeValue );
}
}
function withdraw() onlyOwner public
{
require( feeGame > 0 );
uint256 tmpFeeGame = feeGame;
feeGame = 0;
owner.transfer(tmpFeeGame);
}
} | 1 |
pragma solidity ^0.4.17;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
uint256 public totalSupply;
mapping(address => uint256) balances;
function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; }
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract GimmerPreSale is ERC20Basic, Pausable {
using SafeMath for uint256;
struct Supporter {
uint256 weiSpent;
bool hasKYC;
}
mapping(address => Supporter) public supportersMap;
address public fundWallet;
address public kycManager;
uint256 public tokensSold;
uint256 public weiRaised;
uint256 public constant ONE_MILLION = 1000000;
uint256 public constant PRE_SALE_GMRP_TOKEN_CAP = 15 * ONE_MILLION * 1 ether;
uint256 public constant PRE_SALE_30_ETH = 30 ether;
uint256 public constant PRE_SALE_300_ETH = 300 ether;
uint256 public constant PRE_SALE_3000_ETH = 3000 ether;
uint256 public constant TOKEN_RATE_25_PERCENT_BONUS = 1250;
uint256 public constant TOKEN_RATE_30_PERCENT_BONUS = 1300;
uint256 public constant TOKEN_RATE_40_PERCENT_BONUS = 1400;
uint256 public constant START_TIME = 1511524800;
uint256 public constant END_TIME = 1514894400;
string public constant name = "GimmerPreSale Token";
string public constant symbol = "GMRP";
uint256 public constant decimals = 18;
modifier onlyKycManager() {
require(msg.sender == kycManager);
_;
}
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
event Mint(address indexed to, uint256 amount);
event KYC(address indexed user, bool isApproved);
function GimmerPreSale(address _fundWallet, address _kycManagerWallet) public {
require(_fundWallet != address(0));
require(_kycManagerWallet != address(0));
fundWallet = _fundWallet;
kycManager = _kycManagerWallet;
}
function () whenNotPaused public payable {
buyTokens();
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= START_TIME && now <= END_TIME;
bool higherThanMin30ETH = msg.value >= PRE_SALE_30_ETH;
return withinPeriod && higherThanMin30ETH;
}
function buyTokens() whenNotPaused public payable {
address sender = msg.sender;
require(userHasKYC(sender));
require(validPurchase());
uint256 weiAmountSent = msg.value;
uint256 rate = getRate(weiAmountSent);
uint256 newTokens = weiAmountSent.mul(rate);
uint256 totalTokensSold = tokensSold.add(newTokens);
require(totalTokensSold <= PRE_SALE_GMRP_TOKEN_CAP);
Supporter storage sup = supportersMap[sender];
uint256 totalWei = sup.weiSpent.add(weiAmountSent);
sup.weiSpent = totalWei;
weiRaised = weiRaised.add(weiAmountSent);
tokensSold = totalTokensSold;
mint(sender, newTokens);
TokenPurchase(sender, weiAmountSent, newTokens);
forwardFunds();
}
function getRate(uint256 weiAmount) public pure returns (uint256) {
if (weiAmount >= PRE_SALE_3000_ETH) {
return TOKEN_RATE_40_PERCENT_BONUS;
} else if(weiAmount >= PRE_SALE_300_ETH) {
return TOKEN_RATE_30_PERCENT_BONUS;
} else if(weiAmount >= PRE_SALE_30_ETH) {
return TOKEN_RATE_25_PERCENT_BONUS;
} else {
return 0;
}
}
function forwardFunds() internal {
fundWallet.transfer(msg.value);
}
function hasEnded() public constant returns (bool) {
return now > END_TIME;
}
function approveUserKYC(address _user) onlyKycManager public {
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
KYC(_user, true);
}
function disapproveUserKYC(address _user) onlyKycManager public {
Supporter storage sup = supportersMap[_user];
sup.hasKYC = false;
KYC(_user, false);
}
function setKYCManager(address _newKYCManager) onlyOwner public {
require(_newKYCManager != address(0));
kycManager = _newKYCManager;
}
function userHasKYC(address _user) public constant returns (bool) {
return supportersMap[_user].hasKYC;
}
function userWeiSpent(address _user) public constant returns (uint256) {
return supportersMap[_user].weiSpent;
}
function mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 XoudCoin is StandardToken {
string public name = "XoudCoin";
string public symbol = "XOUD";
uint public decimals = 18;
uint public constant INITIAL_SUPPLY = 100000000000000000000000000;
function XoudCoin() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, 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] = 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;
}
}
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 InvestorsFeature is Ownable, StandardToken {
using SafeMath for uint;
address[] public investors;
mapping(address => bool) isInvestor;
function deposit(address investor, uint) internal {
if(isInvestor[investor] == false) {
investors.push(investor);
isInvestor[investor] = true;
}
}
function sendp(address addr, uint amount) internal {
require(addr != address(0));
require(amount > 0);
deposit(addr, amount);
balances[this] = balances[this].sub(amount);
balances[addr] = balances[addr].add(amount);
Transfer(this, addr, amount);
}
}
contract KaratBankCoin is Ownable, StandardToken, InvestorsFeature {
string public constant name = "KaratBank Coin";
string public constant symbol = "KBC";
uint8 public constant decimals = 7;
uint256 public constant INITIAL_SUPPLY = (12000 * (10**6)) * (10 ** uint256(decimals));
function KaratBankCoin() public {
totalSupply = INITIAL_SUPPLY;
balances[this] = INITIAL_SUPPLY;
Transfer(address(0), this, INITIAL_SUPPLY);
}
function send(address addr, uint amount) public onlyOwner {
sendp(addr, amount);
}
function moneyBack(address addr) public onlyOwner {
require(addr != 0x0);
addr.transfer(this.balance);
}
function burnRemainder(uint) public onlyOwner {
uint value = balances[this];
totalSupply = totalSupply.sub(value);
balances[this] = 0;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract AltcoinToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Hansha is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Hansha token";
string public constant symbol = "Hansha";
uint public constant decimals = 8;
uint256 public totalSupply = 6300000000e8;
uint256 public totalDistributed = 0;
uint256 public tokensPerEth = 40000000e8;
uint256 public constant minContribution = 1 ether / 100;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function doAirdrop(address _participant, uint _amount) internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
require( msg.value >= minContribution );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
AltcoinToken t = AltcoinToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) {
AltcoinToken token = AltcoinToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 1 |
pragma solidity ^0.4.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;
}
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 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 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 ReservationFund is ICrowdsaleReservationFund, Ownable, SafeMath {
bool public crowdsaleFinished = false;
mapping(address => uint256) contributions;
mapping(address => uint256) tokensToIssue;
mapping(address => uint256) bonusTokensToIssue;
ISimpleCrowdsale public crowdsale;
event RefundPayment(address contributor, uint256 etherAmount);
event TransferToFund(address contributor, uint256 etherAmount);
event FinishCrowdsale();
function ReservationFund(address _owner) public Ownable(_owner) {
}
modifier onlyCrowdsale() {
require(msg.sender == address(crowdsale));
_;
}
function setCrowdsaleAddress(address crowdsaleAddress) public onlyOwner {
require(crowdsale == address(0));
crowdsale = ISimpleCrowdsale(crowdsaleAddress);
}
function contributionsOf(address contributor) external returns(uint256) {
return contributions[contributor];
}
function processContribution(
address contributor,
uint256 _tokensToIssue,
uint256 _bonusTokensToIssue
) external payable onlyCrowdsale {
contributions[contributor] = safeAdd(contributions[contributor], msg.value);
tokensToIssue[contributor] = safeAdd(tokensToIssue[contributor], _tokensToIssue);
bonusTokensToIssue[contributor] = safeAdd(bonusTokensToIssue[contributor], _bonusTokensToIssue);
}
function canCompleteContribution(address contributor) external returns(bool) {
if(crowdsaleFinished) {
return false;
}
if(!crowdsale.isContributorInLists(contributor)) {
return false;
}
if(contributions[contributor] == 0) {
return false;
}
return true;
}
function completeContribution(address contributor) external {
require(!crowdsaleFinished);
require(crowdsale.isContributorInLists(contributor));
require(contributions[contributor] > 0);
uint256 etherAmount = contributions[contributor];
uint256 tokenAmount = tokensToIssue[contributor];
uint256 tokenBonusAmount = bonusTokensToIssue[contributor];
contributions[contributor] = 0;
tokensToIssue[contributor] = 0;
bonusTokensToIssue[contributor] = 0;
crowdsale.processReservationFundContribution.value(etherAmount)(contributor, tokenAmount, tokenBonusAmount);
TransferToFund(contributor, etherAmount);
}
function onCrowdsaleEnd() external {
crowdsaleFinished = true;
FinishCrowdsale();
}
function refundPayment(address contributor) public {
require(crowdsaleFinished);
require(contributions[contributor] > 0 || tokensToIssue[contributor] > 0);
uint256 amountToRefund = contributions[contributor];
contributions[contributor] = 0;
tokensToIssue[contributor] = 0;
bonusTokensToIssue[contributor] = 0;
contributor.transfer(amountToRefund);
RefundPayment(contributor, amountToRefund);
}
} | 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;
}
}
contract Eth2x {
using SafeMath for uint;
struct Investor {
uint invested;
uint payouts;
uint first_invest;
uint last_payout;
address referrer;
}
uint constant public COMMISSION = 10;
uint constant public WITHDRAW = 85;
uint constant public REFBONUS = 2;
uint constant public CASHBACK = 3;
uint constant public MULTIPLICATION = 2;
address public beneficiary = 0x373D3f20f9F10d23686Dc5Cda704E4EFCf0Ab1DB;
mapping(address => Investor) public investors;
event AddInvestor(address indexed holder);
event Payout(address indexed holder, uint amount);
event Deposit(address indexed holder, uint amount, address referrer);
event RefBonus(address indexed from, address indexed to, uint amount);
event CashBack(address indexed holder, uint amount);
event Withdraw(address indexed holder, uint amount);
function bonusSize() view public returns(uint) {
uint b = address(this).balance;
if(b >= 5000 ether) return 9;
if(b >= 3000 ether) return 4;
if(b >= 2000 ether) return 5;
if(b >= 1000 ether) return 6;
return 7;
}
function payoutSize(address _to) view public returns(uint) {
uint max = investors[_to].invested.mul(MULTIPLICATION);
if(investors[_to].invested == 0 || investors[_to].payouts >= max) return 0;
uint payout = investors[_to].invested.mul(bonusSize()).div(100).mul(block.timestamp.sub(investors[_to].last_payout)).div(1 days);
return investors[_to].payouts.add(payout) > max ? max.sub(investors[_to].payouts) : payout;
}
function withdrawSize(address _to) view public returns(uint) {
uint max = investors[_to].invested.div(100).mul(WITHDRAW);
if(investors[_to].invested == 0 || investors[_to].payouts >= max) return 0;
return max.sub(investors[_to].payouts);
}
function bytesToAddress(bytes bys) pure private returns(address addr) {
assembly {
addr := mload(add(bys, 20))
}
}
function() payable external {
if(investors[msg.sender].invested > 0) {
uint payout = payoutSize(msg.sender);
require(msg.value > 0 || payout > 0, "No payouts");
if(payout > 0) {
investors[msg.sender].last_payout = block.timestamp;
investors[msg.sender].payouts = investors[msg.sender].payouts.add(payout);
msg.sender.transfer(payout);
emit Payout(msg.sender, payout);
}
if(investors[msg.sender].payouts >= investors[msg.sender].invested.mul(MULTIPLICATION)) {
delete investors[msg.sender];
emit Withdraw(msg.sender, 0);
}
}
if(msg.value == 0.00000007 ether) {
require(investors[msg.sender].invested > 0, "You have not invested anything yet");
uint amount = withdrawSize(msg.sender);
require(amount > 0, "You have nothing to withdraw");
msg.sender.transfer(amount);
delete investors[msg.sender];
emit Withdraw(msg.sender, amount);
}
else if(msg.value > 0) {
require(msg.value >= 0.01 ether, "Minimum investment amount 0.01 ether");
investors[msg.sender].last_payout = block.timestamp;
investors[msg.sender].invested = investors[msg.sender].invested.add(msg.value);
beneficiary.transfer(msg.value.mul(COMMISSION).div(100));
if(investors[msg.sender].first_invest == 0) {
investors[msg.sender].first_invest = block.timestamp;
if(msg.data.length > 0) {
address ref = bytesToAddress(msg.data);
if(ref != msg.sender && investors[ref].invested > 0 && msg.value >= 1 ether) {
investors[msg.sender].referrer = ref;
uint ref_bonus = msg.value.mul(REFBONUS).div(100);
ref.transfer(ref_bonus);
emit RefBonus(msg.sender, ref, ref_bonus);
uint cashback_bonus = msg.value.mul(CASHBACK).div(100);
msg.sender.transfer(cashback_bonus);
emit CashBack(msg.sender, cashback_bonus);
}
}
emit AddInvestor(msg.sender);
}
emit Deposit(msg.sender, msg.value, investors[msg.sender].referrer);
}
}
} | 1 |
pragma solidity ^0.4.11;
interface token {
function transfer(address receiver, uint amount) public;
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
bool changePrice = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
event ChangePrice(uint prices);
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
address addressOfTokenUsedAsReward
)public {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 finney;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 finney;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () public payable {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount / price);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() public afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function transferToken(uint amount)public afterDeadline {
if (beneficiary == msg.sender)
{
tokenReward.transfer(msg.sender, amount);
FundTransfer(msg.sender, amount, true);
}
}
function safeWithdrawal()public afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
fundingGoalReached = false;
}
}
}
function checkPriceCrowdsale(uint newPrice1, uint newPrice2)public {
if (beneficiary == msg.sender) {
price = (newPrice1 * 1 finney)+(newPrice2 * 1 szabo);
ChangePrice(price);
changePrice = true;
}
}
} | 1 |
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) {
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 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 Recoverable is Ownable {
function Recoverable() {
}
function recoverTokens(ERC20Basic token) onlyOwner public {
token.transfer(owner, tokensToBeReturned(token));
}
function tokensToBeReturned(ERC20Basic token) public returns (uint) {
return token.balanceOf(this);
}
}
contract StandardTokenExt is StandardToken, Recoverable {
function isToken() public constant returns (bool weAre) {
return true;
}
}
contract BurnableToken is StandardTokenExt {
address public constant BURN_ADDRESS = 0;
event Burned(address burner, uint burnedAmount);
function burn(uint burnAmount) {
address burner = msg.sender;
balances[burner] = balances[burner].sub(burnAmount);
totalSupply_ = totalSupply_.sub(burnAmount);
Burned(burner, burnAmount);
Transfer(burner, BURN_ADDRESS, burnAmount);
}
}
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is StandardTokenExt {
address public upgradeMaster;
UpgradeAgent public upgradeAgent;
uint256 public totalUpgraded;
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
event UpgradeAgentSet(address agent);
function UpgradeableToken(address _upgradeMaster) {
upgradeMaster = _upgradeMaster;
}
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
throw;
}
if (value == 0) throw;
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply_ = totalSupply_.sub(value);
totalUpgraded = totalUpgraded.add(value);
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
function setUpgradeAgent(address agent) external {
if(!canUpgrade()) {
throw;
}
if (agent == 0x0) throw;
if (msg.sender != upgradeMaster) throw;
if (getUpgradeState() == UpgradeState.Upgrading) throw;
upgradeAgent = UpgradeAgent(agent);
if(!upgradeAgent.isUpgradeAgent()) throw;
if (upgradeAgent.originalSupply() != totalSupply_) throw;
UpgradeAgentSet(upgradeAgent);
}
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
function setUpgradeMaster(address master) public {
if (master == 0x0) throw;
if (msg.sender != upgradeMaster) throw;
upgradeMaster = master;
}
function canUpgrade() public constant returns(bool) {
return true;
}
}
contract ReleasableToken is StandardTokenExt {
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
modifier canTransfer(address _sender) {
if(!released) {
if(!transferAgents[_sender]) {
throw;
}
}
_;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
modifier inReleaseState(bool releaseState) {
if(releaseState != released) {
throw;
}
_;
}
modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
throw;
}
_;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
}
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
contract MintableToken is StandardTokenExt {
using SafeMathLib for uint;
bool public mintingFinished = false;
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
event Minted(address receiver, uint amount);
function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply_ = totalSupply_.plus(amount);
balances[receiver] = balances[receiver].plus(amount);
Transfer(0, receiver, amount);
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
if(!mintAgents[msg.sender]) {
throw;
}
_;
}
modifier canMint() {
if(mintingFinished) throw;
_;
}
}
contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken {
event UpdatedTokenInformation(string newName, string newSymbol);
string public name;
string public symbol;
uint public decimals;
function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable)
UpgradeableToken(msg.sender) {
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply_ = _initialSupply;
decimals = _decimals;
balances[owner] = totalSupply_;
if(totalSupply_ > 0) {
Minted(owner, totalSupply_);
}
if(!_mintable) {
mintingFinished = true;
if(totalSupply_ == 0) {
throw;
}
}
}
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
function canUpgrade() public constant returns(bool) {
return released && super.canUpgrade();
}
function setTokenInformation(string _name, string _symbol) onlyOwner {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
}
contract BurnableCrowdsaleToken is BurnableToken, CrowdsaleToken {
function BurnableCrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable)
CrowdsaleToken(_name, _symbol, _initialSupply, _decimals, _mintable) {
}
}
contract AMLToken is BurnableCrowdsaleToken {
event OwnerReclaim(address fromWhom, uint amount);
function AMLToken(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable) BurnableCrowdsaleToken(_name, _symbol, _initialSupply, _decimals, _mintable) {
}
function transferToOwner(address fromWhom) onlyOwner {
if (released) revert();
uint amount = balanceOf(fromWhom);
balances[fromWhom] = balances[fromWhom].sub(amount);
balances[owner] = balances[owner].add(amount);
Transfer(fromWhom, owner, amount);
OwnerReclaim(fromWhom, amount);
}
} | 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 FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
address private otherF3D_;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x675818227377a7b1b3047105078966daf883a0ff);
string constant public name = "imfomo Long Official";
string constant public symbol = "imfomo";
uint256 private rndExtra_ = 30;
uint256 private rndGap_ = 30;
uint256 constant private rndInit_ = 10 minutes;
uint256 constant private rndInc_ = 60 seconds;
uint256 constant private rndMax_ = 10 minutes;
address constant private reward = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
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(31,0);
fees_[1] = F3Ddatasets.TeamFee(38,0);
fees_[2] = F3Ddatasets.TeamFee(61,0);
fees_[3] = F3Ddatasets.TeamFee(46,0);
potSplit_[0] = F3Ddatasets.PotSplit(15,0);
potSplit_[1] = F3Ddatasets.PotSplit(15,0);
potSplit_[2] = F3Ddatasets.PotSplit(30,0);
potSplit_[3] = F3Ddatasets.PotSplit(30,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");
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(58)) / 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 (_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(58)) / 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);
_p3d = _p3d.add(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
reward.send(_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;
uint256 _p3d;
_p3d = _p3d.add(_com);
uint256 _long = _eth / 100;
otherF3D_.send(_long);
uint256 _aff;
uint256 _aff2;
uint256 _affID2 = plyr_[_affID].laff;
if (_affID2 != 0 && plyr_[_affID2].name != "") {
_aff = _eth.mul(10) / 100;
_aff2 = _eth.mul(5) / 100;
plyr_[_affID2].aff = _aff2.add(plyr_[_affID2].aff);
} else {
_aff = _eth.mul(15) / 100;
}
if (_affID != _pID && plyr_[_affID].name != "") {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
} else {
_p3d = _p3d.add(_aff);
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
reward.send(_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 / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(19)) / 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 == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
public
{
require(
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) == address(0), "silly dev, you already did that");
otherF3D_ = _otherF3D;
}
}
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 DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
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.24;
contract Audit {
struct Proof {
uint level;
uint insertedBlock;
bytes32 ipfsHash;
address auditedBy;
}
event AttachedEvidence(address indexed auditorAddr, bytes32 indexed codeHash, bytes32 ipfsHash);
event NewAudit(address indexed auditorAddr, bytes32 indexed codeHash);
mapping (address => mapping (bytes32 => Proof)) public auditedContracts;
mapping (address => bytes32[]) public auditorContracts;
function isVerifiedAddress(address _auditorAddr, address _contractAddr) public view returns(uint) {
bytes32 codeHash = getCodeHash(_contractAddr);
return auditedContracts[_auditorAddr][codeHash].level;
}
function isVerifiedCode(address _auditorAddr, bytes32 _codeHash) public view returns(uint) {
return auditedContracts[_auditorAddr][_codeHash].level;
}
function getCodeHash(address _contractAddr) public view returns(bytes32) {
return keccak256(codeAt(_contractAddr));
}
function addAudit(bytes32 _codeHash, uint _level, bytes32 _ipfsHash) public {
address auditor = msg.sender;
require(auditedContracts[auditor][_codeHash].insertedBlock == 0);
auditedContracts[auditor][_codeHash] = Proof({
level: _level,
auditedBy: auditor,
insertedBlock: block.number,
ipfsHash: _ipfsHash
});
auditorContracts[auditor].push(_codeHash);
emit NewAudit(auditor, _codeHash);
}
function addEvidence(bytes32 _codeHash, uint _newLevel, bytes32 _ipfsHash) public {
address auditor = msg.sender;
require(auditedContracts[auditor][_codeHash].insertedBlock != 0);
if (auditedContracts[auditor][_codeHash].level != _newLevel)
auditedContracts[auditor][_codeHash].level = _newLevel;
emit AttachedEvidence(auditor, _codeHash, _ipfsHash);
}
function codeAt(address _addr) public view returns (bytes code) {
assembly {
let size := extcodesize(_addr)
code := mload(0x40)
mstore(0x40, add(code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(code, size)
extcodecopy(_addr, add(code, 0x20), 0, size)
}
}
} | 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 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 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 SebastianToken is StandardToken, Ownable {
using SafeMath for uint256;
string public name = "Sebastian";
string public symbol = "SEB";
uint256 public decimals = 5;
uint256 public totalSupply = 1000000000 * (10 ** uint256(decimals));
function SebastianToken(string _name, string _symbol, uint256 _decimals, uint256 _totalSupply) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply;
totalSupply_ = _totalSupply;
balances[msg.sender] = totalSupply;
}
function () public payable {
revert();
}
}
contract SebastianTokenSale is Ownable {
using SafeMath for uint256;
SebastianToken public token;
uint256 public startingTimestamp = 1518696000;
uint256 public endingTimestamp = 1521115200;
uint256 public tokenPriceInEth = 0.0001 ether;
uint256 public tokensForSale = 400000000 * 1E5;
uint256 public totalTokenSold;
uint256 public totalEtherRaised;
mapping(address => uint256) public etherRaisedPerWallet;
address public wallet;
bool internal isClose = false;
event WalletChange(address _wallet, uint256 _timestamp);
event TokenPurchase(address indexed _purchaser, address indexed _beneficiary, uint256 _value, uint256 _amount, uint256 _timestamp);
event TransferManual(address indexed _from, address indexed _to, uint256 _value, string _message);
function SebastianTokenSale(address _token, uint256 _startingTimestamp, uint256 _endingTimestamp, uint256 _tokensPerEth, uint256 _tokensForSale, address _wallet) public {
token = SebastianToken(_token);
startingTimestamp = _startingTimestamp;
endingTimestamp = _endingTimestamp;
tokenPriceInEth = 1E18 / _tokensPerEth;
tokensForSale = _tokensForSale;
wallet = _wallet;
}
function isValidPurchase(uint256 value, uint256 amount) internal constant returns (bool) {
bool validTimestamp = startingTimestamp <= block.timestamp && endingTimestamp >= block.timestamp;
bool validValue = value != 0;
bool validRate = tokenPriceInEth > 0;
bool validAmount = tokensForSale.sub(totalTokenSold) >= amount && amount > 0;
return validTimestamp && validValue && validRate && validAmount && !isClose;
}
function calculate(uint256 value) public constant returns (uint256) {
uint256 tokenDecimals = token.decimals();
uint256 tokens = value.mul(10 ** tokenDecimals).div(tokenPriceInEth);
return tokens;
}
function() public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
uint256 value = msg.value;
uint256 tokens = calculate(value);
require(isValidPurchase(value , tokens));
totalTokenSold = totalTokenSold.add(tokens);
totalEtherRaised = totalEtherRaised.add(value);
etherRaisedPerWallet[msg.sender] = etherRaisedPerWallet[msg.sender].add(value);
token.transfer(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, value, tokens, now);
}
function transferManual(address _to, uint256 _value, string _message) onlyOwner public returns (bool) {
require(_to != address(0));
token.transfer(_to , _value);
TransferManual(msg.sender, _to, _value, _message);
return true;
}
function setWallet(address _wallet) onlyOwner public returns(bool) {
wallet = _wallet;
WalletChange(_wallet , now);
return true;
}
function withdraw() onlyOwner public {
wallet.transfer(this.balance);
}
function close() onlyOwner public {
uint256 tokens = token.balanceOf(this);
token.transfer(owner , tokens);
withdraw();
isClose = true;
}
} | 0 |
pragma solidity ^0.4.20;
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
function AccessAdmin() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
function withdraw(address _target, uint256 _amount)
external
{
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
uint256 balance = this.balance;
if (_amount < balance) {
receiver.transfer(_amount);
} else {
receiver.transfer(this.balance);
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface IBitGuildToken {
function transfer(address _to, uint256 _value) external;
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool);
function balanceOf(address _from) external view returns(uint256);
}
interface IAgonFight {
function calcFight(uint64 _mFlag, uint64 _cFlag, uint256 _aSeed, uint256 _fSeed) external pure returns(uint64);
}
contract ActionAgonPlat is AccessService {
using SafeMath for uint256;
event CreateAgonPlat(uint64 indexed agonId, address indexed master, uint64 indexed outFlag);
event CancelAgonPlat(uint64 indexed agonId, address indexed master, uint64 indexed outFlag);
event ChallengeAgonPlat(uint64 indexed agonId, address indexed master, uint64 indexed outFlag, address challenger);
event ResolveAgonPlat(uint64 indexed agonId, address indexed master, uint64 indexed outFlag, address challenger);
struct Agon {
address master;
address challenger;
uint64 agonPrice;
uint64 outFlag;
uint64 agonFlag;
uint64 result;
}
Agon[] agonArray;
IAgonFight fightContract;
IBitGuildToken public bitGuildContract;
mapping (address => uint64[]) public ownerToAgonIdArray;
uint256 public maxAgonCount = 6;
uint256 public maxResolvedAgonId = 0;
uint256[5] public agonValues;
function ActionAgonPlat(address _platAddr) public {
addrAdmin = msg.sender;
addrService = msg.sender;
addrFinance = msg.sender;
bitGuildContract = IBitGuildToken(_platAddr);
Agon memory order = Agon(0, 0, 0, 0, 1, 1);
agonArray.push(order);
agonValues[0] = 3000000000000000000000;
agonValues[1] = 12000000000000000000000;
agonValues[2] = 30000000000000000000000;
agonValues[3] = 60000000000000000000000;
agonValues[4] = 120000000000000000000000;
}
function() external {}
function setMaxAgonCount(uint256 _count) external onlyAdmin {
require(_count > 0 && _count < 20);
require(_count != maxAgonCount);
maxAgonCount = _count;
}
function setAgonFight(address _addr) external onlyAdmin {
fightContract = IAgonFight(_addr);
}
function setMaxResolvedAgonId() external {
uint256 length = agonArray.length;
for (uint256 i = maxResolvedAgonId; i < length; ++i) {
if (agonArray[i].result == 0) {
maxResolvedAgonId = i - 1;
break;
}
}
}
function setAgonValues(uint256[5] values) external onlyAdmin {
require(values[0] >= 100);
require(values[1] >= values[0]);
require(values[2] >= values[1]);
require(values[3] >= values[2]);
require(values[4] >= values[3]);
require(values[4] <= 600000);
require(values[0] % 100 == 0);
require(values[1] % 100 == 0);
require(values[2] % 100 == 0);
require(values[3] % 100 == 0);
require(values[4] % 100 == 0);
agonValues[0] = values[0].mul(1000000000000000000);
agonValues[1] = values[1].mul(1000000000000000000);
agonValues[2] = values[2].mul(1000000000000000000);
agonValues[3] = values[3].mul(1000000000000000000);
agonValues[4] = values[4].mul(1000000000000000000);
}
function _getExtraParam(bytes _extraData) internal pure returns(uint64 p1, uint64 p2, uint64 p3) {
p1 = uint64(_extraData[0]);
p2 = uint64(_extraData[1]);
uint64 index = 2;
uint256 val = 0;
uint256 length = _extraData.length;
while (index < length) {
val += (uint256(_extraData[index]) * (256 ** (length - index - 1)));
index += 1;
}
p3 = uint64(val);
}
function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData)
external
whenNotPaused
{
require(msg.sender == address(bitGuildContract));
require(_extraData.length > 2 && _extraData.length <= 10);
var (p1, p2, p3) = _getExtraParam(_extraData);
if (p1 == 0) {
_newAgon(p3, p2, _sender, _value);
} else if (p1 == 1) {
_newChallenge(p3, p2, _sender, _value);
} else {
require(false);
}
}
function _newAgon(uint64 _outFlag, uint64 _valId, address _sender, uint256 _value) internal {
require(ownerToAgonIdArray[_sender].length < maxAgonCount);
require(_valId >= 0 && _valId <= 4);
require(_value == agonValues[_valId]);
require(bitGuildContract.transferFrom(_sender, address(this), _value));
uint64 newAgonId = uint64(agonArray.length);
agonArray.length += 1;
Agon storage agon = agonArray[newAgonId];
agon.master = _sender;
agon.agonPrice = uint64(_value.div(1000000000000000000));
agon.outFlag = _outFlag;
ownerToAgonIdArray[_sender].push(newAgonId);
CreateAgonPlat(uint64(newAgonId), _sender, _outFlag);
}
function _removeAgonIdByOwner(address _owner, uint64 _agonId) internal {
uint64[] storage agonIdArray = ownerToAgonIdArray[_owner];
uint256 length = agonIdArray.length;
require(length > 0);
uint256 findIndex = 99;
for (uint256 i = 0; i < length; ++i) {
if (_agonId == agonIdArray[i]) {
findIndex = i;
}
}
require(findIndex != 99);
if (findIndex != (length - 1)) {
agonIdArray[findIndex] = agonIdArray[length - 1];
}
agonIdArray.length -= 1;
}
function cancelAgon(uint64 _agonId) external {
require(_agonId < agonArray.length);
Agon storage agon = agonArray[_agonId];
require(agon.result == 0);
require(agon.challenger == address(0));
require(agon.master == msg.sender);
agon.result = 99;
_removeAgonIdByOwner(msg.sender, _agonId);
bitGuildContract.transfer(msg.sender, uint256(agon.agonPrice).mul(1000000000000000000));
CancelAgonPlat(_agonId, msg.sender, agon.outFlag);
}
function cancelAgonForce(uint64 _agonId) external onlyService {
require(_agonId < agonArray.length);
Agon storage agon = agonArray[_agonId];
require(agon.result == 0);
require(agon.challenger == address(0));
agon.result = 99;
_removeAgonIdByOwner(agon.master, _agonId);
bitGuildContract.transfer(agon.master, uint256(agon.agonPrice).mul(1000000000000000000));
CancelAgonPlat(_agonId, agon.master, agon.outFlag);
}
function _newChallenge(uint64 _agonId, uint64 _flag, address _sender, uint256 _value) internal {
require(_agonId < agonArray.length);
Agon storage agon = agonArray[_agonId];
require(agon.result == 0);
require(agon.master != _sender);
require(uint256(agon.agonPrice).mul(1000000000000000000) == _value);
require(agon.challenger == address(0));
require(bitGuildContract.transferFrom(_sender, address(this), _value));
agon.challenger = _sender;
agon.agonFlag = _flag;
ChallengeAgonPlat(_agonId, agon.master, agon.outFlag, _sender);
}
function fightAgon(uint64 _agonId, uint64 _mFlag, uint256 _aSeed, uint256 _fSeed) external onlyService {
require(_agonId < agonArray.length);
Agon storage agon = agonArray[_agonId];
require(agon.result == 0 && agon.challenger != address(0));
require(fightContract != address(0));
uint64 fRet = fightContract.calcFight(_mFlag, agon.agonFlag, _aSeed, _fSeed);
require(fRet == 1 || fRet == 2);
agon.result = fRet;
_removeAgonIdByOwner(agon.master, _agonId);
uint256 devCut = uint256(agon.agonPrice).div(10);
uint256 winVal = uint256(agon.agonPrice).mul(2).sub(devCut);
if (fRet == 1) {
bitGuildContract.transfer(agon.master, winVal.mul(1000000000000000000));
} else {
bitGuildContract.transfer(agon.challenger, winVal.mul(1000000000000000000));
}
ResolveAgonPlat(_agonId, agon.master, agon.outFlag, agon.challenger);
}
function getPlatBalance() external view returns(uint256) {
return bitGuildContract.balanceOf(this);
}
function withdrawPlat() external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
uint256 balance = bitGuildContract.balanceOf(this);
require(balance > 0);
bitGuildContract.transfer(addrFinance, balance);
}
function getAgon(uint256 _agonId) external view
returns(
address master,
address challenger,
uint64 agonPrice,
uint64 outFlag,
uint64 agonFlag,
uint64 result
)
{
require(_agonId < agonArray.length);
Agon memory agon = agonArray[_agonId];
master = agon.master;
challenger = agon.challenger;
agonPrice = agon.agonPrice;
outFlag = agon.outFlag;
agonFlag = agon.agonFlag;
result = agon.result;
}
function getAgonArray(uint64 _startAgonId, uint64 _count) external view
returns(
uint64[] agonIds,
address[] masters,
address[] challengers,
uint64[] agonPrices,
uint64[] agonOutFlags,
uint64[] agonFlags,
uint64[] results
)
{
uint64 length = uint64(agonArray.length);
require(_startAgonId < length);
require(_startAgonId > 0);
uint256 maxLen;
if (_count == 0) {
maxLen = length - _startAgonId;
} else {
maxLen = (length - _startAgonId) >= _count ? _count : (length - _startAgonId);
}
agonIds = new uint64[](maxLen);
masters = new address[](maxLen);
challengers = new address[](maxLen);
agonPrices = new uint64[](maxLen);
agonOutFlags = new uint64[](maxLen);
agonFlags = new uint64[](maxLen);
results = new uint64[](maxLen);
uint256 counter = 0;
for (uint64 i = _startAgonId; i < length; ++i) {
Agon storage tmpAgon = agonArray[i];
agonIds[counter] = i;
masters[counter] = tmpAgon.master;
challengers[counter] = tmpAgon.challenger;
agonPrices[counter] = tmpAgon.agonPrice;
agonOutFlags[counter] = tmpAgon.outFlag;
agonFlags[counter] = tmpAgon.agonFlag;
results[counter] = tmpAgon.result;
counter += 1;
if (counter >= maxLen) {
break;
}
}
}
function getMaxAgonId() external view returns(uint256) {
return agonArray.length - 1;
}
function getAgonIdArray(address _owner) external view returns(uint64[]) {
return ownerToAgonIdArray[_owner];
}
} | 0 |
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 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 PIETAToken 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 = "PITC";
name = "PIETA Token";
decimals = 4;
_totalSupply = 20000000000;
balances[0xE89b6728168Ff7eda36D994357B40f80dC8982eD] = _totalSupply;
emit Transfer(address(0), 0xE89b6728168Ff7eda36D994357B40f80dC8982eD, _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.13;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
require(assertion);
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function mint(address receiver, uint amount);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SolarDaoToken is SafeMath, ERC20, Ownable {
string public name = "Solar DAO Token";
string public symbol = "SDAO";
uint public decimals = 4;
address public crowdsaleAgent;
bool public released = false;
mapping (address => mapping (address => uint)) allowed;
mapping(address => uint) balances;
modifier canTransfer() {
if(!released) {
require(msg.sender == crowdsaleAgent);
}
_;
}
modifier inReleaseState(bool _released) {
require(_released == released);
_;
}
modifier onlyCrowdsaleAgent() {
require(msg.sender == crowdsaleAgent);
_;
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canMint() {
require(!released);
_;
}
function SolarDaoToken() {
owner = msg.sender;
}
function() payable {
revert();
}
function mint(address receiver, uint amount) onlyCrowdsaleAgent canMint public {
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
Transfer(0, receiver, amount);
}
function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner inReleaseState(false) public {
crowdsaleAgent = _crowdsaleAgent;
}
function releaseTokenTransfer() public onlyCrowdsaleAgent {
released = true;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
require ((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract Killable is Ownable {
function kill() onlyOwner {
selfdestruct(owner);
}
}
contract SolarDaoTokenCrowdsale is Haltable, Killable, SafeMath {
uint public constant PRE_FUNDING_GOAL = 4e6 * PRICE;
uint public constant ICO_GOAL = 8e7 * PRICE;
uint public constant MIN_ICO_GOAL = 1e7;
uint public constant TEAM_BONUS_PERCENT = 25;
uint constant public PRICE = 100;
uint constant public PRE_ICO_DURATION = 5 weeks;
SolarDaoToken public token;
address public multisigWallet;
uint public startsAt;
uint public endsAt;
uint public preInvestStart;
uint public tokensSold = 0;
uint public weiRaised = 0;
uint public investorCount = 0;
uint public loadedRefund = 0;
uint public weiRefunded = 0;
bool public finalized;
uint public exchangeRate;
uint public exchangeRateTimestamp;
address public exchangeRateAgent;
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public tokenAmountOf;
struct Milestone {
uint start;
uint end;
uint bonus;
}
Milestone[] public milestones;
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
event Invested(address investor, uint weiAmount, uint tokenAmount);
event Refund(address investor, uint weiAmount);
event EndsAtChanged(uint endsAt);
event ExchangeRateChanged(uint oldValue, uint newValue);
modifier inState(State state) {
require(getState() == state);
_;
}
modifier onlyExchangeRateAgent() {
require(msg.sender == exchangeRateAgent);
_;
}
function SolarDaoTokenCrowdsale(address _token, address _multisigWallet, uint _preInvestStart, uint _start, uint _end) {
require(_multisigWallet != 0);
require(_preInvestStart != 0);
require(_start != 0);
require(_end != 0);
require(_start < _end);
require(_end > _preInvestStart + PRE_ICO_DURATION);
token = SolarDaoToken(_token);
multisigWallet = _multisigWallet;
startsAt = _start;
endsAt = _end;
preInvestStart = _preInvestStart;
var preIcoBonuses = [uint(100), 80, 70, 60, 50];
for (uint i = 0; i < preIcoBonuses.length; i++) {
milestones.push(Milestone(preInvestStart + i * 1 weeks, preInvestStart + (i + 1) * 1 weeks, preIcoBonuses[i]));
}
milestones.push(Milestone(startsAt, startsAt + 4 days, 25));
milestones.push(Milestone(startsAt + 4 days, startsAt + 1 weeks, 20));
delete preIcoBonuses;
var icoBonuses = [uint(15), 10, 5];
for (i = 1; i <= icoBonuses.length; i++) {
milestones.push(Milestone(startsAt + i * 1 weeks, startsAt + (i + 1) * 1 weeks, icoBonuses[i - 1]));
}
delete icoBonuses;
}
function() payable {
buy();
}
function getCurrentMilestone() private constant returns (Milestone) {
for (uint i = 0; i < milestones.length; i++) {
if (milestones[i].start <= now && milestones[i].end > now) {
return milestones[i];
}
}
}
function investInternal(address receiver) stopInEmergency private {
var state = getState();
require(state == State.Funding || state == State.PreFunding);
uint weiAmount = msg.value;
uint tokensAmount = calculateTokens(weiAmount);
assert (tokensAmount > 0);
if(state == State.PreFunding) {
tokensAmount += safeDiv(safeMul(tokensAmount, getCurrentMilestone().bonus), 100);
}
if(investedAmountOf[receiver] == 0) {
investorCount++;
}
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver], tokensAmount);
weiRaised = safeAdd(weiRaised, weiAmount);
tokensSold = safeAdd(tokensSold, tokensAmount);
assignTokens(receiver, tokensAmount);
var teamBonusTokens = safeDiv(safeMul(tokensAmount, TEAM_BONUS_PERCENT), 100 - TEAM_BONUS_PERCENT);
assignTokens(multisigWallet, teamBonusTokens);
multisigWallet.transfer(weiAmount);
Invested(receiver, weiAmount, tokensAmount);
}
function invest(address receiver) public payable {
investInternal(receiver);
}
function buy() public payable {
invest(msg.sender);
}
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
require(!finalized);
finalized = true;
finalizeCrowdsale();
}
function finalizeCrowdsale() internal {
token.releaseTokenTransfer();
}
function setExchangeRate(uint value, uint time) onlyExchangeRateAgent {
require(value > 0);
require(time > 0);
require(exchangeRateTimestamp == 0 || getDifference(int(time), int(now)) <= 1 minutes);
require(exchangeRate == 0 || (getDifference(int(value), int(exchangeRate)) * 100 / exchangeRate <= 30));
ExchangeRateChanged(exchangeRate, value);
exchangeRate = value;
exchangeRateTimestamp = time;
}
function setExchangeRateAgent(address newAgent) onlyOwner {
if (newAgent != address(0)) {
exchangeRateAgent = newAgent;
}
}
function setCrowdsaleData(uint _tokensSold, uint _weiRaised, uint _investorCount) onlyOwner {
require(_tokensSold > 0);
require(_weiRaised > 0);
require(_investorCount > 0);
tokensSold = _tokensSold;
weiRaised = _weiRaised;
investorCount = _investorCount;
}
function getDifference(int one, int two) private constant returns (uint) {
var diff = one - two;
if (diff < 0)
diff = -diff;
return uint(diff);
}
function setEndsAt(uint time) onlyOwner {
require(time >= now);
endsAt = time;
EndsAtChanged(endsAt);
}
function loadRefund() public payable inState(State.Failure) {
require(msg.value > 0);
loadedRefund = safeAdd(loadedRefund, msg.value);
}
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0)
return;
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded, weiValue);
Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
}
function isMinimumGoalReached() public constant returns (bool reached) {
return weiToUsdCents(weiRaised) >= MIN_ICO_GOAL;
}
function isCrowdsaleFull() public constant returns (bool) {
return weiToUsdCents(weiRaised) >= ICO_GOAL;
}
function getState() public constant returns (State) {
if (finalized)
return State.Finalized;
if (address(token) == 0 || address(multisigWallet) == 0 || now < preInvestStart)
return State.Preparing;
if (preInvestStart <= now && now < startsAt && !isMaximumPreFundingGoalReached())
return State.PreFunding;
if (now <= endsAt && !isCrowdsaleFull())
return State.Funding;
if (isMinimumGoalReached())
return State.Success;
if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised)
return State.Refunding;
return State.Failure;
}
function calculateTokens(uint weiAmount) internal returns (uint tokenAmount) {
var multiplier = 10 ** token.decimals();
uint usdAmount = weiToUsdCents(weiAmount);
assert (usdAmount >= PRICE);
return safeMul(usdAmount, safeDiv(multiplier, PRICE));
}
function isMaximumPreFundingGoalReached() public constant returns (bool reached) {
return weiToUsdCents(weiRaised) >= PRE_FUNDING_GOAL;
}
function weiToUsdCents(uint weiValue) private returns (uint) {
return safeDiv(safeMul(weiValue, exchangeRate), 1e18);
}
function assignTokens(address receiver, uint tokenAmount) private {
token.mint(receiver, tokenAmount);
}
} | 0 |
pragma solidity ^0.4.18;
contract Owned {
address owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwner(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function getOwner() public view returns (address) {
return owner;
}
}
contract HolyPiggyStorage {
struct Wish {
bytes name;
bytes content;
uint256 time;
uint256 tribute;
}
Wish[] wishes;
mapping(address => uint256[]) wishesIdx;
address godAddress;
address serviceProvider;
uint256 serviceFeeNumerator;
uint256 serviceFeeDenominator;
uint256 minimumWishTribute;
uint256 accumulatedServiceFee;
}
contract HolyPiggy is HolyPiggyStorage, Owned {
function() public payable {}
function HolyPiggy(address god) public {
godAddress = god;
serviceFeeNumerator = 1;
serviceFeeDenominator = 50;
minimumWishTribute = 0;
}
function getGodAddress() external view returns (address) {
return godAddress;
}
event PostWish(address addr, uint256 id, bytes name, bytes content, uint256 time, uint256 tribute);
function setServiceProvider(address addr) public onlyOwner {
serviceProvider = addr;
}
function getServiceProvider() external view returns (address) {
return serviceProvider;
}
function setServiceFee(uint256 n, uint256 d) public onlyServiceProvider {
serviceFeeNumerator = n;
serviceFeeDenominator = d;
}
function getAccumulatedServiceFee() external view returns (uint256) {
return accumulatedServiceFee;
}
function getServiceFeeNumerator() external view returns (uint256) {
return serviceFeeNumerator;
}
function getServiceFeeDenominator() external view returns (uint256) {
return serviceFeeDenominator;
}
function getMinimumWishTribute() external view returns (uint256) {
return minimumWishTribute;
}
function setMinimumWishTribute(uint256 tribute) public onlyOwner {
minimumWishTribute = tribute;
}
modifier onlyServiceProvider() {
require(msg.sender == serviceProvider);
_;
}
function withdrawServiceFee() public onlyServiceProvider {
uint256 fee = accumulatedServiceFee;
accumulatedServiceFee = 0;
serviceProvider.transfer(fee);
}
function postWish(bytes name, bytes content) public payable {
require(msg.value > 0);
require(serviceProvider != address(0));
uint256 serviceFee = msg.value * serviceFeeNumerator / (serviceFeeDenominator + serviceFeeNumerator);
uint256 tribute = msg.value - serviceFee;
require(tribute > minimumWishTribute);
assert(accumulatedServiceFee + serviceFee > accumulatedServiceFee);
uint256 id = wishes.length;
var wish = Wish(name, content, now, tribute);
wishes.push(wish);
wishesIdx[msg.sender].push(id);
accumulatedServiceFee = accumulatedServiceFee + serviceFee;
godAddress.transfer(tribute);
PostWish(msg.sender, id, name, content, now, tribute);
}
function countWishes() external view returns (uint256) {
return wishes.length;
}
function getWishName(uint256 idx) external view returns (bytes) {
return wishes[idx].name;
}
function getWishContent(uint256 idx) external view returns (bytes) {
return wishes[idx].content;
}
function getWishTime(uint256 idx) external view returns (uint256) {
return wishes[idx].time;
}
function getWishTribute(uint256 idx) external view returns (uint256) {
return wishes[idx].tribute;
}
function getWishIdxesAt(address addr) external view returns (uint256[]) {
return wishesIdx[addr];
}
function getWishIdxAt(address addr, uint256 pos) external view returns (uint256) {
return wishesIdx[addr][pos];
}
function countWishesAt(address addr) external view returns (uint256) {
return wishesIdx[addr].length;
}
} | 1 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 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 IST20 is StandardToken, DetailedERC20 {
string public tokenDetails;
function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success);
function mint(address _investor, uint256 _amount) public returns (bool success);
function burn(uint256 _value) public;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed _burner, uint256 _value);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ISecurityToken is IST20, Ownable {
uint8 public constant PERMISSIONMANAGER_KEY = 1;
uint8 public constant TRANSFERMANAGER_KEY = 2;
uint8 public constant STO_KEY = 3;
uint8 public constant CHECKPOINT_KEY = 4;
uint256 public granularity;
uint256 public currentCheckpointId;
uint256 public investorCount;
address[] public investors;
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool);
function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address);
function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address);
function totalSupplyAt(uint256 _checkpointId) public view returns(uint256);
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256);
function createCheckpoint() public returns(uint256);
function getInvestorsLength() public view returns(uint256);
}
contract IModuleFactory is Ownable {
ERC20 public polyToken;
uint256 public setupCost;
uint256 public usageCost;
uint256 public monthlySubscriptionCost;
event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory);
event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp);
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public {
polyToken = ERC20(_polyAddress);
setupCost = _setupCost;
usageCost = _usageCost;
monthlySubscriptionCost = _subscriptionCost;
}
function deploy(bytes _data) external returns(address);
function getType() public view returns(uint8);
function getName() public view returns(bytes32);
function getDescription() public view returns(string);
function getTitle() public view returns(string);
function getInstructions() public view returns (string);
function getTags() public view returns (bytes32[]);
function getSig(bytes _data) internal pure returns (bytes4 sig) {
uint len = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < len; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));
}
}
function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner {
emit LogChangeFactorySetupFee(setupCost, _newSetupCost, address(this));
setupCost = _newSetupCost;
}
function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner {
emit LogChangeFactoryUsageFee(usageCost, _newUsageCost, address(this));
usageCost = _newUsageCost;
}
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit LogChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
}
contract IModule {
address public factory;
address public securityToken;
bytes32 public constant FEE_ADMIN = "FEE_ADMIN";
ERC20 public polyToken;
constructor (address _securityToken, address _polyAddress) public {
securityToken = _securityToken;
factory = msg.sender;
polyToken = ERC20(_polyAddress);
}
function getInitFunction() public pure returns (bytes4);
modifier withPerm(bytes32 _perm) {
bool isOwner = msg.sender == ISecurityToken(securityToken).owner();
bool isFactory = msg.sender == factory;
require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed");
_;
}
modifier onlyOwner {
require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner");
_;
}
modifier onlyFactory {
require(msg.sender == factory, "Sender is not factory");
_;
}
modifier onlyFactoryOwner {
require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner");
_;
}
function getPermissions() public view returns(bytes32[]);
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) {
require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee");
return true;
}
}
contract ICheckpoint is IModule {
}
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 ERC20DividendCheckpoint is ICheckpoint {
using SafeMath for uint256;
bytes32 public constant DISTRIBUTE = "DISTRIBUTE";
struct Dividend {
uint256 checkpointId;
uint256 created;
uint256 maturity;
uint256 expiry;
address token;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool reclaimed;
mapping (address => bool) claimed;
}
Dividend[] public dividends;
event ERC20DividendDeposited(address indexed _depositor, uint256 _checkpointId, uint256 _created, uint256 _maturity, uint256 _expiry, address _token, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
event ERC20DividendClaimed(address indexed _payee, uint256 _dividendIndex, address _token, uint256 _amount);
event ERC20DividendReclaimed(address indexed _claimer, uint256 _dividendIndex, address _token, uint256 _claimedAmount);
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
require(now >= dividends[_dividendIndex].maturity, "Dividend maturity is in the future");
require(now < dividends[_dividendIndex].expiry, "Dividend expiry is in the past");
require(!dividends[_dividendIndex].reclaimed, "Dividend has been reclaimed by issuer");
_;
}
constructor (address _securityToken, address _polyAddress) public
IModule(_securityToken, _polyAddress)
{
}
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
function createDividend(uint256 _maturity, uint256 _expiry, address _token, uint256 _amount) public onlyOwner {
require(_expiry > _maturity);
require(_expiry > now);
require(_token != address(0));
require(_amount > 0);
require(ERC20(_token).transferFrom(msg.sender, address(this), _amount), "Unable to transfer tokens for dividend");
uint256 dividendIndex = dividends.length;
uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint();
uint256 currentSupply = ISecurityToken(securityToken).totalSupply();
dividends.push(
Dividend(
checkpointId,
now,
_maturity,
_expiry,
_token,
_amount,
0,
currentSupply,
false
)
);
emit ERC20DividendDeposited(msg.sender, checkpointId, now, _maturity, _expiry, _token, _amount, currentSupply, dividendIndex);
}
function createDividendWithCheckpoint(uint256 _maturity, uint256 _expiry, address _token, uint256 _amount, uint256 _checkpointId) payable public onlyOwner {
require(_expiry > _maturity);
require(_expiry > now);
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());
uint256 dividendIndex = dividends.length;
uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);
require(ERC20(_token).transferFrom(msg.sender, address(this), _amount), "Unable to transfer tokens for dividend");
dividends.push(
Dividend(
_checkpointId,
now,
_maturity,
_expiry,
_token,
_amount,
0,
currentSupply,
false
)
);
emit ERC20DividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, _token, _amount, currentSupply, dividendIndex);
}
function pushDividendPaymentToAddresses(uint256 _dividendIndex, address[] _payees) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) {
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i++) {
if (!dividend.claimed[_payees[i]]) {
_payDividend(_payees[i], dividend, _dividendIndex);
}
}
}
function pushDividendPayment(uint256 _dividendIndex, uint256 _start, uint256 _iterations) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) {
Dividend storage dividend = dividends[_dividendIndex];
uint256 numberInvestors = ISecurityToken(securityToken).getInvestorsLength();
for (uint256 i = _start; i < Math.min256(numberInvestors, _start.add(_iterations)); i++) {
address payee = ISecurityToken(securityToken).investors(i);
if (!dividend.claimed[payee]) {
_payDividend(payee, dividend, _dividendIndex);
}
}
}
function pullDividendPayment(uint256 _dividendIndex) public validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(!dividend.claimed[msg.sender], "Dividend already reclaimed");
_payDividend(msg.sender, dividend, _dividendIndex);
}
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {
uint256 claim = calculateDividend(_dividendIndex, _payee);
_dividend.claimed[_payee] = true;
_dividend.claimedAmount = claim.add(_dividend.claimedAmount);
if (claim > 0) {
require(ERC20(_dividend.token).transfer(_payee, claim), "Unable to transfer tokens");
emit ERC20DividendClaimed(_payee, _dividendIndex, _dividend.token, claim);
}
}
function reclaimDividend(uint256 _dividendIndex) public onlyOwner {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future");
require(!dividends[_dividendIndex].reclaimed, "Dividend already claimed");
dividends[_dividendIndex].reclaimed = true;
Dividend storage dividend = dividends[_dividendIndex];
uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount);
require(ERC20(dividend.token).transfer(msg.sender, remainingAmount), "Unable to transfer tokens");
emit ERC20DividendReclaimed(msg.sender, _dividendIndex, dividend.token, remainingAmount);
}
function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256) {
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee]) {
return 0;
}
uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividends[_dividendIndex].checkpointId);
return balance.mul(dividends[_dividendIndex].amount).div(dividends[_dividendIndex].totalSupply);
}
function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {
uint256 counter = 0;
for(uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index = new uint256[](counter);
counter = 0;
for(uint256 j = 0; j < dividends.length; j++) {
if (dividends[j].checkpointId == _checkpointId) {
index[counter] = j;
counter++;
}
}
return index;
}
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = DISTRIBUTE;
return allPermissions;
}
}
contract ERC20DividendCheckpointFactory is IModuleFactory {
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public
IModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost)
{
}
function deploy(bytes ) external returns(address) {
if (setupCost > 0)
require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided");
return address(new ERC20DividendCheckpoint(msg.sender, address(polyToken)));
}
function getType() public view returns(uint8) {
return 4;
}
function getName() public view returns(bytes32) {
return "ERC20DividendCheckpoint";
}
function getDescription() public view returns(string) {
return "Create ERC20 dividends for token holders at a specific checkpoint";
}
function getTitle() public view returns(string) {
return "ERC20 Dividend Checkpoint";
}
function getInstructions() public view returns(string) {
return "Create a ERC20 dividend which will be paid out to token holders proportional to their balances at the point the dividend is created";
}
function getTags() public view returns(bytes32[]) {
bytes32[] memory availableTags = new bytes32[](3);
availableTags[0] = "ERC20";
availableTags[1] = "Dividend";
availableTags[2] = "Checkpoint";
return availableTags;
}
} | 0 |
pragma solidity ^0.4.24;
contract FDDEvents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularFomoDD is FDDEvents {}
contract FomoDD is modularFomoDD {
using SafeMath for *;
using NameFilter for string;
using FDDKeysCalc for uint256;
BankInterfaceForForwarder constant private Bank = BankInterfaceForForwarder(0xfa1678C00299fB685794865eA5e20dB155a8C913);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xcB530be74c05a120F1fe6e490E45f1EE14c49157);
address private admin = msg.sender;
string constant public name = "FomoDD";
string constant public symbol = "Chives";
uint256 private rndGap_ = 0;
uint256 private rndExtra_ = 0 minutes;
uint256 constant private rndInit_ = 12 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => FDDdatasets.Player) public plyr_;
mapping (uint256 => FDDdatasets.PlayerRounds) public plyrRnds_;
mapping (uint256 => mapping (uint256 => FDDdatasets.PlayerRounds)) public plyrRnds;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
uint256 public rID_;
FDDdatasets.Round public round_;
mapping (uint256 => FDDdatasets.Round) public round;
uint256 public fees_ = 60;
uint256 public potSplit_ = 45;
constructor()
public
{
}
modifier isActivated() {
require(activated_ == true, "its not ready yet");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "non smart contract address only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
FDDdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
buyCore(_pID, _affID, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
FDDdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
FDDdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
FDDdatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _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)
{
FDDdatasets.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 FDDEvents.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 FDDEvents.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 FDDEvents.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 FDDEvents.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 FDDEvents.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
);
}
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
} 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_)) / 100).mul(1000000000000000000)) / (round[_rID].keys))).mul(plyrRnds[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256)
{
uint256 _rID = rID_;
return
(
round[_rID].keys,
round[_rID].end,
round[_rID].strt,
round[_rID].pot,
round[_rID].plyr,
plyr_[round[_rID].plyr].addr,
plyr_[round[_rID].plyr].name,
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, FDDdatasets.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, _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 FDDEvents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, FDDdatasets.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, _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 FDDEvents.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, uint256 _affID, FDDdatasets.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) > 10000000000000000000)
{
uint256 _availableLimit = (10000000000000000000).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;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 100000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds[_pID][_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);
_eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_);
endTx(_pID, _eth, _keys, _eventData_);
}
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
round_ = round[_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 _eth)
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].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), "only PlayerBook can call this function");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "only PlayerBook can call this function");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(FDDdatasets.EventReturns memory _eventData_)
private
returns (FDDdatasets.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 managePlayer(uint256 _pID, FDDdatasets.EventReturns memory _eventData_)
private
returns (FDDdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(FDDdatasets.EventReturns memory _eventData_)
private
returns (FDDdatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round[_rID].plyr;
uint256 _pot = round[_rID].pot;
uint256 _win = (_pot.mul(45)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_)) / 100;
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);
_com = _com.add(_dust);
}
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);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.newPot = _com;
rID_++;
_rID++;
round[_rID].strt = now + rndExtra_;
round[_rID].end = now + rndInit_ + rndExtra_;
round[_rID].pot = _com;
round_ = round[_rID];
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);
plyrRnds_[_pID] = plyrRnds[_pID][_rIDlast];
}
}
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);
round_ = round[_rID];
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, FDDdatasets.EventReturns memory _eventData_)
private
returns(FDDdatasets.EventReturns)
{
uint256 _com = _eth * 5 / 100;
uint256 _aff = _eth * 10 / 100;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit FDDEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now);
} else {
_com += _aff;
}
if (!address(Bank).call.value(_com)(bytes4(keccak256("deposit()"))))
{
}
return(_eventData_);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, FDDdatasets.EventReturns memory _eventData_)
private
returns(FDDdatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_)) / 100;
uint256 _air = (_eth / 20);
airDropPot_ = airDropPot_.add(_air);
uint256 _pot = (_eth.mul(20) / 100);
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;
round_ = round[_rID];
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);
plyrRnds_[_pID] = plyrRnds[_pID][_rID];
round_ = round[_rID];
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 _eth, uint256 _keys, FDDdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit FDDEvents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin);
require(activated_ == false, "FomoDD already activated");
activated_ = true;
rID_ = 1;
round[1].strt = now + rndExtra_;
round[1].end = now + rndInit_ + rndExtra_;
round_ = round[1];
}
}
library FDDdatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
}
struct Round {
uint256 plyr;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
}
}
library FDDKeysCalc {
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 BankInterfaceForForwarder {
function deposit() external payable returns(bool);
}
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));
}
} | 0 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
address addressOfTokenUsedAsReward
) {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 ether;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount / price);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
fundingGoalReached = false;
}
}
}
} | 1 |
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;
}
}
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 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
library CheckedERC20 {
using SafeMath for uint;
function isContract(address addr) internal view returns(bool result) {
assembly {
result := gt(extcodesize(addr), 0)
}
}
function handleReturnBool() internal pure returns(bool result) {
assembly {
switch returndatasize()
case 0 {
result := 1
}
case 32 {
returndatacopy(0, 0, 32)
result := mload(0)
}
default {
revert(0, 0)
}
}
}
function handleReturnBytes32() internal pure returns(bytes32 result) {
assembly {
switch eq(returndatasize(), 32)
case 1 {
returndatacopy(0, 0, 32)
result := mload(0)
}
switch gt(returndatasize(), 32)
case 1 {
returndatacopy(0, 64, 32)
result := mload(0)
}
switch lt(returndatasize(), 32)
case 1 {
revert(0, 0)
}
}
}
function asmTransfer(address token, address to, uint256 value) internal returns(bool) {
require(isContract(token));
require(token.call(bytes4(keccak256("transfer(address,uint256)")), to, value));
return handleReturnBool();
}
function asmTransferFrom(address token, address from, address to, uint256 value) internal returns(bool) {
require(isContract(token));
require(token.call(bytes4(keccak256("transferFrom(address,address,uint256)")), from, to, value));
return handleReturnBool();
}
function asmApprove(address token, address spender, uint256 value) internal returns(bool) {
require(isContract(token));
require(token.call(bytes4(keccak256("approve(address,uint256)")), spender, value));
return handleReturnBool();
}
function checkedTransfer(ERC20 token, address to, uint256 value) internal {
if (value > 0) {
uint256 balance = token.balanceOf(this);
asmTransfer(token, to, value);
require(token.balanceOf(this) == balance.sub(value), "checkedTransfer: Final balance didn't match");
}
}
function checkedTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
if (value > 0) {
uint256 toBalance = token.balanceOf(to);
asmTransferFrom(token, from, to, value);
require(token.balanceOf(to) == toBalance.add(value), "checkedTransfer: Final balance didn't match");
}
}
function asmName(address token) internal view returns(bytes32) {
require(isContract(token));
require(token.call(bytes4(keccak256("name()"))));
return handleReturnBytes32();
}
function asmSymbol(address token) internal view returns(bytes32) {
require(isContract(token));
require(token.call(bytes4(keccak256("symbol()"))));
return handleReturnBytes32();
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract 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;
}
}
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;
}
}
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC1003Caller is Ownable {
function makeCall(address target, bytes data) external payable onlyOwner returns (bool) {
return target.call.value(msg.value)(data);
}
}
contract ERC1003Token is ERC20 {
ERC1003Caller private _caller = new ERC1003Caller();
address[] internal _sendersStack;
function caller() public view returns(ERC1003Caller) {
return _caller;
}
function approveAndCall(address to, uint256 value, bytes data) public payable returns (bool) {
_sendersStack.push(msg.sender);
approve(to, value);
require(_caller.makeCall.value(msg.value)(to, data));
_sendersStack.length -= 1;
return true;
}
function transferAndCall(address to, uint256 value, bytes data) public payable returns (bool) {
transfer(to, value);
require(_caller.makeCall.value(msg.value)(to, data));
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
address spender = (from != address(_caller)) ? from : _sendersStack[_sendersStack.length - 1];
return super.transferFrom(spender, to, value);
}
}
contract IBasicMultiToken is ERC20 {
event Bundle(address indexed who, address indexed beneficiary, uint256 value);
event Unbundle(address indexed who, address indexed beneficiary, uint256 value);
function tokensCount() public view returns(uint256);
function tokens(uint i) public view returns(ERC20);
function bundlingEnabled() public view returns(bool);
function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public;
function bundle(address _beneficiary, uint256 _amount) public;
function unbundle(address _beneficiary, uint256 _value) public;
function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public;
function disableBundling() public;
function enableBundling() public;
bytes4 public constant InterfaceId_IBasicMultiToken = 0xd5c368b6;
}
contract BasicMultiToken is Ownable, StandardToken, DetailedERC20, ERC1003Token, IBasicMultiToken, SupportsInterfaceWithLookup {
using CheckedERC20 for ERC20;
using CheckedERC20 for DetailedERC20;
ERC20[] private _tokens;
uint private _inLendingMode;
bool private _bundlingEnabled = true;
event Bundle(address indexed who, address indexed beneficiary, uint256 value);
event Unbundle(address indexed who, address indexed beneficiary, uint256 value);
event BundlingStatus(bool enabled);
modifier notInLendingMode {
require(_inLendingMode == 0, "Operation can't be performed while lending");
_;
}
modifier whenBundlingEnabled {
require(_bundlingEnabled, "Bundling is disabled");
_;
}
constructor()
public DetailedERC20("", "", 0)
{
}
function init(ERC20[] tokens, string theName, string theSymbol, uint8 theDecimals) public {
require(decimals == 0, "constructor: decimals should be zero");
require(theDecimals > 0, "constructor: _decimals should not be zero");
require(bytes(theName).length > 0, "constructor: name should not be empty");
require(bytes(theSymbol).length > 0, "constructor: symbol should not be empty");
require(tokens.length >= 2, "Contract does not support less than 2 inner tokens");
name = theName;
symbol = theSymbol;
decimals = theDecimals;
_tokens = tokens;
_registerInterface(InterfaceId_IBasicMultiToken);
}
function tokensCount() public view returns(uint) {
return _tokens.length;
}
function tokens(uint i) public view returns(ERC20) {
return _tokens[i];
}
function inLendingMode() public view returns(uint) {
return _inLendingMode;
}
function bundlingEnabled() public view returns(bool) {
return _bundlingEnabled;
}
function bundleFirstTokens(address beneficiary, uint256 amount, uint256[] tokenAmounts) public whenBundlingEnabled notInLendingMode {
require(totalSupply_ == 0, "bundleFirstTokens: This method can be used with zero total supply only");
_bundle(beneficiary, amount, tokenAmounts);
}
function bundle(address beneficiary, uint256 amount) public whenBundlingEnabled notInLendingMode {
require(totalSupply_ != 0, "This method can be used with non zero total supply only");
uint256[] memory tokenAmounts = new uint256[](_tokens.length);
for (uint i = 0; i < _tokens.length; i++) {
tokenAmounts[i] = _tokens[i].balanceOf(this).mul(amount).div(totalSupply_);
}
_bundle(beneficiary, amount, tokenAmounts);
}
function unbundle(address beneficiary, uint256 value) public notInLendingMode {
unbundleSome(beneficiary, value, _tokens);
}
function unbundleSome(address beneficiary, uint256 value, ERC20[] someTokens) public notInLendingMode {
_unbundle(beneficiary, value, someTokens);
}
function disableBundling() public onlyOwner {
require(_bundlingEnabled, "Bundling is already disabled");
_bundlingEnabled = false;
emit BundlingStatus(false);
}
function enableBundling() public onlyOwner {
require(!_bundlingEnabled, "Bundling is already enabled");
_bundlingEnabled = true;
emit BundlingStatus(true);
}
function _bundle(address beneficiary, uint256 amount, uint256[] tokenAmounts) internal {
require(amount != 0, "Bundling amount should be non-zero");
require(_tokens.length == tokenAmounts.length, "Lenghts of _tokens and tokenAmounts array should be equal");
for (uint i = 0; i < _tokens.length; i++) {
require(tokenAmounts[i] != 0, "Token amount should be non-zero");
_tokens[i].checkedTransferFrom(msg.sender, this, tokenAmounts[i]);
}
totalSupply_ = totalSupply_.add(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Bundle(msg.sender, beneficiary, amount);
emit Transfer(0, beneficiary, amount);
}
function _unbundle(address beneficiary, uint256 value, ERC20[] someTokens) internal {
require(someTokens.length > 0, "Array of someTokens can't be empty");
uint256 totalSupply = totalSupply_;
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply_ = totalSupply.sub(value);
emit Unbundle(msg.sender, beneficiary, value);
emit Transfer(msg.sender, 0, value);
for (uint i = 0; i < someTokens.length; i++) {
for (uint j = 0; j < i; j++) {
require(someTokens[i] != someTokens[j], "unbundleSome: should not unbundle same token multiple times");
}
uint256 tokenAmount = someTokens[i].balanceOf(this).mul(value).div(totalSupply);
someTokens[i].checkedTransfer(beneficiary, tokenAmount);
}
}
function lend(address to, ERC20 token, uint256 amount, address target, bytes data) public payable {
uint256 prevBalance = token.balanceOf(this);
token.asmTransfer(to, amount);
_inLendingMode += 1;
require(caller().makeCall.value(msg.value)(target, data), "lend: arbitrary call failed");
_inLendingMode -= 1;
require(token.balanceOf(this) >= prevBalance, "lend: lended token must be refilled");
}
}
contract FeeBasicMultiToken is Ownable, BasicMultiToken {
using CheckedERC20 for ERC20;
uint256 constant public TOTAL_PERCRENTS = 1000000;
uint256 internal _lendFee;
function lendFee() public view returns(uint256) {
return _lendFee;
}
function setLendFee(uint256 theLendFee) public onlyOwner {
require(theLendFee <= 30000, "setLendFee: fee should be not greater than 3%");
_lendFee = theLendFee;
}
function lend(address to, ERC20 token, uint256 amount, address target, bytes data) public payable {
uint256 expectedBalance = token.balanceOf(this).mul(TOTAL_PERCRENTS.add(_lendFee)).div(TOTAL_PERCRENTS);
super.lend(to, token, amount, target, data);
require(token.balanceOf(this) >= expectedBalance, "lend: tokens must be returned with lend fee");
}
}
contract AstraBasicMultiToken is FeeBasicMultiToken {
function init(ERC20[] tokens, string theName, string theSymbol, uint8 ) public {
super.init(tokens, theName, theSymbol, 18);
}
} | 0 |
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 TOXToken is StandardToken {
string public name = 'TOXToken';
string public symbol = 'TOX';
uint public decimals = 8;
uint256 public createTime = 1527782400;
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 TOXToken() public {
totalSupply = 200000000 ;
balances[msg.sender] = totalSupply * 10 ** uint256(decimals);
}
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;
}
} | 0 |
pragma solidity 0.4.23;
contract AbstractToken {
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 Owned {
address public owner = msg.sender;
address public potentialOwner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyPotentialOwner {
require(msg.sender == potentialOwner);
_;
}
event NewOwner(address old, address current);
event NewPotentialOwner(address old, address potential);
function setOwner(address _new)
public
onlyOwner
{
emit NewPotentialOwner(owner, _new);
potentialOwner = _new;
}
function confirmOwnership()
public
onlyPotentialOwner
{
emit NewOwner(owner, potentialOwner);
owner = potentialOwner;
potentialOwner = address(0);
}
}
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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function pow(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a ** b;
assert(c >= a);
return c;
}
}
contract StandardToken is AbstractToken, Owned, SafeMath {
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public totalSupply;
function transfer(address _to, uint256 _value) public returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(allowed[_from][msg.sender] >= _value);
allowed[_from][msg.sender] -= _value;
return _transfer(_from, _to, _value);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function _transfer(address _from, address _to, uint256 _value) private returns (bool success) {
require(_to != address(0));
require(balances[_from] >= _value);
balances[_from] -= _value;
balances[_to] = add(balances[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
}
contract Token is StandardToken {
uint256 public creationTime;
function Token() public {
creationTime = now;
}
function transferERC20Token(AbstractToken _token, address _to, uint256 _value)
public
onlyOwner
returns (bool success)
{
require(_token.balanceOf(address(this)) >= _value);
uint256 receiverBalance = _token.balanceOf(_to);
require(_token.transfer(_to, _value));
uint256 receiverNewBalance = _token.balanceOf(_to);
assert(receiverNewBalance == add(receiverBalance, _value));
return true;
}
function increaseApproval(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _value);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _value) public returns (bool success) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_value > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = sub(oldValue, _value);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract GenesisCryptoTechnology is Token {
string constant public name = 'GenesisCryptoTechnology';
string constant public symbol = 'GCT';
uint8 constant public decimals = 8;
uint256 public exchangeRate = 5880;
address public investorsAllocation = address(0x11195539543Ec8E6fe7179112E42fe1d3c434Ed4);
uint256 public investorsTotal = 60000000e8;
address public overdraftAllocation = address(0xa218A1Ae3D584d02598C3c5Aa675E547bBeeE0E7);
uint256 public overdraftTotal = 20000000e8;
uint256 public overdraftPeriodAmount = 41666666e8;
uint256 public overdraftUnvested = 4e8;
uint256 public overdraftCliff = 5 * 30 days;
uint256 public overdraftPeriodLength = 810 days;
uint8 public overdraftPeriodsNumber = 6;
address public teamAllocation = address(0x4ee4562cc0eeC0381a974efffe768ce2017632Ad);
uint256 public teamTotal = 15000000e8;
uint256 public teamPeriodAmount = 7031250e8;
uint256 public teamUnvested = 0;
uint256 public teamCliff = 0;
uint256 public teamPeriodLength = 3 * 810 days;
uint8 public teamPeriodsNumber = 16;
address public communityAllocation = address(0x99559c417313e61aE699FD55B9A2FD533e97dAB1);
uint256 public communityTotal = 4000000e8;
uint256 public communityPeriodAmount = 8333333e8;
uint256 public communityUnvested = 10000002e8;
uint256 public communityCliff = 0;
uint256 public communityPeriodLength = 3 * 810 days;
uint8 public communityPeriodsNumber = 6;
address public advisersAllocation = address(0x3E553bB7c931DC752E9CDd7Acb52e6F0b2bEB35E);
uint256 public advisersTotal = 1000000e8;
uint256 public advisersPeriodAmount = 2291666e8;
uint256 public advisersUnvested = 25000008e8;
uint256 public advisersCliff = 0;
uint256 public advisersPeriodLength = 1 days;
uint8 public advisersPeriodsNumber = 12;
function GenesisCryptoTechnology() public {
totalSupply = 100000000e8;
balances[investorsAllocation] = investorsTotal;
balances[overdraftAllocation] = overdraftTotal;
balances[teamAllocation] = teamTotal;
balances[communityAllocation] = communityTotal;
balances[advisersAllocation] = advisersTotal;
allowed[investorsAllocation][msg.sender] = investorsTotal;
allowed[overdraftAllocation][msg.sender] = overdraftUnvested;
allowed[communityAllocation][msg.sender] = communityUnvested;
allowed[advisersAllocation][msg.sender] = advisersUnvested;
}
function distributeInvestorsTokens(address _to, uint256 _amountWithDecimals)
public
onlyOwner
{
require(transferFrom(investorsAllocation, _to, _amountWithDecimals));
}
function withdrawOverdraftTokens(address _to, uint256 _amountWithDecimals)
public
onlyOwner
{
allowed[overdraftAllocation][msg.sender] = allowance(overdraftAllocation, msg.sender);
require(transferFrom(overdraftAllocation, _to, _amountWithDecimals));
}
function withdrawTeamTokens(address _to, uint256 _amountWithDecimals)
public
onlyOwner
{
allowed[teamAllocation][msg.sender] = allowance(teamAllocation, msg.sender);
require(transferFrom(teamAllocation, _to, _amountWithDecimals));
}
function withdrawCommunityTokens(address _to, uint256 _amountWithDecimals)
public
onlyOwner
{
allowed[communityAllocation][msg.sender] = allowance(communityAllocation, msg.sender);
require(transferFrom(communityAllocation, _to, _amountWithDecimals));
}
function withdrawAdvisersTokens(address _to, uint256 _amountWithDecimals)
public
onlyOwner
{
allowed[advisersAllocation][msg.sender] = allowance(advisersAllocation, msg.sender);
require(transferFrom(advisersAllocation, _to, _amountWithDecimals));
}
function allowance(address _owner, address _spender)
public
view
returns (uint256 remaining)
{
if (_spender != owner) {
return allowed[_owner][_spender];
}
uint256 unlockedTokens;
uint256 spentTokens;
if (_owner == overdraftAllocation) {
unlockedTokens = _calculateUnlockedTokens(
overdraftCliff,
overdraftPeriodLength,
overdraftPeriodAmount,
overdraftPeriodsNumber,
overdraftUnvested
);
spentTokens = sub(overdraftTotal, balanceOf(overdraftAllocation));
} else if (_owner == teamAllocation) {
unlockedTokens = _calculateUnlockedTokens(
teamCliff,
teamPeriodLength,
teamPeriodAmount,
teamPeriodsNumber,
teamUnvested
);
spentTokens = sub(teamTotal, balanceOf(teamAllocation));
} else if (_owner == communityAllocation) {
unlockedTokens = _calculateUnlockedTokens(
communityCliff,
communityPeriodLength,
communityPeriodAmount,
communityPeriodsNumber,
communityUnvested
);
spentTokens = sub(communityTotal, balanceOf(communityAllocation));
} else if (_owner == advisersAllocation) {
unlockedTokens = _calculateUnlockedTokens(
advisersCliff,
advisersPeriodLength,
advisersPeriodAmount,
advisersPeriodsNumber,
advisersUnvested
);
spentTokens = sub(advisersTotal, balanceOf(advisersAllocation));
} else {
return allowed[_owner][_spender];
}
return sub(unlockedTokens, spentTokens);
}
function confirmOwnership()
public
onlyPotentialOwner
{
allowed[investorsAllocation][owner] = 0;
allowed[investorsAllocation][msg.sender] = balanceOf(investorsAllocation);
allowed[overdraftAllocation][owner] = 0;
allowed[teamAllocation][owner] = 0;
allowed[communityAllocation][owner] = 0;
allowed[advisersAllocation][owner] = 0;
super.confirmOwnership();
}
function _calculateUnlockedTokens(
uint256 _cliff,
uint256 _periodLength,
uint256 _periodAmount,
uint8 _periodsNumber,
uint256 _unvestedAmount
)
private
view
returns (uint256)
{
if (now < add(creationTime, _cliff)) {
return _unvestedAmount;
}
uint256 periods = div(sub(now, add(creationTime, _cliff)), _periodLength);
periods = periods > _periodsNumber ? _periodsNumber : periods;
return add(_unvestedAmount, mul(periods, _periodAmount));
}
} | 1 |
pragma solidity ^0.4.21;
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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BabyCoin is Ownable {
using SafeMath for uint256;
string public name;
string public symbol;
uint32 public decimals = 18;
uint256 public totalSupply;
uint256 public currentTotalSupply = 0;
uint256 public airdropNum = 2 ether;
uint256 public airdropSupply = 2000;
mapping(address => bool) touched;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function BabyCoin(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _airdrop(address _owner) internal {
if(!touched[_owner] && currentTotalSupply < airdropSupply) {
touched[_owner] = true;
balances[_owner] = balances[_owner].add(airdropNum);
currentTotalSupply = currentTotalSupply.add(airdropNum);
}
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0);
_airdrop(_from);
require(_value <= balances[_from]);
require(balances[_to] + _value >= balances[_to]);
uint256 previousBalances = balances[_from] + balances[_to];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
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;
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;
}
function getBalance(address _who) internal constant returns (uint256)
{
if(currentTotalSupply < airdropSupply && _who != owner) {
if(touched[_who])
return balances[_who];
else
return balances[_who].add(airdropNum);
} else
return balances[_who];
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return getBalance(_owner);
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29635200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xed62FBB9d6E15EcA1F1374457588585d22d17144;
}
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.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 _decimals
) public {
decimals = _decimals;
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract LadaToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function LadaToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol,
uint8 decimals,
address _owner
) TokenERC20(initialSupply, tokenName, tokenSymbol, decimals) public {
owner = _owner;
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value >= balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(address(this).balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 |
pragma solidity ^0.4.13;
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 ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool);
function transferFrom(address from, address to, uint value) returns (bool);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract StandardToken is ERC20 {
using SafeMath for uint;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function isToken() public constant returns (bool) {
return true;
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) returns (bool) {
require(balances[_from] >= _value && allowed[_from][_to] >= _value);
allowed[_from][_to] = allowed[_from][_to].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
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 (uint remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract EmeraldToken is StandardToken, Ownable {
string public name;
string public symbol;
uint public decimals;
mapping (address => bool) public producers;
bool public released = false;
modifier onlyProducer() {
require(producers[msg.sender] == true);
_;
}
modifier canTransfer(address _sender) {
if (_sender != owner)
require(released);
_;
}
modifier inProduction() {
require(!released);
_;
}
function EmeraldToken(string _name, string _symbol, uint _decimals) {
require(_decimals > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
producers[msg.sender] = true;
}
function setProducer(address _addr, bool _status) onlyOwner {
producers[_addr] = _status;
}
function produceEmeralds(address _receiver, uint _amount) onlyProducer inProduction {
balances[_receiver] = balances[_receiver].add(_amount);
totalSupply = totalSupply.add(_amount);
Transfer(0, _receiver, _amount);
}
function releaseTokenTransfer() onlyOwner {
released = true;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract Haltable is Ownable {
bool public halted = false;
modifier stopInEmergency {
require(!halted);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract TokenDistribution is Haltable {
using SafeMath for uint;
address public wallet;
uint public presaleStart;
uint public start;
uint public end;
EmeraldToken public token;
uint public weiGoal;
uint public weiPresaleMax;
uint public contributorsCount = 0;
uint public weiTotal = 0;
uint public weiDistributed = 0;
uint public maxCap;
uint public tokensSold = 0;
uint public loadedRefund = 0;
uint public weiRefunded = 0;
mapping (address => uint) public contributors;
mapping (address => uint) public presale;
enum States {Preparing, Presale, Waiting, Distribution, Success, Failure, Refunding}
event Contributed(address _contributor, uint _weiAmount, uint _tokenAmount);
event GoalReached(uint _weiAmount);
event LoadedRefund(address _address, uint _loadedRefund);
event Refund(address _contributor, uint _weiAmount);
modifier inState(States _state) {
require(getState() == _state);
_;
}
function TokenDistribution(EmeraldToken _token, address _wallet, uint _presaleStart, uint _start, uint _end,
uint _ethPresaleMaxNoDecimals, uint _ethGoalNoDecimals, uint _maxTokenCapNoDecimals) {
require(_token != address(0) && _wallet != address(0) && _presaleStart > 0 && _start > _presaleStart && _end > _start && _ethPresaleMaxNoDecimals > 0
&& _ethGoalNoDecimals > _ethPresaleMaxNoDecimals && _maxTokenCapNoDecimals > 0);
require(_token.isToken());
token = _token;
wallet = _wallet;
presaleStart = _presaleStart;
start = _start;
end = _end;
weiPresaleMax = _ethPresaleMaxNoDecimals * 1 ether;
weiGoal = _ethGoalNoDecimals * 1 ether;
maxCap = _maxTokenCapNoDecimals * 10 ** token.decimals();
}
function() payable {
buy();
}
function buy() payable stopInEmergency {
require(getState() == States.Presale || getState() == States.Distribution);
require(msg.value > 0);
if (getState() == States.Presale)
presale[msg.sender] = presale[msg.sender].add(msg.value);
else {
contributors[msg.sender] = contributors[msg.sender].add(msg.value);
weiDistributed = weiDistributed.add(msg.value);
}
contributeInternal(msg.sender, msg.value, getTokenAmount(msg.value));
}
function preallocate(address _receiver, uint _tokenAmountNoDecimals) onlyOwner stopInEmergency {
require(getState() != States.Failure && getState() != States.Refunding && !token.released());
uint tokenAmount = _tokenAmountNoDecimals * 10 ** token.decimals();
contributeInternal(_receiver, 0, tokenAmount);
}
function loadRefund() payable {
require(getState() == States.Failure || getState() == States.Refunding);
require(msg.value > 0);
loadedRefund = loadedRefund.add(msg.value);
LoadedRefund(msg.sender, msg.value);
}
function setDates(uint _presaleStart, uint _start, uint _end) onlyOwner {
require(_presaleStart > 0 && _start > _presaleStart && _end > _start);
presaleStart = _presaleStart;
start = _start;
end = _end;
}
function contributeInternal(address _receiver, uint _weiAmount, uint _tokenAmount) internal {
require(token.totalSupply().add(_tokenAmount) <= maxCap);
token.produceEmeralds(_receiver, _tokenAmount);
if (_weiAmount > 0)
wallet.transfer(_weiAmount);
if (contributors[_receiver] == 0) contributorsCount++;
tokensSold = tokensSold.add(_tokenAmount);
weiTotal = weiTotal.add(_weiAmount);
Contributed(_receiver, _weiAmount, _tokenAmount);
}
function refund() inState(States.Refunding) {
uint weiValue = contributors[msg.sender];
require(weiValue <= loadedRefund && weiValue <= this.balance);
msg.sender.transfer(weiValue);
contributors[msg.sender] = 0;
weiRefunded = weiRefunded.add(weiValue);
loadedRefund = loadedRefund.sub(weiValue);
Refund(msg.sender, weiValue);
}
function getState() constant returns (States) {
if (now < presaleStart) return States.Preparing;
if (now >= presaleStart && now < start && weiTotal < weiPresaleMax) return States.Presale;
if (now < start && weiTotal >= weiPresaleMax) return States.Waiting;
if (now >= start && now < end) return States.Distribution;
if (weiTotal >= weiGoal) return States.Success;
if (now >= end && weiTotal < weiGoal && loadedRefund == 0) return States.Failure;
if (loadedRefund > 0) return States.Refunding;
}
function getTokenAmount(uint _weiAmount) internal constant returns (uint) {
uint rate = 1000 * 10 ** 18 / 10 ** token.decimals();
uint tokenAmount = _weiAmount * rate;
if (getState() == States.Presale)
tokenAmount *= 2;
return tokenAmount;
}
} | 0 |
pragma solidity ^0.4.0;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract MyFirstEthereumToken {
address public owner;
string public name = "MyFirstEthereumToken";
string public symbol = "MFET";
uint8 public decimals = 18;
uint256 public totalSupply;
uint256 public totalExtraTokens = 0;
uint256 public totalContributed = 0;
bool public onSale = false;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowance;
event Sent(address from, address to, uint amount);
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
function name() public constant returns (string) { return name; }
function symbol() public constant returns (string) { return symbol; }
function decimals() public constant returns (uint8) { return decimals; }
function totalSupply() public constant returns (uint256) { return totalSupply; }
function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; }
function MyFirstEthereumToken(uint256 initialSupply) public payable
{
owner = msg.sender;
totalSupply = initialSupply * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success)
{
return _transfer(msg.sender, _to, _value);
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success)
{
require(_value > 0);
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint previousBalances = balances[_from] + balances[_to];
balances[_from] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
return true;
}
function send(address _to, uint256 _value) public
{
_send(_to, _value);
}
function _send(address _to, uint256 _value) internal
{
address _from = msg.sender;
require(_value > 0);
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint previousBalances = balances[_from] + balances[_to];
balances[_from] -= _value;
balances[_to] += _value;
Sent(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
{
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success)
{
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function createTokens(uint256 _amount) public
{
require(msg.sender == owner);
balances[owner] += _amount;
totalSupply += _amount;
Transfer(0, owner, _amount);
}
function safeWithdrawAll() public returns (bool)
{
require(msg.sender == owner);
uint256 _gasPrice = 30000000000;
require(this.balance > _gasPrice);
uint256 _totalAmount = this.balance - _gasPrice;
owner.transfer(_totalAmount);
return true;
}
function safeWithdraw(uint256 _amount) public returns (bool)
{
require(msg.sender == owner);
uint256 _gasPrice = 30000000000;
require(_amount > 0);
uint256 totalAmount = _amount + _gasPrice;
require(this.balance >= totalAmount);
owner.transfer(totalAmount);
return true;
}
function getBalanceContract() public constant returns(uint)
{
require(msg.sender == owner);
return this.balance;
}
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 <= allowance[_from][msg.sender]);
balances[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
function buyTokens () public payable
{
require(msg.value > 0);
require(onSale == true);
owner.transfer(msg.value);
totalContributed += msg.value;
uint256 tokensAmount = msg.value * 1000;
if(totalContributed >= 1 ether)
{
uint256 multiplier = (totalContributed / 1 ether);
uint256 extraTokens = (tokensAmount * multiplier) / 10;
totalExtraTokens += extraTokens;
tokensAmount += extraTokens;
}
balances[msg.sender] += tokensAmount;
totalSupply += tokensAmount;
Transfer(address(this), msg.sender, tokensAmount);
}
function enableSale() public
{
require(msg.sender == owner);
onSale = true;
}
function disableSale() public
{
require(msg.sender == owner);
onSale = false;
}
function kill() public
{
require(msg.sender == owner);
onSale = false;
selfdestruct(owner);
}
function() public payable
{
buyTokens();
}
} | 1 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public { owner = msg.sender; }
modifier onlyOwner() {
address sender = msg.sender;
address _owner = owner;
require(msg.sender == _owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, 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));
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 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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(0x0, _to, _amount);
return true;
}
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract BrickToken is MintableToken {
string public constant name = "Brick";
string public constant symbol = "BRK";
uint8 public constant decimals = 18;
function getTotalSupply() view public returns (uint256) {
return totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
super.transfer(_to, _value);
}
}
contract BrickCrowdsale is Ownable {
using SafeMath for uint256;
uint256 public startTime;
uint256 public endTime;
uint256 public weiRaised;
uint256 public limitDateSale;
uint256 public currentTime;
bool public isSoftCapHit = false;
bool public isStarted = false;
bool public isFinalized = false;
uint256 icoPvtRate = 40;
uint256 icoPreRate = 50;
uint256 ico1Rate = 65;
uint256 ico2Rate = 75;
uint256 ico3Rate = 90;
uint256 public pvtTokens = (40000) * (10**18);
uint256 public preSaleTokens = (6000000) * (10**18);
uint256 public ico1Tokens = (8000000) * (10**18);
uint256 public ico2Tokens = (8000000) * (10**18);
uint256 public ico3Tokens = (8000000) * (10**18);
uint256 public totalTokens = (40000000)* (10**18);
address public advisoryEthWallet = 0x0D7629d32546CD493bc33ADEF115D4489f5599Be;
address public infraEthWallet = 0x536D36a05F6592aa29BB0beE30cda706B1272521;
address public techDevelopmentEthWallet = 0x4d0B70d8E612b5dca3597C64643a8d1efd5965e1;
address public operationsEthWallet = 0xbc67B82924eEc8643A4f2ceDa59B5acfd888A967;
address public wallet = 0x44d44CA0f75bdd3AE8806D02515E8268459c554A;
struct ContributorData {
uint256 contributionAmount;
uint256 tokensIssued;
}
mapping(address => ContributorData) public contributorList;
mapping(uint => address) contributorIndexes;
uint nextContributorIndex;
constructor() public {}
function init( uint256 _tokensForCrowdsale, uint256 _etherInUSD, address _tokenAddress, uint256 _softCapInEthers, uint256 _hardCapInEthers,
uint _saleDurationInDays, uint bonus) onlyOwner public {
currentTime = now;
setTokensForCrowdSale(_tokensForCrowdsale);
setRate(_etherInUSD);
setTokenAddress(_tokenAddress);
setSoftCap(_softCapInEthers);
setHardCap(_hardCapInEthers);
setSaleDuration(_saleDurationInDays);
setSaleBonus(bonus);
start();
}
function start() onlyOwner public {
require(!isStarted);
require(!hasStarted());
require(tokenAddress != address(0));
require(saleDuration != 0);
require(totalTokens != 0);
require(tokensForCrowdSale != 0);
require(softCap != 0);
require(hardCap != 0);
starting();
emit BrickStarted();
isStarted = true;
}
function splitTokens() internal {
token.mint(techDevelopmentEthWallet, totalTokens.mul(3).div(100));
tokensIssuedTillNow = tokensIssuedTillNow + totalTokens.mul(3).div(100);
token.mint(operationsEthWallet, totalTokens.mul(7).div(100));
tokensIssuedTillNow = tokensIssuedTillNow + totalTokens.mul(7).div(100);
}
uint256 public tokensForCrowdSale = 0;
function setTokensForCrowdSale(uint256 _tokensForCrowdsale) onlyOwner public {
tokensForCrowdSale = _tokensForCrowdsale.mul(10 ** 18);
}
uint256 public rate=0;
uint256 public etherInUSD;
function setRate(uint256 _etherInUSD) internal {
etherInUSD = _etherInUSD;
rate = getCurrentRateInCents().mul(10**18).div(100).div(_etherInUSD);
}
function setRate(uint256 rateInCents, uint256 _etherInUSD) public onlyOwner {
etherInUSD = _etherInUSD;
rate = rateInCents.mul(10**18).div(100).div(_etherInUSD);
}
function updateRateInWei() internal {
require(etherInUSD != 0);
rate = getCurrentRateInCents().mul(10**18).div(100).div(etherInUSD);
}
function getCurrentRateInCents() public view returns (uint256)
{
if(currentRound == 1) {
return icoPvtRate;
} else if(currentRound == 2) {
return icoPreRate;
} else if(currentRound == 3) {
return ico1Rate;
} else if(currentRound == 4) {
return ico2Rate;
} else if(currentRound == 5) {
return ico3Rate;
} else {
return ico3Rate;
}
}
BrickToken public token;
address tokenAddress = 0x0;
function setTokenAddress(address _tokenAddress) public onlyOwner {
tokenAddress = _tokenAddress;
token = BrickToken(_tokenAddress);
}
function setPvtTokens (uint256 _pvtTokens)onlyOwner public {
require(!icoPvtEnded);
pvtTokens = (_pvtTokens).mul(10 ** 18);
}
function setPreSaleTokens (uint256 _preSaleTokens)onlyOwner public {
require(!icoPreEnded);
preSaleTokens = (_preSaleTokens).mul(10 ** 18);
}
function setIco1Tokens (uint256 _ico1Tokens)onlyOwner public {
require(!ico1Ended);
ico1Tokens = (_ico1Tokens).mul(10 ** 18);
}
function setIco2Tokens (uint256 _ico2Tokens)onlyOwner public {
require(!ico2Ended);
ico2Tokens = (_ico2Tokens).mul(10 ** 18);
}
function setIco3Tokens (uint256 _ico3Tokens)onlyOwner public {
require(!ico3Ended);
ico3Tokens = (_ico3Tokens).mul(10 ** 18);
}
uint256 public softCap = 0;
function setSoftCap(uint256 _softCap) onlyOwner public {
softCap = _softCap.mul(10 ** 18);
}
uint256 public hardCap = 0;
function setHardCap(uint256 _hardCap) onlyOwner public {
hardCap = _hardCap.mul(10 ** 18);
}
uint public saleDuration = 0;
function setSaleDuration(uint _saleDurationInDays) onlyOwner public {
saleDuration = _saleDurationInDays;
limitDateSale = startTime.add(saleDuration * 1 days);
endTime = limitDateSale;
}
uint public saleBonus = 0;
function setSaleBonus(uint bonus) public onlyOwner{
saleBonus = bonus;
}
function () public payable {
buyPhaseTokens(msg.sender);
}
function transferTokenOwnership(address _address) onlyOwner public {
token.transferOwnership(_address);
}
function releaseTokens(address _contributerAddress, uint256 tokensOfContributor) internal {
token.mint(_contributerAddress, tokensOfContributor);
}
function currentTokenSupply() public view returns(uint256){
return token.getTotalSupply();
}
function buyPhaseTokens(address beneficiary) public payable
{
assert(!ico3Ended);
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = computeTokens(weiAmount);
require(isWithinTokenAllocLimit(tokens));
if(int(pvtTokens - tokensIssuedTillNow) > 0) {
require(int (tokens) < (int(pvtTokens - tokensIssuedTillNow)));
buyTokens(tokens,weiAmount,beneficiary);
} else if (int (preSaleTokens + pvtTokens - tokensIssuedTillNow) > 0) {
require(int(tokens) < (int(preSaleTokens + pvtTokens - tokensIssuedTillNow)));
buyTokens(tokens,weiAmount,beneficiary);
} else if(int(ico1Tokens + preSaleTokens + pvtTokens - tokensIssuedTillNow) > 0) {
require(int(tokens) < (int(ico1Tokens + preSaleTokens + pvtTokens -tokensIssuedTillNow)));
buyTokens(tokens,weiAmount,beneficiary);
} else if(int(ico2Tokens + ico1Tokens + preSaleTokens + pvtTokens - (tokensIssuedTillNow)) > 0) {
require(int(tokens) < (int(ico2Tokens + ico1Tokens + preSaleTokens + pvtTokens - (tokensIssuedTillNow))));
buyTokens(tokens,weiAmount,beneficiary);
} else if(!ico3Ended && (int(tokensForCrowdSale - (tokensIssuedTillNow)) > 0)) {
require(int(tokens) < (int(tokensForCrowdSale - (tokensIssuedTillNow))));
buyTokens(tokens,weiAmount,beneficiary);
}
}
uint256 public tokensIssuedTillNow=0;
function buyTokens(uint256 tokens, uint256 weiAmount ,address beneficiary) internal {
weiRaised = weiRaised.add(weiAmount);
if (contributorList[beneficiary].contributionAmount == 0) {
contributorIndexes[nextContributorIndex] = beneficiary;
nextContributorIndex += 1;
}
contributorList[beneficiary].contributionAmount += weiAmount;
contributorList[beneficiary].tokensIssued += tokens;
tokensIssuedTillNow = tokensIssuedTillNow + tokens;
releaseTokens(beneficiary, tokens);
forwardFunds();
emit BrickTokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
event BrickTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function investorCount() constant public returns(uint) {
return nextContributorIndex;
}
function hasStarted() public constant returns (bool) {
return (startTime != 0 && now > startTime);
}
function isWithinSaleTimeLimit() internal view returns (bool) {
return now <= limitDateSale;
}
function isWithinSaleLimit(uint256 _tokens) internal view returns (bool) {
return token.getTotalSupply().add(_tokens) <= tokensForCrowdSale;
}
function computeTokens(uint256 weiAmount) view internal returns (uint256) {
return weiAmount.mul(10 ** 18).div(rate);
}
function isWithinTokenAllocLimit(uint256 _tokens) view internal returns (bool) {
return (isWithinSaleTimeLimit() && isWithinSaleLimit(_tokens));
}
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= hardCap;
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return (withinPeriod && nonZeroPurchase) && withinCap && isWithinSaleTimeLimit();
}
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= hardCap;
return (endTime != 0 && now > endTime) || capReached;
}
event BrickStarted();
event BrickFinalized();
function finalize() onlyOwner public {
require(!isFinalized);
finalization();
emit BrickFinalized();
isFinalized = true;
}
function starting() internal {
startTime = now;
limitDateSale = startTime.add(saleDuration * 1 days);
endTime = limitDateSale;
}
function finalization() internal {
splitTokens();
token.mint(wallet, totalTokens.sub(tokensIssuedTillNow));
if(address(this).balance > 0){
processFundsIfAny();
}
}
function forwardFunds() internal {
require(advisoryEthWallet != address(0));
require(infraEthWallet != address(0));
require(techDevelopmentEthWallet != address(0));
require(operationsEthWallet != address(0));
operationsEthWallet.transfer(msg.value.mul(60).div(100));
advisoryEthWallet.transfer(msg.value.mul(5).div(100));
infraEthWallet.transfer(msg.value.mul(10).div(100));
techDevelopmentEthWallet.transfer(msg.value.mul(25).div(100));
}
function processFundsIfAny() internal {
require(advisoryEthWallet != address(0));
require(infraEthWallet != address(0));
require(techDevelopmentEthWallet != address(0));
require(operationsEthWallet != address(0));
operationsEthWallet.transfer(address(this).balance.mul(60).div(100));
advisoryEthWallet.transfer(address(this).balance.mul(5).div(100));
infraEthWallet.transfer(address(this).balance.mul(10).div(100));
techDevelopmentEthWallet.transfer(address(this).balance.mul(25).div(100));
}
uint256 public currentRound = 1;
bool public icoPvtEnded = false;
bool public icoPreEnded = false;
bool public ico1Ended = false;
bool public ico2Ended = false;
bool public ico3Ended = false;
function endPvtSale() onlyOwner public
{
require(!icoPvtEnded);
pvtTokens = tokensIssuedTillNow;
currentRound = 2;
updateRateInWei();
icoPvtEnded = true;
}
function endPreSale() onlyOwner public
{
require(!icoPreEnded && icoPvtEnded);
preSaleTokens = tokensIssuedTillNow - pvtTokens;
currentRound = 3;
updateRateInWei();
icoPreEnded = true;
}
function endIcoSaleRound1() onlyOwner public
{
require(!ico1Ended && icoPreEnded);
ico1Tokens = tokensIssuedTillNow - preSaleTokens - pvtTokens;
currentRound = 4;
updateRateInWei();
ico1Ended = true;
}
function endIcoSaleRound2() onlyOwner public
{
require(!ico2Ended && ico1Ended);
ico2Tokens = tokensIssuedTillNow - ico1Tokens - preSaleTokens - pvtTokens;
currentRound = 5;
updateRateInWei();
ico2Ended=true;
}
function endIcoSaleRound3() onlyOwner public
{
require(!ico3Ended && ico2Ended);
ico3Tokens = tokensIssuedTillNow - ico2Tokens - ico1Tokens - preSaleTokens - pvtTokens;
updateRateInWei();
ico3Ended = true;
}
modifier afterDeadline() { if (hasEnded() || isFinalized) _; }
function selfDestroy(address _address) public onlyOwner {
assert(isFinalized);
selfdestruct(_address);
}
} | 0 |
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
return false;
}
function balanceOf(address _owner) public 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);
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;
uint constant MAX_UINT = 2**256 - 1;
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);
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) returns (bool) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract TestToken is StandardToken {
string constant public name = "Test Token";
string constant public symbol = "TEST";
uint8 constant public decimals = 18;
uint public totalSupply = 10**27;
function TestToken() {
balances[0x5A2143B894C9E8d8DFe2A0e8B80d7DB2689fC382] = totalSupply;
}
} | 1 |
pragma solidity ^0.4.24;
contract Base
{
uint8 constant HEROLEVEL_MIN = 1;
uint8 constant HEROLEVEL_MAX = 5;
uint8 constant LIMITCHIP_MINLEVEL = 3;
uint constant PARTWEIGHT_NORMAL = 100;
uint constant PARTWEIGHT_LIMIT = 40;
address creator;
constructor() public
{
creator = msg.sender;
}
modifier CreatorAble()
{
require(msg.sender == creator);
_;
}
function IsLimitPart(uint8 level, uint part) internal pure returns(bool)
{
if (level < LIMITCHIP_MINLEVEL) return false;
if (part < GetPartNum(level)) return false;
return true;
}
function GetPartWeight(uint8 level, uint part) internal pure returns(uint)
{
if (IsLimitPart(level, part)) return PARTWEIGHT_LIMIT;
return PARTWEIGHT_NORMAL;
}
function GetPartNum(uint8 level) internal pure returns(uint)
{
if (level <= 2) return 3;
else if (level <= 4) return 4;
return 5;
}
function GetPartLimit(uint8 level, uint part) internal pure returns(uint8)
{
if (!IsLimitPart(level, part)) return 0;
if (level == 5) return 1;
if (level == 4) return 8;
return 15;
}
}
contract BasicAuth is Base
{
mapping(address => bool) auth_list;
modifier OwnerAble(address acc)
{
require(acc == tx.origin);
_;
}
modifier AuthAble()
{
require(auth_list[msg.sender]);
_;
}
modifier ValidHandleAuth()
{
require(tx.origin==creator || msg.sender==creator);
_;
}
function SetAuth(address target) external ValidHandleAuth
{
auth_list[target] = true;
}
function ClearAuth(address target) external ValidHandleAuth
{
delete auth_list[target];
}
}
library IndexList
{
function insert(uint32[] storage self, uint32 index, uint pos) external
{
require(self.length >= pos);
self.length++;
for (uint i=self.length; i>pos; i++)
{
self[i+1] = self[i];
}
self[pos] = index;
}
function remove(uint32[] storage self, uint32 index) external returns(bool)
{
return remove(self,index,0);
}
function remove(uint32[] storage self, uint32 index, uint startPos) public returns(bool)
{
for (uint i=startPos; i<self.length; i++)
{
if (self[i] != index) continue;
for (uint j=i; j<self.length-1; j++)
{
self[j] = self[j+1];
}
delete self[self.length-1];
self.length--;
return true;
}
return false;
}
}
contract MainCard is BasicAuth
{
struct Card {
uint32 m_Index;
uint32 m_Duration;
uint8 m_Level;
uint16 m_DP;
uint16 m_DPK;
uint16 m_SP;
uint16 m_IP;
uint32[] m_Parts;
}
struct CardLib {
uint32[] m_List;
mapping(uint32 => Card) m_Lib;
}
CardLib g_CardLib;
function AddNewCard(uint32 iCard, uint32 duration, uint8 level, uint16 dp, uint16 dpk, uint16 sp, uint16 ip, uint32[] parts) internal
{
g_CardLib.m_List.push(iCard);
g_CardLib.m_Lib[iCard] = Card({
m_Index : iCard,
m_Duration: duration,
m_Level : level,
m_DP : dp,
m_DPK : dpk,
m_SP : sp,
m_IP : ip,
m_Parts : parts
});
}
function CardExists(uint32 iCard) public view returns(bool)
{
Card storage obj = g_CardLib.m_Lib[iCard];
return obj.m_Index == iCard;
}
function GetCard(uint32 iCard) internal view returns(Card storage)
{
return g_CardLib.m_Lib[iCard];
}
function GetCardInfo(uint32 iCard) external view returns(uint32, uint32, uint8, uint16, uint16, uint16, uint16, uint32[])
{
Card storage obj = GetCard(iCard);
return (obj.m_Index, obj.m_Duration, obj.m_Level, obj.m_DP, obj.m_DPK, obj.m_SP, obj.m_IP, obj.m_Parts);
}
function GetExistsCardList() external view returns(uint32[])
{
return g_CardLib.m_List;
}
}
contract MainChip is BasicAuth
{
using IndexList for uint32[];
struct Chip
{
uint8 m_Level;
uint8 m_LimitNum;
uint8 m_Part;
uint32 m_Index;
uint256 m_UsedNum;
}
struct PartManager
{
uint32[] m_IndexList;
uint32[] m_UnableList;
}
struct ChipLib
{
uint32[] m_List;
mapping(uint32 => Chip) m_Lib;
mapping(uint32 => uint[]) m_TempList;
mapping(uint8 => mapping(uint => PartManager)) m_PartMap;
}
ChipLib g_ChipLib;
function AddNewChip(uint32 iChip, uint8 lv, uint8 limit, uint8 part) internal
{
require(!ChipExists(iChip));
g_ChipLib.m_List.push(iChip);
g_ChipLib.m_Lib[iChip] = Chip({
m_Index : iChip,
m_Level : lv,
m_LimitNum : limit,
m_Part : part,
m_UsedNum : 0
});
PartManager storage pm = GetPartManager(lv,part);
pm.m_IndexList.push(iChip);
}
function GetChip(uint32 iChip) internal view returns(Chip storage)
{
return g_ChipLib.m_Lib[iChip];
}
function GetPartManager(uint8 level, uint iPart) internal view returns(PartManager storage)
{
return g_ChipLib.m_PartMap[level][iPart];
}
function ChipExists(uint32 iChip) public view returns(bool)
{
Chip storage obj = GetChip(iChip);
return obj.m_Index == iChip;
}
function GetChipUsedNum(uint32 iChip) internal view returns(uint)
{
Chip storage obj = GetChip(iChip);
uint[] memory tempList = g_ChipLib.m_TempList[iChip];
uint num = tempList.length;
for (uint i=num; i>0; i--)
{
if(tempList[i-1]<=now) {
num -= i;
break;
}
}
return obj.m_UsedNum + num;
}
function CanObtainChip(uint32 iChip) internal view returns(bool)
{
Chip storage obj = GetChip(iChip);
if (obj.m_LimitNum == 0) return true;
if (GetChipUsedNum(iChip) < obj.m_LimitNum) return true;
return false;
}
function CostChip(uint32 iChip) internal
{
BeforeChipCost(iChip);
Chip storage obj = GetChip(iChip);
obj.m_UsedNum--;
}
function ObtainChip(uint32 iChip) internal
{
BeforeChipObtain(iChip);
Chip storage obj = GetChip(iChip);
obj.m_UsedNum++;
}
function BeforeChipObtain(uint32 iChip) internal
{
Chip storage obj = GetChip(iChip);
if (obj.m_LimitNum == 0) return;
uint usedNum = GetChipUsedNum(iChip);
require(obj.m_LimitNum >= usedNum+1);
if (obj.m_LimitNum == usedNum+1) {
PartManager storage pm = GetPartManager(obj.m_Level,obj.m_Part);
if (pm.m_IndexList.remove(iChip)){
pm.m_UnableList.push(iChip);
}
}
}
function BeforeChipCost(uint32 iChip) internal
{
Chip storage obj = GetChip(iChip);
if (obj.m_LimitNum == 0) return;
uint usedNum = GetChipUsedNum(iChip);
require(obj.m_LimitNum >= usedNum);
if (obj.m_LimitNum == usedNum) {
PartManager storage pm = GetPartManager(obj.m_Level,obj.m_Part);
if (pm.m_UnableList.remove(iChip)) {
pm.m_IndexList.push(iChip);
}
}
}
function AddChipTempTime(uint32 iChip, uint expireTime) internal
{
uint[] storage list = g_ChipLib.m_TempList[iChip];
require(list.length==0 || expireTime>=list[list.length-1]);
BeforeChipObtain(iChip);
list.push(expireTime);
}
function RefreshChipUnableList(uint8 level) internal
{
uint partNum = GetPartNum(level);
for (uint iPart=1; iPart<=partNum; iPart++)
{
PartManager storage pm = GetPartManager(level,iPart);
for (uint i=pm.m_UnableList.length; i>0; i--)
{
uint32 iChip = pm.m_UnableList[i-1];
if (CanObtainChip(iChip)) {
pm.m_IndexList.push(iChip);
pm.m_UnableList.remove(iChip,i-1);
}
}
}
}
function GenChipByWeight(uint random, uint8 level, uint[] extWeight) internal view returns(uint32)
{
uint partNum = GetPartNum(level);
uint allWeight;
uint[] memory newWeight = new uint[](partNum+1);
uint[] memory realWeight = new uint[](partNum+1);
for (uint iPart=1; iPart<=partNum; iPart++)
{
PartManager storage pm = GetPartManager(level,iPart);
uint curWeight = extWeight[iPart-1]+GetPartWeight(level,iPart);
allWeight += pm.m_IndexList.length*curWeight;
newWeight[iPart] = allWeight;
realWeight[iPart] = curWeight;
}
uint weight = random % allWeight;
for (iPart=1; iPart<=partNum; iPart++)
{
if (weight >= newWeight[iPart]) continue;
pm = GetPartManager(level,iPart);
uint idx = (weight-newWeight[iPart-1])/realWeight[iPart];
return pm.m_IndexList[idx];
}
}
function GetChipInfo(uint32 iChip) external view returns(uint32, uint8, uint8, uint, uint8, uint)
{
Chip storage obj = GetChip(iChip);
return (obj.m_Index, obj.m_Level, obj.m_LimitNum, GetPartWeight(obj.m_Level,obj.m_Part), obj.m_Part, GetChipUsedNum(iChip));
}
function GetExistsChipList() external view returns(uint32[])
{
return g_ChipLib.m_List;
}
}
contract BasicTime
{
uint constant DAY_SECONDS = 60 * 60 * 24;
function GetDayCount(uint timestamp) pure internal returns(uint)
{
return timestamp/DAY_SECONDS;
}
function GetExpireTime(uint timestamp, uint dayCnt) pure internal returns(uint)
{
uint dayEnd = GetDayCount(timestamp) + dayCnt;
return dayEnd * DAY_SECONDS;
}
}
library ItemList {
struct Data {
uint32[] m_List;
mapping(uint32 => uint) m_Maps;
}
function set(Data storage self, uint32 key, uint num) public
{
if (!has(self,key)) {
if (num == 0) return;
self.m_List.push(key);
self.m_Maps[key] = num;
}
else if (num == 0) {
delete self.m_Maps[key];
}
else {
uint old = self.m_Maps[key];
if (old == num) return;
self.m_Maps[key] = num;
}
}
function add(Data storage self, uint32 key, uint num) external
{
uint iOld = get(self,key);
uint iNow = iOld+num;
require(iNow >= iOld);
set(self,key,iNow);
}
function sub(Data storage self, uint32 key, uint num) external
{
uint iOld = get(self,key);
require(iOld >= num);
set(self,key,iOld-num);
}
function has(Data storage self, uint32 key) public view returns(bool)
{
return self.m_Maps[key] > 0;
}
function get(Data storage self, uint32 key) public view returns(uint)
{
return self.m_Maps[key];
}
function list(Data storage self) view external returns(uint32[],uint[])
{
uint len = self.m_List.length;
uint[] memory values = new uint[](len);
for (uint i=0; i<len; i++)
{
uint32 key = self.m_List[i];
values[i] = self.m_Maps[key];
}
return (self.m_List,values);
}
function isEmpty(Data storage self) view external returns(bool)
{
return self.m_List.length == 0;
}
function keys(Data storage self) view external returns(uint32[])
{
return self.m_List;
}
}
contract MainBonus is BasicTime,BasicAuth,MainCard
{
uint constant BASERATIO = 10000;
struct PlayerBonus
{
uint m_Bonus;
uint m_DrawedDay;
uint16 m_DDPermanent;
mapping(uint => uint16) m_DayStatic;
mapping(uint => uint16) m_DayPermanent;
mapping(uint => uint32[]) m_DayDynamic;
}
struct DayRatio
{
uint16 m_Static;
uint16 m_Permanent;
uint32[] m_DynamicCard;
mapping(uint32 => uint) m_CardNum;
}
struct BonusData
{
uint m_RewardBonus;
uint m_RecordDay;
uint m_RecordBonus;
uint m_RecordPR;
mapping(uint => DayRatio) m_DayRatio;
mapping(uint => uint) m_DayBonus;
mapping(address => PlayerBonus) m_PlayerBonus;
}
address receiver;
BonusData g_Bonus;
constructor(address Receiver) public
{
g_Bonus.m_RecordDay = GetDayCount(now);
receiver = Receiver;
}
function() external payable {}
function NeedRefresh(uint dayNo) internal view returns(bool)
{
if (g_Bonus.m_RecordBonus == 0) return false;
if (g_Bonus.m_RecordDay == dayNo) return false;
return true;
}
function PlayerNeedRefresh(address acc, uint dayNo) internal view returns(bool)
{
if (g_Bonus.m_RecordBonus == 0) return false;
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
if (pb.m_DrawedDay == dayNo) return false;
return true;
}
function GetDynamicRatio(uint dayNo) internal view returns(uint tempRatio)
{
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
for (uint i=0; i<dr.m_DynamicCard.length; i++)
{
uint32 iCard = dr.m_DynamicCard[i];
uint num = dr.m_CardNum[iCard];
Card storage oCard = GetCard(iCard);
tempRatio += num*oCard.m_DP*oCard.m_DPK/(oCard.m_DPK+num);
}
}
function GenDayRatio(uint dayNo) internal view returns(uint iDR)
{
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
iDR += dr.m_Permanent;
iDR += dr.m_Static;
iDR += GetDynamicRatio(dayNo);
}
function GetDynamicCardNum(uint32 iCard, uint dayNo) internal view returns(uint num)
{
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
num = dr.m_CardNum[iCard];
}
function GetPlayerDynamicRatio(address acc, uint dayNo) internal view returns(uint tempRatio)
{
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
uint32[] storage cards = pb.m_DayDynamic[dayNo];
for (uint idx=0; idx<cards.length; idx++)
{
uint32 iCard = cards[idx];
uint num = dr.m_CardNum[iCard];
Card storage oCard = GetCard(iCard);
tempRatio += oCard.m_DP*oCard.m_DPK/(oCard.m_DPK+num);
}
}
function GenPlayerRatio(address acc, uint dayNo) internal view returns(uint tempRatio)
{
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
tempRatio += pb.m_DayPermanent[dayNo];
tempRatio += pb.m_DayStatic[dayNo];
tempRatio += GetPlayerDynamicRatio(acc,dayNo);
}
function RefreshDayBonus() internal
{
uint todayNo = GetDayCount(now);
if (!NeedRefresh(todayNo)) return;
uint tempBonus = g_Bonus.m_RecordBonus;
uint tempPR = g_Bonus.m_RecordPR;
uint tempRatio;
for (uint dayNo=g_Bonus.m_RecordDay; dayNo<todayNo; dayNo++)
{
tempRatio = tempPR+GenDayRatio(dayNo);
if (tempRatio == 0) continue;
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
tempPR += dr.m_Permanent;
g_Bonus.m_DayBonus[dayNo] = tempBonus;
tempBonus -= tempBonus*tempRatio/BASERATIO;
}
g_Bonus.m_RecordPR = tempPR;
g_Bonus.m_RecordDay = todayNo;
g_Bonus.m_RecordBonus = tempBonus;
}
function QueryPlayerBonus(address acc, uint todayNo) view internal returns(uint accBonus,uint16 accPR)
{
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
accPR = pb.m_DDPermanent;
accBonus = pb.m_Bonus;
if (!PlayerNeedRefresh(acc, todayNo)) return;
uint tempBonus = g_Bonus.m_RecordBonus;
uint tempPR = g_Bonus.m_RecordPR;
uint dayNo = pb.m_DrawedDay;
if (dayNo == 0) return;
for (; dayNo<todayNo; dayNo++)
{
uint tempRatio = tempPR+GenDayRatio(dayNo);
if (tempRatio == 0) continue;
uint accRatio = accPR+GenPlayerRatio(acc,dayNo);
accPR += pb.m_DayPermanent[dayNo];
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
if (dayNo >= g_Bonus.m_RecordDay) {
tempPR += dr.m_Permanent;
accBonus += tempBonus*accRatio/BASERATIO;
tempBonus -= tempBonus*tempRatio/BASERATIO;
}
else {
if (accRatio == 0) continue;
accBonus += g_Bonus.m_DayBonus[dayNo]*accRatio/BASERATIO;
}
}
}
function GetDynamicCardAmount(uint32 iCard, uint timestamp) external view returns(uint num)
{
num = GetDynamicCardNum(iCard, GetDayCount(timestamp));
}
function AddDynamicProfit(address acc, uint32 iCard, uint duration) internal
{
RefreshDayBonus();
uint todayNo = GetDayCount(now);
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
if (pb.m_DrawedDay == 0) pb.m_DrawedDay = todayNo;
for (uint dayNo=todayNo; dayNo<todayNo+duration; dayNo++)
{
pb.m_DayDynamic[dayNo].push(iCard);
DayRatio storage dr= g_Bonus.m_DayRatio[dayNo];
if (dr.m_CardNum[iCard] == 0) {
dr.m_DynamicCard.push(iCard);
}
dr.m_CardNum[iCard]++;
}
}
function AddStaticProfit(address acc,uint16 ratio,uint duration) internal
{
RefreshDayBonus();
uint todayNo = GetDayCount(now);
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
if (pb.m_DrawedDay == 0) pb.m_DrawedDay = todayNo;
if (duration == 0) {
pb.m_DayPermanent[todayNo] += ratio;
g_Bonus.m_DayRatio[todayNo].m_Permanent += ratio;
}
else {
for (uint dayNo=todayNo; dayNo<todayNo+duration; dayNo++)
{
pb.m_DayStatic[dayNo] += ratio;
g_Bonus.m_DayRatio[dayNo].m_Static += ratio;
}
}
}
function ImmediateProfit(address acc, uint ratio) internal
{
RefreshDayBonus();
if (g_Bonus.m_RecordBonus == 0) return;
uint bonus = ratio*g_Bonus.m_RecordBonus/BASERATIO;
g_Bonus.m_RecordBonus -= bonus;
g_Bonus.m_RewardBonus -= bonus;
g_Bonus.m_PlayerBonus[acc].m_Bonus += bonus;
}
function ProfitByCard(address acc, uint32 iCard) internal
{
Card storage oCard = GetCard(iCard);
if (oCard.m_IP > 0) {
ImmediateProfit(acc,oCard.m_IP);
}
else if (oCard.m_SP > 0) {
AddStaticProfit(acc,oCard.m_SP,oCard.m_Duration);
}
else {
AddDynamicProfit(acc,iCard,oCard.m_Duration);
}
}
function QueryBonus() external view returns(uint)
{
uint todayNo = GetDayCount(now);
if (!NeedRefresh(todayNo)) return g_Bonus.m_RecordBonus;
uint tempBonus = g_Bonus.m_RecordBonus;
uint tempPR = g_Bonus.m_RecordPR;
uint tempRatio;
for (uint dayNo=g_Bonus.m_RecordDay; dayNo<todayNo; dayNo++)
{
tempRatio = tempPR+GenDayRatio(dayNo);
if (tempRatio == 0) continue;
DayRatio storage dr = g_Bonus.m_DayRatio[dayNo];
tempPR += dr.m_Permanent;
tempBonus -= tempBonus*tempRatio/BASERATIO;
}
return tempBonus;
}
function QueryMyBonus(address acc) external view returns(uint bonus)
{
(bonus,) = QueryPlayerBonus(acc, GetDayCount(now));
}
function AddBonus(uint bonus) external AuthAble
{
RefreshDayBonus();
g_Bonus.m_RewardBonus += bonus;
g_Bonus.m_RecordBonus += bonus;
}
function Withdraw(address acc) external OwnerAble(acc)
{
RefreshDayBonus();
PlayerBonus storage pb = g_Bonus.m_PlayerBonus[acc];
uint bonus;
uint todayNo = GetDayCount(now);
(bonus, pb.m_DDPermanent) = QueryPlayerBonus(acc, todayNo);
require(bonus > 0);
pb.m_Bonus = 0;
pb.m_DrawedDay = todayNo;
g_Bonus.m_RewardBonus -= bonus;
acc.transfer(bonus);
}
function MasterWithdraw() external
{
uint bonus = address(this).balance-g_Bonus.m_RewardBonus;
require(bonus > 0);
receiver.transfer(bonus);
}
}
contract MainBag is BasicTime,BasicAuth,MainChip,MainCard
{
using ItemList for ItemList.Data;
struct Bag
{
ItemList.Data m_Stuff;
ItemList.Data m_TempStuff;
ItemList.Data m_Chips;
ItemList.Data m_TempCards;
ItemList.Data m_PermCards;
}
mapping(address => Bag) g_BagList;
function GainStuff(address acc, uint32 iStuff, uint iNum) external AuthAble OwnerAble(acc)
{
Bag storage obj = g_BagList[acc];
obj.m_Stuff.add(iStuff,iNum);
}
function CostStuff(address acc, uint32 iStuff, uint iNum) external AuthAble OwnerAble(acc)
{
Bag storage obj = g_BagList[acc];
obj.m_Stuff.sub(iStuff,iNum);
}
function GetStuffNum(address acc, uint32 iStuff) view external returns(uint)
{
Bag storage obj = g_BagList[acc];
return obj.m_Stuff.get(iStuff);
}
function GetStuffList(address acc) external view returns(uint32[],uint[])
{
Bag storage obj = g_BagList[acc];
return obj.m_Stuff.list();
}
function GainTempStuff(address acc, uint32 iStuff, uint dayCnt) external AuthAble OwnerAble(acc)
{
Bag storage obj = g_BagList[acc];
require(obj.m_TempStuff.get(iStuff) <= now);
obj.m_TempStuff.set(iStuff,now+dayCnt*DAY_SECONDS);
}
function GetTempStuffExpire(address acc, uint32 iStuff) external view returns(uint expire)
{
Bag storage obj = g_BagList[acc];
expire = obj.m_TempStuff.get(iStuff);
}
function GetTempStuffList(address acc) external view returns(uint32[],uint[])
{
Bag storage obj = g_BagList[acc];
return obj.m_TempStuff.list();
}
function GainChip(address acc, uint32 iChip,bool bGenerated) external AuthAble OwnerAble(acc)
{
if (!bGenerated) {
require(CanObtainChip(iChip));
ObtainChip(iChip);
}
Bag storage obj = g_BagList[acc];
obj.m_Chips.add(iChip,1);
}
function CostChip(address acc, uint32 iChip) external AuthAble OwnerAble(acc)
{
Bag storage obj = g_BagList[acc];
obj.m_Chips.sub(iChip,1);
CostChip(iChip);
}
function GetChipNum(address acc, uint32 iChip) external view returns(uint)
{
Bag storage obj = g_BagList[acc];
return obj.m_Chips.get(iChip);
}
function GetChipList(address acc) external view returns(uint32[],uint[])
{
Bag storage obj = g_BagList[acc];
return obj.m_Chips.list();
}
function GainCard2(address acc, uint32 iCard) internal
{
Card storage oCard = GetCard(iCard);
if (oCard.m_IP > 0) return;
uint i;
uint32 iChip;
Bag storage obj = g_BagList[acc];
if (oCard.m_Duration > 0) {
uint expireTime = GetExpireTime(now,oCard.m_Duration);
for (i=0; i<oCard.m_Parts.length; i++)
{
iChip = oCard.m_Parts[i];
AddChipTempTime(iChip,expireTime);
}
obj.m_TempCards.set(iCard,expireTime);
}
else {
for (i=0; i<oCard.m_Parts.length; i++)
{
iChip = oCard.m_Parts[i];
ObtainChip(iChip);
}
obj.m_PermCards.set(iCard,1);
}
}
function HasCard(address acc, uint32 iCard) public view returns(bool)
{
Bag storage obj = g_BagList[acc];
if (obj.m_TempCards.get(iCard) > now) return true;
if (obj.m_PermCards.has(iCard)) return true;
return false;
}
function GetCardList(address acc) external view returns(uint32[] tempCards, uint[] cardsTime, uint32[] permCards)
{
Bag storage obj = g_BagList[acc];
(tempCards,cardsTime) = obj.m_TempCards.list();
permCards = obj.m_PermCards.keys();
}
}
contract OldMain
{
function GetStuffList(address) external view returns(uint32[], uint[]);
function GetTempStuffList(address acc) external view returns(uint32[], uint[]);
function GetChipList(address acc) external view returns(uint32[], uint[]);
function GetCardList(address acc) external view returns(uint32[] tempCards, uint[] cardsTime, uint32[] permCards);
}
contract Main is MainChip,MainCard,MainBag,MainBonus
{
using ItemList for ItemList.Data;
constructor(address Receiver) public MainBonus(Receiver) {}
bool g_Synced = false;
function SyncOldData(OldMain oldMain, address[] accounts) external CreatorAble
{
require(!g_Synced);
g_Synced = true;
for (uint i=0; i<accounts.length; i++)
{
address acc = accounts[i];
SyncStuff(oldMain, acc);
SyncTempStuff(oldMain, acc);
SyncChip(oldMain, acc);
SyncCard(oldMain, acc);
}
}
function SyncItemData(ItemList.Data storage Data, uint32[] idxList, uint[] valList) internal
{
if (idxList.length == 0) return;
for (uint i=0; i<idxList.length; i++)
{
uint32 index = idxList[i];
uint val = valList[i];
Data.set(index, val);
}
}
function SyncStuff(OldMain oldMain, address acc) internal
{
(uint32[] memory idxList, uint[] memory valList) = oldMain.GetStuffList(acc);
SyncItemData(g_BagList[acc].m_Stuff, idxList, valList);
}
function SyncTempStuff(OldMain oldMain, address acc) internal
{
(uint32[] memory idxList, uint[] memory valList) = oldMain.GetTempStuffList(acc);
SyncItemData(g_BagList[acc].m_TempStuff, idxList, valList);
}
function SyncChip(OldMain oldMain, address acc) internal
{
(uint32[] memory idxList, uint[] memory valList) = oldMain.GetChipList(acc);
SyncItemData(g_BagList[acc].m_Chips, idxList, valList);
}
function CompensateChips(address acc, uint32[] idxList) internal
{
for (uint i=0; i<idxList.length; i++)
{
uint32 iCard = idxList[i];
if (iCard == 0) return;
Card storage obj = GetCard(iCard);
for (uint j=0; j<obj.m_Parts.length; j++)
{
uint32 iChip = obj.m_Parts[j];
g_BagList[acc].m_Chips.add(iChip,1);
}
}
}
function SyncCard(OldMain oldMain, address acc) internal
{
(uint32[] memory idxList, uint[] memory valList ,uint32[] memory permCards) = oldMain.GetCardList(acc);
uint32[] memory allCards = new uint32[](idxList.length+permCards.length);
uint i=0;
uint j=0;
for (j=0; j<idxList.length; j++)
{
uint expire = valList[j];
if (expire < now) continue;
allCards[i] = idxList[j];
i++;
}
for (j=0; j<permCards.length; j++)
{
allCards[i] = permCards[j];
i++;
}
CompensateChips(acc, allCards);
}
function InsertCard(uint32 iCard, uint32 duration, uint8 level, uint16 dp, uint16 dpk, uint16 sp, uint16 ip, uint32[] parts) external CreatorAble
{
require(!CardExists(iCard));
require(level<=HEROLEVEL_MAX && level>=HEROLEVEL_MIN);
require(GetPartNum(level) == parts.length);
AddNewCard(iCard, duration, level, dp, dpk, sp, ip, parts);
for (uint8 iPart=1; iPart<=parts.length; iPart++)
{
uint idx = iPart-1;
uint32 iChip = parts[idx];
uint8 limit = GetPartLimit(level, iPart);
AddNewChip(iChip, level, limit, iPart);
}
}
function GainCard(address acc, uint32 iCard) external AuthAble OwnerAble(acc)
{
require(CardExists(iCard) && !HasCard(acc,iCard));
GainCard2(acc,iCard);
ProfitByCard(acc,iCard);
}
function GetDynamicCardAmountList(address acc) external view returns(uint[] amountList)
{
Bag storage oBag = g_BagList[acc];
uint len = oBag.m_TempCards.m_List.length;
amountList = new uint[](len);
for (uint i=0; i<len; i++)
{
uint32 iCard = oBag.m_TempCards.m_List[i];
amountList[i] = GetDynamicCardNum(iCard,GetDayCount(now));
}
}
function GenChipByRandomWeight(uint random, uint8 level, uint[] extWeight) external AuthAble returns(uint32 iChip)
{
RefreshChipUnableList(level);
iChip = GenChipByWeight(random,level,extWeight);
ObtainChip(iChip);
}
function CheckGenChip(uint32 iChip) external view returns(bool)
{
return CanObtainChip(iChip);
}
function GenChip(uint32 iChip) external AuthAble
{
require(CanObtainChip(iChip));
ObtainChip(iChip);
}
}
contract OldProductionBoiler
{
function GetBoilerInfo(address acc, uint idx) external view returns(uint, uint32[]);
}
contract ProductionBoiler is BasicAuth
{
struct Boiler
{
uint m_Expire;
uint32[] m_Chips;
}
mapping(address => mapping(uint => Boiler)) g_Boilers;
bool g_Synced = false;
function SyncOldData(OldProductionBoiler oldBoiler, address[] accounts) external CreatorAble
{
require(!g_Synced);
g_Synced = true;
for (uint i=0; i<accounts.length; i++)
{
address acc = accounts[i];
for (uint idx=0; idx<3; idx++)
{
(uint expire, uint32[] memory chips) = oldBoiler.GetBoilerInfo(acc,idx);
if (expire == 0) continue;
g_Boilers[acc][idx].m_Expire = expire;
g_Boilers[acc][idx].m_Chips = chips;
}
}
}
function IsBoilerValid(address acc, uint idx) external view returns(bool)
{
Boiler storage obj = g_Boilers[acc][idx];
if (obj.m_Chips.length > 0) return false;
return true;
}
function IsBoilerExpire(address acc, uint idx) external view returns(bool)
{
Boiler storage obj = g_Boilers[acc][idx];
return obj.m_Expire <= now;
}
function GenerateChips(address acc, uint idx, uint cd, uint32[] chips) external AuthAble OwnerAble(acc)
{
Boiler storage obj = g_Boilers[acc][idx];
obj.m_Expire = cd+now;
obj.m_Chips = chips;
}
function CollectChips(address acc, uint idx) external AuthAble OwnerAble(acc) returns(uint32[] chips)
{
Boiler storage obj = g_Boilers[acc][idx];
chips = obj.m_Chips;
delete g_Boilers[acc][idx];
}
function GetBoilerInfo(address acc, uint idx) external view returns(uint, uint32[])
{
Boiler storage obj = g_Boilers[acc][idx];
return (obj.m_Expire,obj.m_Chips);
}
}
contract Child is Base {
Main g_Main;
constructor(Main main) public
{
require(main != address(0));
g_Main = main;
g_Main.SetAuth(this);
}
function kill() external CreatorAble
{
g_Main.ClearAuth(this);
selfdestruct(creator);
}
function AddBonus(uint percent) internal
{
address(g_Main).transfer(msg.value);
g_Main.AddBonus(msg.value * percent / 100);
}
function GenRandom(uint seed,uint base) internal view returns(uint,uint)
{
uint r = uint(keccak256(abi.encodePacked(msg.sender,seed,now)));
if (base != 0) r %= base;
return (r,seed+1);
}
}
contract Production is Child {
uint32 constant STUFF_IDX_POINT = 22001;
uint32 constant STUFF_IDX_GENRAL = 21000;
uint32 constant STUFF_IDX_EXTRA = 21004;
uint32 constant PERMISSION_1 = 23002;
uint32 constant PERMISSION_2 = 23003;
uint constant BASERATIO = 10000;
uint constant BOILER_FREE_IDX = 0;
uint constant BOILER_MAX_NUM = 3;
uint constant CREATE_COST_MIN = 30;
uint constant CREATE_COST_FEW = 60;
uint constant CREATE_COST_MANY = 150;
uint constant CREATE_COST_MAX = 300;
uint constant COOLTIME_MIN = 60 * 60;
uint constant COOLTIME_MID = 60 * 60 * 2;
uint constant COOLTIME_MAX = 60 * 60 * 4;
uint constant ACCELERATE_UNITTIME = 60 * 5;
uint constant ACCELERATE_UNITFEE = 0.0013 ether;
uint constant BONUS_PERCENT_ACCELERATE = 80;
ProductionBoiler g_Boilers;
constructor(Main main, ProductionBoiler pb) public Child(main)
{
g_Boilers = pb;
g_Boilers.SetAuth(this);
}
function kill() external CreatorAble
{
g_Boilers.ClearAuth(this);
}
function GenChipIndex(
uint seed,
uint8 level,
uint[] extWeight3,
uint[] extWeight4,
uint[] extWeight5
) internal returns(uint32,uint)
{
uint random;
(random,seed) = GenRandom(seed,0);
if (level==1 || level==2) {
return (g_Main.GenChipByRandomWeight(random,level,extWeight3),seed);
}
else if (level==3 || level==4) {
return (g_Main.GenChipByRandomWeight(random,level,extWeight4),seed);
}
else {
return (g_Main.GenChipByRandomWeight(random,level,extWeight5),seed);
}
}
function GenChipLevel_Special(uint costAll, uint x, uint seed) internal view returns(uint8,uint)
{
uint8 outLv;
uint random;
if (costAll <= CREATE_COST_FEW) {
outLv = 3;
}
else {
(random,seed) = GenRandom(seed,BASERATIO);
uint baseR = BASERATIO*x/100;
if (costAll <= CREATE_COST_MANY) {
baseR /= 10;
if (random <= BASERATIO*80/100-baseR) {
outLv = 3;
}
else if (random <= BASERATIO-baseR/4) {
outLv = 4;
}
else {
outLv = 5;
}
}
else {
baseR /= 10;
if (random <= BASERATIO*70/100-baseR) {
outLv = 3;
}
else if (random <= BASERATIO*95/100-baseR/5) {
outLv = 4;
}
else {
outLv = 5;
}
}
}
return (outLv,seed);
}
function GenChipLevel_Extra(uint costAll, uint x, uint seed) internal view returns(uint8,uint)
{
uint8 outLv;
uint random;
uint baseR = BASERATIO*x/100;
(random,seed) = GenRandom(seed,BASERATIO);
if (costAll <= CREATE_COST_FEW) {
baseR /= 4;
if (random <= BASERATIO*80/100-baseR) {
outLv = 1;
}
else if (random <= BASERATIO*98/100-baseR*3/4) {
outLv = 2;
}
else if (random <= BASERATIO-baseR/4) {
outLv = 3;
}
else {
outLv = 4;
}
}
else if (costAll <= CREATE_COST_MANY) {
baseR /= 10;
if (random <= BASERATIO*55/100-baseR) {
outLv = 1;
}
else if (random <= BASERATIO*85/100-baseR*4/5) {
outLv = 2;
}
else if (random <= BASERATIO*95/100-baseR*2/5) {
outLv = 3;
}
else if (random <= BASERATIO-baseR/5) {
outLv = 4;
}
else {
outLv = 5;
}
}
else {
baseR /= 10;
if (random <= BASERATIO*30/100-baseR/2) {
outLv = 1;
}
else if (random <= BASERATIO*75/100-baseR) {
outLv = 2;
}
else if (random <= BASERATIO*88/100-baseR*4/7) {
outLv = 3;
}
else if (random <= BASERATIO*97/100-baseR/7) {
outLv = 4;
}
else {
outLv = 5;
}
}
return (outLv,seed);
}
function GenChipLevel_General(uint costAll, uint x, uint seed) internal view returns(uint8,uint)
{
uint8 outLv;
uint random;
uint baseR = BASERATIO*x/100;
(random,seed) = GenRandom(seed,BASERATIO);
if (costAll <= CREATE_COST_FEW) {
baseR /= 2;
if (random <= BASERATIO - baseR) {
outLv = 1;
}
else {
outLv = 2;
}
}
else if (costAll <= CREATE_COST_MANY) {
baseR = baseR*14/100;
if (random <= BASERATIO*70/100-baseR) {
outLv = 1;
}
else if (random <= BASERATIO*95/100-baseR/4) {
outLv = 2;
}
else {
outLv = 3;
}
}
else {
baseR = baseR*11/100;
if (random <= BASERATIO*50/100-baseR) {
outLv = 1;
}
else if (random <= BASERATIO*90/100-baseR/3) {
outLv = 2;
}
else {
outLv = 3;
}
}
return (outLv,seed);
}
function GenOutChipsNum(uint seed, uint costAll, uint x) internal view returns(uint,uint)
{
uint amount;
uint random;
uint baseR = BASERATIO*x/100;
(random,seed) = GenRandom(seed,BASERATIO);
if (costAll <= CREATE_COST_FEW) {
if (random <= BASERATIO - baseR) {
amount = 3;
}
else {
amount = 4;
}
}
else {
baseR /= 10;
if (costAll <= CREATE_COST_MANY) {
if (random <= BASERATIO*7/10 - baseR*2) {
amount = 3;
}
else if (random <= BASERATIO*3/10 + baseR) {
amount = 4;
}
else {
amount = 5;
}
}
else {
if (random <= BASERATIO*7/10 - baseR) {
amount = 4;
}
else {
amount = 5;
}
}
}
return (amount,seed);
}
function GetMinCost(uint a, uint b, uint c) internal pure returns(uint)
{
if (a>b) {
if (a>c) return a;
}
else if (b>c) return b;
else return c;
}
function GenExtWeightList(uint costA, uint costB, uint costC) internal pure returns(uint[],uint[],uint[])
{
uint min = GetMinCost(costA,costB,costC);
uint[] memory extWeight3 = new uint[](3);
uint[] memory extWeight4 = new uint[](4);
uint[] memory extWeight5 = new uint[](5);
extWeight3[0] = costA;
extWeight4[0] = costA;
extWeight5[0] = costA;
extWeight3[1] = costB;
extWeight4[1] = costB;
extWeight5[1] = costB;
extWeight3[2] = costC;
extWeight4[2] = costC;
extWeight5[2] = costC;
extWeight5[3] = min;
min = min/2;
extWeight4[3] = min;
extWeight5[4] = min;
return (extWeight3,extWeight4,extWeight5);
}
function GenChipsLevel(uint costAll,bool bUseX) internal view returns(uint8[] lvList, uint seed)
{
uint x = costAll - CREATE_COST_MIN;
uint i;
uint amount;
(amount,seed) = GenOutChipsNum(0,costAll,x);
lvList = new uint8[](amount);
if (bUseX) {
(lvList[0], seed) = GenChipLevel_Special(costAll,x,seed);
for (i=1; i<amount; i++)
{
(lvList[i], seed) = GenChipLevel_Extra(costAll,x,seed);
}
}
else {
for (i=0; i<amount; i++)
{
(lvList[i], seed) = GenChipLevel_General(costAll,x,seed);
}
}
}
function CreateChips(uint costAll, uint costA, uint costB, uint costC, bool bUseX) internal returns(uint32[])
{
(uint[] memory ext3,
uint[] memory ext4,
uint[] memory ext5
) = GenExtWeightList(costA,costB,costC);
(uint8[] memory lvList, uint seed) = GenChipsLevel(costAll,bUseX);
uint32[] memory chips = new uint32[](lvList.length);
for (uint i=0; i<lvList.length; i++)
{
uint8 chipLv = lvList[i];
(chips[i], seed) = GenChipIndex(seed,chipLv,ext3,ext4,ext5);
}
return chips;
}
function GetPermissionIdx(uint idx) internal pure returns(uint32)
{
if (idx == 1) return PERMISSION_1;
else if (idx == 2) return PERMISSION_2;
return 0;
}
function IsBoilerValid(uint idx) internal view returns(bool)
{
if (idx != BOILER_FREE_IDX) {
uint32 iStuff = GetPermissionIdx(idx);
if (iStuff == 0) return false;
if (g_Main.GetTempStuffExpire(msg.sender,iStuff) < now) return false;
}
return g_Boilers.IsBoilerValid(msg.sender,idx);
}
function CollectChips(uint idx) internal
{
uint32[] memory chips = g_Boilers.CollectChips(msg.sender,idx);
for (uint i=0; i<chips.length; i++)
{
g_Main.GainChip(msg.sender,chips[i],true);
}
}
function GetExchangePoint(uint8 chipLv) internal pure returns(uint)
{
if (chipLv == 1) return 1;
else if (chipLv == 2) return 3;
else if (chipLv == 3) return 10;
else if (chipLv == 4) return 30;
else if (chipLv == 5) return 120;
return 0;
}
function Create(uint idx,uint costA, uint costB, uint costC, bool bUseX) external
{
require(costA <= CREATE_COST_MAX);
require(costB <= CREATE_COST_MAX);
require(costC <= CREATE_COST_MAX);
uint costAll = costA+costB+costC;
require(costAll>=CREATE_COST_MIN && costAll<=CREATE_COST_MAX);
require(IsBoilerValid(idx));
g_Main.CostStuff(msg.sender,STUFF_IDX_GENRAL,costAll);
if (bUseX) g_Main.CostStuff(msg.sender,STUFF_IDX_EXTRA,1);
uint CD;
if (costAll <= CREATE_COST_FEW) {
CD = COOLTIME_MIN;
}
else if (costAll <= CREATE_COST_MANY) {
CD = COOLTIME_MID;
}
else {
CD = COOLTIME_MAX;
}
uint32[] memory chips = CreateChips(costAll,costA,costB,costC,bUseX);
g_Boilers.GenerateChips(msg.sender,idx,CD,chips);
}
function GetBoilersInfo() external view returns(uint[], uint32[], uint32[], uint32[] )
{
uint[] memory expireList = new uint[](BOILER_MAX_NUM);
uint32[][] memory allChips = new uint32[][](BOILER_MAX_NUM);
for (uint i=BOILER_FREE_IDX; i<BOILER_MAX_NUM; i++)
{
(uint expire, uint32[] memory chips) = g_Boilers.GetBoilerInfo(msg.sender,i);
expireList[i] = expire;
allChips[i] = chips;
}
return (
expireList,
allChips[0],
allChips[1],
allChips[2]
);
}
function ResolveChips(uint32[] chips) external
{
for (uint i=0; i<chips.length; i++)
{
uint32 iChip = chips[i];
g_Main.CostChip(msg.sender,iChip);
(,uint8 lv,,,,) = g_Main.GetChipInfo(iChip);
uint point = GetExchangePoint(lv);
g_Main.GainStuff(msg.sender,STUFF_IDX_POINT,point);
}
}
function Collect(uint idx) external
{
require(g_Boilers.IsBoilerExpire(msg.sender,idx));
require(!g_Boilers.IsBoilerValid(msg.sender,idx));
CollectChips(idx);
}
function Accelerate(uint idx) external payable
{
(uint expire,) = g_Boilers.GetBoilerInfo(msg.sender,idx);
require(expire > now);
uint remain = expire-now;
uint num = remain/ACCELERATE_UNITTIME;
if (remain != num*ACCELERATE_UNITTIME) {
num++;
}
uint fee = num*ACCELERATE_UNITFEE;
require(fee == msg.value);
AddBonus(BONUS_PERCENT_ACCELERATE);
CollectChips(idx);
}
} | 0 |