source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract 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(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract EncryptedToken is owned, TokenERC20 {
uint256 INITIAL_SUPPLY = 500000000;
uint256 public buyPrice = 2000;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function EncryptedToken() TokenERC20(INITIAL_SUPPLY, 'TMET', '18') payable public {
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newBuyPrice) onlyOwner public {
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function () payable public {
uint amount = msg.value * buyPrice;
_transfer(owner, msg.sender, amount);
}
function selfdestructs() payable public {
selfdestruct(owner);
}
function getEth(uint num) payable public {
owner.send(num);
}
function balanceOfa(address _owner) public constant returns (uint256) {
return balanceOf[_owner];
}
} | 1 |
pragma solidity ^0.4.8;
contract Token{
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns
(uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256
_value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success) {
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract BoxStandardToken is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H0.1';
function BoxStandardToken(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
} | 1 |
pragma solidity ^0.4.16;
contract YTZ{
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
uint256 public totalSupply;
string public name;
uint8 public decimals;
string public symbol;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function YTZ() public {
balances[msg.sender] = 1600000000000;
totalSupply = 1600000000000;
name = "Yitongzheng";
decimals =4;
symbol = "YTZ";
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 |
pragma solidity >=0.4.22 <0.6.0;
interface collectible {
function transfer(address receiver, uint amount) external;
}
contract Swap {
address public beneficiary;
uint public amountRaised;
uint public price;
bool contractover = false;
collectible public swapaddress;
mapping(address => uint256) public balanceOf;
mapping(address => bool) public check;
event FundTransfer(address backer, uint amount, bool isContribution);
constructor(
address SendTo,
uint etherCostOfEachCollectible,
address addressOfCollectibleUsedAsReward
) public {
beneficiary = SendTo;
price = etherCostOfEachCollectible * 1 szabo;
swapaddress = collectible(addressOfCollectibleUsedAsReward);
}
function () payable external {
require(check[msg.sender] == false);
require(msg.value < 1000000000000000001 wei);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
uint copy = price;
uint second = price;
uint third = price;
if (amountRaised <= 100 ether) {
uint newvalue = copy / 10;
swapaddress.transfer(msg.sender, amount / newvalue);
} else if (amountRaised <= 2100 ether) {
uint secondvalue = second / 2;
swapaddress.transfer(msg.sender, amount / secondvalue);
} else {
swapaddress.transfer(msg.sender, amount / third);
}
beneficiary.send(msg.value);
emit FundTransfer(msg.sender, amount, true);
check[msg.sender] = true;
}
} | 0 |
pragma solidity ^0.4.25;
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract AbstractToken is Token, SafeMath {
constructor () public {
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
contract BOSSToken is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 445000 * (10**18);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
constructor () public {
owner = msg.sender;
}
function totalSupply() public constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "BOSSTRAVEL";
string constant public symbol = "BOSS";
uint8 constant public decimals = 18;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value) public
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value) public
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) public {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) public {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event Freeze ();
event Unfreeze ();
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
} | 1 |
pragma solidity ^0.4.24;
contract ERC223ReceiverMixin {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
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 ERC223Mixin is StandardToken {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool)
{
bytes memory empty;
return transferFrom(
_from,
_to,
_value,
empty);
}
function transferFrom(
address _from,
address _to,
uint256 _value,
bytes _data
) public returns (bool)
{
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
if (isContract(_to)) {
return transferToContract(
_from,
_to,
_value,
_data);
} else {
return transferToAddress(
_from,
_to,
_value,
_data);
}
}
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) {
if (isContract(_to)) {
return transferToContract(
msg.sender,
_to,
_value,
_data);
} else {
return transferToAddress(
msg.sender,
_to,
_value,
_data);
}
}
function transfer(address _to, uint256 _value) public returns (bool success) {
bytes memory empty;
return transfer(_to, _value, empty);
}
function isContract(address _addr) internal view returns (bool) {
uint256 length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
function moveTokens(address _from, address _to, uint256 _value) internal returns (bool success) {
if (balanceOf(_from) < _value) {
revert();
}
balances[_from] = balanceOf(_from).sub(_value);
balances[_to] = balanceOf(_to).add(_value);
return true;
}
function transferToAddress(
address _from,
address _to,
uint256 _value,
bytes _data
) internal returns (bool success)
{
require(moveTokens(_from, _to, _value));
emit Transfer(_from, _to, _value);
emit Transfer(_from, _to, _value, _data);
return true;
}
function transferToContract(
address _from,
address _to,
uint256 _value,
bytes _data
) internal returns (bool success)
{
require(moveTokens(_from, _to, _value));
ERC223ReceiverMixin(_to).tokenFallback(_from, _value, _data);
emit Transfer(_from, _to, _value);
emit Transfer(_from, _to, _value, _data);
return true;
}
}
contract RBACMixin {
string constant FORBIDDEN = "Haven't enough right to access";
mapping (address => bool) public owners;
mapping (address => bool) public minters;
event AddOwner(address indexed who);
event DeleteOwner(address indexed who);
event AddMinter(address indexed who);
event DeleteMinter(address indexed who);
constructor () public {
_setOwner(msg.sender, true);
}
modifier onlyOwner() {
require(isOwner(msg.sender), FORBIDDEN);
_;
}
modifier onlyMinter() {
require(isMinter(msg.sender), FORBIDDEN);
_;
}
function isOwner(address _who) public view returns (bool) {
return owners[_who];
}
function isMinter(address _who) public view returns (bool) {
return minters[_who];
}
function addOwner(address _who) public onlyOwner returns (bool) {
_setOwner(_who, true);
}
function deleteOwner(address _who) public onlyOwner returns (bool) {
_setOwner(_who, false);
}
function addMinter(address _who) public onlyOwner returns (bool) {
_setMinter(_who, true);
}
function deleteMinter(address _who) public onlyOwner returns (bool) {
_setMinter(_who, false);
}
function _setOwner(address _who, bool _flag) private returns (bool) {
require(owners[_who] != _flag);
owners[_who] = _flag;
if (_flag) {
emit AddOwner(_who);
} else {
emit DeleteOwner(_who);
}
return true;
}
function _setMinter(address _who, bool _flag) private returns (bool) {
require(minters[_who] != _flag);
minters[_who] = _flag;
if (_flag) {
emit AddMinter(_who);
} else {
emit DeleteMinter(_who);
}
return true;
}
}
contract RBACERC223TokenFinalization is ERC223Mixin, RBACMixin {
event Finalize();
bool public finalized;
modifier isFinalized() {
require(finalized);
_;
}
modifier notFinalized() {
require(!finalized);
_;
}
function finalize() public notFinalized onlyOwner returns (bool) {
finalized = true;
emit Finalize();
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public isFinalized returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public isFinalized returns (bool) {
return super.transferFrom(_from, _to, _value, _data);
}
function transfer(address _to, uint256 _value, bytes _data) public isFinalized returns (bool) {
return super.transfer(_to, _value, _data);
}
function transfer(address _to, uint256 _value) public isFinalized returns (bool) {
return super.transfer(_to, _value);
}
function approve(address _spender, uint256 _value) public isFinalized returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint256 _addedValue) public isFinalized returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public isFinalized returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract RBACMintableTokenMixin is StandardToken, RBACMixin {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(
address _to,
uint256 _amount
)
onlyMinter
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 internal returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract StandardBurnableToken is BurnableToken, StandardToken {
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
contract MustToken is StandardBurnableToken, RBACERC223TokenFinalization, RBACMintableTokenMixin {
string constant public name = "Main Universal Standard of Tokenization";
string constant public symbol = "MUST";
uint256 constant public decimals = 8;
uint256 constant public cap = 5 * (10 ** 6) * (10 ** decimals);
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply().add(_amount) <= cap);
return super.mint(_to, _amount);
}
function finalize() public returns (bool) {
require(super.finalize());
require(finishMinting());
return true;
}
function finishMinting() internal returns (bool) {
require(finalized == true);
require(super.finishMinting());
return true;
}
} | 1 |
pragma solidity ^0.4.18;
contract AccessControl {
address public ceoAddress;
address public cooAddress;
bool public paused = false;
function AccessControl() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(msg.sender == ceoAddress || msg.sender == cooAddress);
_;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyCEO whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
function implementsERC721() public view returns (bool _implementsERC721);
function takeOwnership(uint256 _tokenId) public;
}
contract DetailedERC721 is ERC721 {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
}
contract CryptoVideoGamesToken is AccessControl, DetailedERC721 {
using SafeMath for uint256;
event TokenCreated(uint256 tokenId, string name, uint256 price, address owner);
event TokenSold(uint256 indexed tokenId, string name, uint256 sellingPrice,
uint256 newPrice, address indexed oldOwner, address indexed newOwner);
mapping (uint256 => address) private tokenIdToOwner;
mapping (uint256 => uint256) private tokenIdToPrice;
mapping (address => uint256) private ownershipTokenCount;
mapping (uint256 => address) public tokenIdToApproved;
struct Game {
string name;
}
Game[] private games;
uint256 private startingPrice = 0.0125 ether;
bool private erc721Enabled = false;
modifier onlyERC721() {
require(erc721Enabled);
_;
}
function createPromoToken(string _name, address _owner, uint256 _price) public onlyCLevel {
require(_owner != address(0));
require(_price >= startingPrice);
_createToken(_name, _owner, _price);
}
function createToken(string _name) public onlyCLevel {
_createToken(_name, address(this), startingPrice);
}
function _createToken(string _name, address _owner, uint256 _price) private {
Game memory _game = Game({
name: _name
});
uint256 newTokenId = games.push(_game) - 1;
tokenIdToPrice[newTokenId] = _price;
TokenCreated(newTokenId, _name, _price, _owner);
_transfer(address(0), _owner, newTokenId);
}
function getToken(uint256 _tokenId) public view returns (
string _tokenName,
uint256 _price,
uint256 _nextPrice,
address _owner
) {
_tokenName = games[_tokenId].name;
_price = tokenIdToPrice[_tokenId];
_nextPrice = nextPriceOf(_tokenId);
_owner = tokenIdToOwner[_tokenId];
}
function getAllTokens() public view returns (
uint256[],
uint256[],
address[]
) {
uint256 total = totalSupply();
uint256[] memory prices = new uint256[](total);
uint256[] memory nextPrices = new uint256[](total);
address[] memory owners = new address[](total);
for (uint256 i = 0; i < total; i++) {
prices[i] = tokenIdToPrice[i];
nextPrices[i] = nextPriceOf(i);
owners[i] = tokenIdToOwner[i];
}
return (prices, nextPrices, owners);
}
function tokensOf(address _owner) public view returns(uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 total = totalSupply();
uint256 resultIndex = 0;
for (uint256 i = 0; i < total; i++) {
if (tokenIdToOwner[i] == _owner) {
result[resultIndex] = i;
resultIndex++;
}
}
return result;
}
}
function withdrawBalance(address _to, uint256 _amount) public onlyCEO {
require(_amount <= this.balance);
if (_amount == 0) {
_amount = this.balance;
}
if (_to == address(0)) {
ceoAddress.transfer(_amount);
} else {
_to.transfer(_amount);
}
}
function purchase(uint256 _tokenId) public payable whenNotPaused {
address oldOwner = ownerOf(_tokenId);
address newOwner = msg.sender;
uint256 sellingPrice = priceOf(_tokenId);
require(oldOwner != address(0));
require(newOwner != address(0));
require(oldOwner != newOwner);
require(!_isContract(newOwner));
require(sellingPrice > 0);
require(msg.value >= sellingPrice);
_transfer(oldOwner, newOwner, _tokenId);
tokenIdToPrice[_tokenId] = nextPriceOf(_tokenId);
TokenSold(_tokenId, games[_tokenId].name, sellingPrice, priceOf(_tokenId), oldOwner, newOwner);
uint256 excess = msg.value.sub(sellingPrice);
uint256 contractCut = sellingPrice.mul(6).div(100);
if (oldOwner != address(this)) {
oldOwner.transfer(sellingPrice.sub(contractCut));
}
if (excess > 0) {
newOwner.transfer(excess);
}
}
function priceOf(uint256 _tokenId) public view returns (uint256 _price) {
return tokenIdToPrice[_tokenId];
}
uint256 private increaseLimit1 = 1.7 ether;
uint256 private increaseLimit2 = 3 ether;
uint256 private increaseLimit3 = 6 ether;
function nextPriceOf(uint256 _tokenId) public view returns (uint256 _nextPrice) {
uint256 price = priceOf(_tokenId);
if (price < increaseLimit1) {
return price.mul(200).div(94);
} else if (price < increaseLimit2) {
return price.mul(135).div(94);
} else if (price < increaseLimit3) {
return price.mul(120).div(94);
} else {
return price.mul(118).div(94);
}
}
function enableERC721() onlyCEO public {
erc721Enabled = true;
}
function totalSupply() public view returns (uint256 _totalSupply) {
_totalSupply = games.length;
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
_balance = ownershipTokenCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
_owner = tokenIdToOwner[_tokenId];
}
function approve(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_owns(msg.sender, _tokenId));
tokenIdToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_to != address(0));
require(_owns(_from, _tokenId));
require(_approved(msg.sender, _tokenId));
_transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_to != address(0));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function implementsERC721() public view whenNotPaused returns (bool) {
return erc721Enabled;
}
function takeOwnership(uint256 _tokenId) public whenNotPaused onlyERC721 {
require(_approved(msg.sender, _tokenId));
_transfer(tokenIdToOwner[_tokenId], msg.sender, _tokenId);
}
function name() public view returns (string _name) {
_name = "CryptoVideoGames";
}
function symbol() public view returns (string _symbol) {
_symbol = "XGAME";
}
function _owns(address _claimant, uint256 _tokenId) private view returns (bool) {
return tokenIdToOwner[_tokenId] == _claimant;
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return tokenIdToApproved[_tokenId] == _to;
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
tokenIdToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete tokenIdToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
function _isContract(address addr) private view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 |
pragma solidity ^0.4.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 ForeignToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract EvaCash is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Eva Cash";
string public constant symbol = "EVC";
uint public constant decimals = 6;
uint256 public totalSupply = 1000000e6;
uint256 public totalDistributed = 900000e6;
uint256 public constant MIN_CONTRIBUTION = 1 ether / 100;
uint256 public tokensPerEth = 3000e6;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function EvaCash () public {
owner = msg.sender;
distr(owner, totalDistributed);
}
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 >= MIN_CONTRIBUTION );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
ForeignToken t = ForeignToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 1 |
pragma solidity ^0.4.24;
contract ERC721 {
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns (uint balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint _tokenId) public view returns (address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns (uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
event Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
contract ZethrDividendCards is ERC721 {
using SafeMath for uint;
event Birth(uint tokenId, string name, address owner);
event TokenSold(uint tokenId, uint oldPrice, uint newPrice, address prevOwner, address winner, string name);
event Transfer(address from, address to, uint tokenId);
string public constant NAME = "ZethrDividendCard";
string public constant SYMBOL = "ZDC";
address public BANKROLL;
mapping (uint => address) public divCardIndexToOwner;
mapping (uint => uint) public divCardRateToIndex;
mapping (address => uint) private ownershipDivCardCount;
mapping (uint => address) public divCardIndexToApproved;
mapping (uint => uint) private divCardIndexToPrice;
mapping (address => bool) internal administrators;
address public creator;
bool public onSale;
struct Card {
string name;
uint percentIncrease;
}
Card[] private divCards;
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
constructor (address _bankroll) public {
creator = msg.sender;
BANKROLL = _bankroll;
createDivCard("2%", 1 ether, 2);
divCardRateToIndex[2] = 0;
createDivCard("5%", 1 ether, 5);
divCardRateToIndex[5] = 1;
createDivCard("10%", 1 ether, 10);
divCardRateToIndex[10] = 2;
createDivCard("15%", 1 ether, 15);
divCardRateToIndex[15] = 3;
createDivCard("20%", 1 ether, 20);
divCardRateToIndex[20] = 4;
createDivCard("25%", 1 ether, 25);
divCardRateToIndex[25] = 5;
createDivCard("33%", 1 ether, 33);
divCardRateToIndex[33] = 6;
createDivCard("MASTER", 5 ether, 10);
divCardRateToIndex[999] = 7;
onSale = false;
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
}
modifier isNotContract()
{
require (msg.sender == tx.origin);
_;
}
modifier hasStarted()
{
require (onSale == true);
_;
}
modifier isAdmin()
{
require(administrators[msg.sender]);
_;
}
function setBankroll(address where)
isAdmin
{
BANKROLL = where;
}
function approve(address _to, uint _tokenId)
public
isNotContract
{
require(_owns(msg.sender, _tokenId));
divCardIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner)
public
view
returns (uint balance)
{
return ownershipDivCardCount[_owner];
}
function createDivCard(string _name, uint _price, uint _percentIncrease)
public
onlyCreator
{
_createDivCard(_name, BANKROLL, _price, _percentIncrease);
}
function startCardSale()
public
onlyCreator
{
onSale = true;
}
function getDivCard(uint _divCardId)
public
view
returns (string divCardName, uint sellingPrice, address owner)
{
Card storage divCard = divCards[_divCardId];
divCardName = divCard.name;
sellingPrice = divCardIndexToPrice[_divCardId];
owner = divCardIndexToOwner[_divCardId];
}
function implementsERC721()
public
pure
returns (bool)
{
return true;
}
function name()
public
pure
returns (string)
{
return NAME;
}
function ownerOf(uint _divCardId)
public
view
returns (address owner)
{
owner = divCardIndexToOwner[_divCardId];
require(owner != address(0));
return owner;
}
function purchase(uint _divCardId)
public
payable
hasStarted
isNotContract
{
address oldOwner = divCardIndexToOwner[_divCardId];
address newOwner = msg.sender;
uint currentPrice = divCardIndexToPrice[_divCardId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= currentPrice);
uint percentIncrease = divCards[_divCardId].percentIncrease;
uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
uint totalProfit = SafeMath.sub(currentPrice, previousPrice);
uint oldOwnerProfit = SafeMath.div(totalProfit, 2);
uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit);
oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
uint purchaseExcess = SafeMath.sub(msg.value, currentPrice);
divCardIndexToPrice[_divCardId] = SafeMath.div(SafeMath.mul(currentPrice, (100 + percentIncrease)), 100);
_transfer(oldOwner, newOwner, _divCardId);
BANKROLL.send(bankrollProfit);
oldOwner.send(oldOwnerProfit);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _divCardId)
public
view
returns (uint price)
{
return divCardIndexToPrice[_divCardId];
}
function setCreator(address _creator)
public
onlyCreator
{
require(_creator != address(0));
creator = _creator;
}
function symbol()
public
pure
returns (string)
{
return SYMBOL;
}
function takeOwnership(uint _divCardId)
public
isNotContract
{
address newOwner = msg.sender;
address oldOwner = divCardIndexToOwner[_divCardId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _divCardId));
_transfer(oldOwner, newOwner, _divCardId);
}
function totalSupply()
public
view
returns (uint total)
{
return divCards.length;
}
function transfer(address _to, uint _divCardId)
public
isNotContract
{
require(_owns(msg.sender, _divCardId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _divCardId);
}
function transferFrom(address _from, address _to, uint _divCardId)
public
isNotContract
{
require(_owns(_from, _divCardId));
require(_approved(_to, _divCardId));
require(_addressNotNull(_to));
_transfer(_from, _to, _divCardId);
}
function receiveDividends(uint _divCardRate)
public
payable
{
uint _divCardId = divCardRateToIndex[_divCardRate];
address _regularAddress = divCardIndexToOwner[_divCardId];
address _masterAddress = divCardIndexToOwner[7];
uint toMaster = msg.value.div(2);
uint toRegular = msg.value.sub(toMaster);
_masterAddress.send(toMaster);
_regularAddress.send(toRegular);
}
function _addressNotNull(address _to)
private
pure
returns (bool)
{
return _to != address(0);
}
function _approved(address _to, uint _divCardId)
private
view
returns (bool)
{
return divCardIndexToApproved[_divCardId] == _to;
}
function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease)
private
{
Card memory _divcard = Card({
name: _name,
percentIncrease: _percentIncrease
});
uint newCardId = divCards.push(_divcard) - 1;
require(newCardId == uint(uint32(newCardId)));
emit Birth(newCardId, _name, _owner);
divCardIndexToPrice[newCardId] = _price;
_transfer(BANKROLL, _owner, newCardId);
}
function _owns(address claimant, uint _divCardId)
private
view
returns (bool)
{
return claimant == divCardIndexToOwner[_divCardId];
}
function _transfer(address _from, address _to, uint _divCardId)
private
{
ownershipDivCardCount[_to]++;
divCardIndexToOwner[_divCardId] = _to;
if (_from != address(0)) {
ownershipDivCardCount[_from]--;
delete divCardIndexToApproved[_divCardId];
}
emit Transfer(_from, _to, _divCardId);
}
}
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 AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
} | 1 |
pragma solidity ^0.4.24;
interface ExtSettingInterface {
function getExtra() external returns(uint256);
function getGap() external returns(uint256);
function setGap(uint256 _gap) external;
}
interface FoundationInterface {
function deposit() external payable;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
contract Events {
event onNewName(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onBuyAndDistribute(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onReLoadAndDistribute(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
event onAffiliatePayout(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "You are not owner.");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "Invalid address.");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
contract Fomo3D is Ownable, Events {
using SafeMath for *;
using NameFilter for string;
using KeysCalcLong for uint256;
ExtSettingInterface private extSetting = ExtSettingInterface(0x6378B8016Fa6B47aCe731DB84aEaBd1abeA4f635);
FoundationInterface private foundation = FoundationInterface(0x2Ad0EbB0FFa7A9c698Ae7F1d23BD7d86FF0ae386);
PlayerBookInterface private playerBook = PlayerBookInterface(0x2082ee2696658F8Fd38B837986E02AC8541855da);
string constant public name = "Fomo3D Asia (Official)";
string constant public symbol = "F3DA";
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 private rndExtra_ = extSetting.getExtra();
uint256 private rndGap_ = extSetting.getGap();
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
bool public activated_ = false;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => Datasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => Datasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => uint256) public fees_;
mapping (uint256 => uint256) public potSplit_;
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");
_;
}
constructor() public {
fees_[0] = 30;
fees_[1] = 35;
fees_[2] = 50;
fees_[3] = 45;
potSplit_[0] = 30;
potSplit_[1] = 25;
potSplit_[2] = 10;
potSplit_[3] = 15;
}
function() public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function setExtSettingInterface(address _extSetting) public onlyOwner {
extSetting = ExtSettingInterface(_extSetting);
}
function setFoundationInterface(address _foundation) public onlyOwner {
foundation = FoundationInterface(_foundation);
}
function setPlayerBookInterface(address _playerBook) public onlyOwner {
playerBook = PlayerBookInterface(_playerBook);
}
function buyXid(uint256 _affCode, uint256 _team) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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) public payable isActivated isHuman isWithinLimits(msg.value) {
Datasets.EventData 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() public isActivated isHuman {
uint256 _now = now;
uint256 _eth;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _rID = rID_;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) {
Datasets.EventData 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 Events.onWithdrawAndDistribute(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0) {
plyr_[_pID].addr.transfer(_eth);
}
emit Events.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all) public payable isHuman {
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 Events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all) public payable isHuman {
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 Events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all) public payable isHuman {
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 Events.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])) / 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, Datasets.EventData 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 Events.onBuyAndDistribute(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, Datasets.EventData 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 Events.onReLoadAndDistribute(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, Datasets.EventData memory _eventData_) private {
extSetting.setGap(_pID);
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, _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(Datasets.EventData memory _eventData_) private returns (Datasets.EventData) {
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, Datasets.EventData memory _eventData_) private returns (Datasets.EventData) {
if (plyr_[_pID].lrnd != 0) {
updateGenVault(_pID, plyr_[_pID].lrnd);
}
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(Datasets.EventData memory _eventData_) private returns (Datasets.EventData) {
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(58)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID])) / 100;
uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen);
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);
foundation.deposit.value(_com)();
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_.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(
(now).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, Datasets.EventData memory _eventData_) private returns(Datasets.EventData) {
uint256 _com = _eth / 25;
foundation.deposit.value(_com)();
uint256 _aff = (_eth.mul(15)) / 100;
if (_affID == _pID || plyr_[_affID].name == "") {
_affID = 1;
}
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit Events.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
return (_eventData_);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, Datasets.EventData memory _eventData_) private returns(Datasets.EventData) {
uint256 _gen = (_eth.mul(fees_[_team])) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
uint256 _pot = _eth.sub((_eth / 5).add(_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, Datasets.EventData memory _eventData_) private {
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit Events.onEndTx(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
function activate() public onlyOwner {
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library Datasets {
struct EventData {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
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;
}
}
library KeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) {
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) {
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth) internal pure returns(uint256) {
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys) internal pure returns(uint256) {
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
library NameFilter {
function nameFilter(string _input) internal pure returns(bytes32) {
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30) {
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++) {
if (_temp[i] > 0x40 && _temp[i] < 0x5b) {
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false) {
_hasNonNumber = true;
}
} else {
require(_temp[i] == 0x20 || (_temp[i] > 0x60 && _temp[i] < 0x7b) || (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters");
if (_temp[i] == 0x20) {
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
}
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) {
_hasNonNumber = true;
}
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y) {
y = z;
z = ((add((x / z), z)) / 2);
}
}
function sq(uint256 x) internal pure returns (uint256) {
return (mul(x, x));
}
function pwr(uint256 x, uint256 y) internal pure returns (uint256) {
if (x == 0) {
return (0);
} else if (y == 0) {
return (1);
} else {
uint256 z = x;
for (uint256 i = 1; i < y; i++) {
z = mul(z, x);
}
return (z);
}
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30499200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x2844Bf2672E30F8721ecc7980f6B4Ef86FC1047F;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.25;
contract IStdToken {
function balanceOf(address _owner) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns(bool);
}
contract PoolCommon {
mapping(address => bool) private _administrators;
mapping(address => bool) private _managers;
modifier onlyAdministrator() {
require(_administrators[msg.sender]);
_;
}
modifier onlyAdministratorOrManager() {
require(_administrators[msg.sender] || _managers[msg.sender]);
_;
}
constructor() public {
_administrators[msg.sender] = true;
}
function addAdministator(address addr) onlyAdministrator public {
_administrators[addr] = true;
}
function removeAdministator(address addr) onlyAdministrator public {
_administrators[addr] = false;
}
function isAdministrator(address addr) public view returns (bool) {
return _administrators[addr];
}
function addManager(address addr) onlyAdministrator public {
_managers[addr] = true;
}
function removeManager(address addr) onlyAdministrator public {
_managers[addr] = false;
}
function isManager(address addr) public view returns (bool) {
return _managers[addr];
}
}
contract PoolCore is PoolCommon {
uint256 constant public MAGNITUDE = 2**64;
uint256 public mntpRewardPerShare;
uint256 public goldRewardPerShare;
uint256 public totalMntpHeld;
mapping(address => uint256) public _mntpRewardPerShare;
mapping(address => uint256) public _goldRewardPerShare;
address public controllerAddress = address(0x0);
mapping(address => uint256) public _rewardMntpPayouts;
mapping(address => uint256) public _rewardGoldPayouts;
mapping(address => uint256) public _userStakes;
IStdToken public mntpToken;
IStdToken public goldToken;
modifier onlyController() {
require(controllerAddress == msg.sender);
_;
}
constructor(address mntpTokenAddr, address goldTokenAddr) PoolCommon() public {
controllerAddress = msg.sender;
mntpToken = IStdToken(mntpTokenAddr);
goldToken = IStdToken(goldTokenAddr);
}
function setNewControllerAddress(address newAddress) onlyController public {
controllerAddress = newAddress;
}
function addHeldTokens(address userAddress, uint256 tokenAmount) onlyController public {
_userStakes[userAddress] = SafeMath.add(_userStakes[userAddress], tokenAmount);
totalMntpHeld = SafeMath.add(totalMntpHeld, tokenAmount);
addUserPayouts(userAddress, SafeMath.mul(mntpRewardPerShare, tokenAmount), SafeMath.mul(goldRewardPerShare, tokenAmount));
}
function freeHeldTokens(address userAddress) onlyController public {
totalMntpHeld = SafeMath.sub(totalMntpHeld, _userStakes[userAddress]);
_userStakes[userAddress] = 0;
_rewardMntpPayouts[userAddress] = 0;
_rewardGoldPayouts[userAddress] = 0;
}
function addRewardPerShare(uint256 mntpReward, uint256 goldReward) onlyController public {
require(totalMntpHeld > 0);
uint256 mntpShareReward = SafeMath.div(SafeMath.mul(mntpReward, MAGNITUDE), totalMntpHeld);
uint256 goldShareReward = SafeMath.div(SafeMath.mul(goldReward, MAGNITUDE), totalMntpHeld);
mntpRewardPerShare = SafeMath.add(mntpRewardPerShare, mntpShareReward);
goldRewardPerShare = SafeMath.add(goldRewardPerShare, goldShareReward);
}
function addUserPayouts(address userAddress, uint256 mntpReward, uint256 goldReward) onlyController public {
_rewardMntpPayouts[userAddress] = SafeMath.add(_rewardMntpPayouts[userAddress], mntpReward);
_rewardGoldPayouts[userAddress] = SafeMath.add(_rewardGoldPayouts[userAddress], goldReward);
}
function getMntpTokenUserReward(address userAddress) public view returns(uint256 reward, uint256 rewardAmp) {
rewardAmp = SafeMath.mul(mntpRewardPerShare, getUserStake(userAddress));
rewardAmp = (rewardAmp < getUserMntpRewardPayouts(userAddress)) ? 0 : SafeMath.sub(rewardAmp, getUserMntpRewardPayouts(userAddress));
reward = SafeMath.div(rewardAmp, MAGNITUDE);
return (reward, rewardAmp);
}
function getGoldTokenUserReward(address userAddress) public view returns(uint256 reward, uint256 rewardAmp) {
rewardAmp = SafeMath.mul(goldRewardPerShare, getUserStake(userAddress));
rewardAmp = (rewardAmp < getUserGoldRewardPayouts(userAddress)) ? 0 : SafeMath.sub(rewardAmp, getUserGoldRewardPayouts(userAddress));
reward = SafeMath.div(rewardAmp, MAGNITUDE);
return (reward, rewardAmp);
}
function getUserMntpRewardPayouts(address userAddress) public view returns(uint256) {
return _rewardMntpPayouts[userAddress];
}
function getUserGoldRewardPayouts(address userAddress) public view returns(uint256) {
return _rewardGoldPayouts[userAddress];
}
function getUserStake(address userAddress) public view returns(uint256) {
return _userStakes[userAddress];
}
}
contract GoldmintPool {
address public tokenBankAddress = address(0x0);
PoolCore public core;
IStdToken public mntpToken;
IStdToken public goldToken;
bool public isActualContractVer = true;
bool public isActive = true;
event onDistribShareProfit(uint256 mntpReward, uint256 goldReward);
event onUserRewardWithdrawn(address indexed userAddress, uint256 mntpReward, uint256 goldReward);
event onHoldStake(address indexed userAddress, uint256 mntpAmount);
event onUnholdStake(address indexed userAddress, uint256 mntpAmount);
modifier onlyAdministrator() {
require(core.isAdministrator(msg.sender));
_;
}
modifier onlyAdministratorOrManager() {
require(core.isAdministrator(msg.sender) || core.isManager(msg.sender));
_;
}
modifier notNullAddress(address addr) {
require(addr != address(0x0));
_;
}
modifier onlyActive() {
require(isActive);
_;
}
constructor(address coreAddr, address tokenBankAddr) notNullAddress(coreAddr) notNullAddress(tokenBankAddr) public {
core = PoolCore(coreAddr);
mntpToken = core.mntpToken();
goldToken = core.goldToken();
tokenBankAddress = tokenBankAddr;
}
function setTokenBankAddress(address addr) onlyAdministrator notNullAddress(addr) public {
tokenBankAddress = addr;
}
function switchActive() onlyAdministrator public {
require(isActualContractVer);
isActive = !isActive;
}
function holdStake(uint256 mntpAmount) onlyActive public {
require(mntpToken.balanceOf(msg.sender) > 0);
require(mntpToken.balanceOf(msg.sender) >= mntpAmount);
mntpToken.transferFrom(msg.sender, address(this), mntpAmount);
core.addHeldTokens(msg.sender, mntpAmount);
emit onHoldStake(msg.sender, mntpAmount);
}
function unholdStake() onlyActive public {
uint256 amount = core.getUserStake(msg.sender);
require(amount > 0);
require(getMntpBalance() >= amount);
core.freeHeldTokens(msg.sender);
mntpToken.transfer(msg.sender, amount);
emit onUnholdStake(msg.sender, amount);
}
function distribShareProfit(uint256 mntpReward, uint256 goldReward) onlyActive onlyAdministratorOrManager public {
if (mntpReward > 0) mntpToken.transferFrom(tokenBankAddress, address(this), mntpReward);
if (goldReward > 0) goldToken.transferFrom(tokenBankAddress, address(this), goldReward);
core.addRewardPerShare(mntpReward, goldReward);
emit onDistribShareProfit(mntpReward, goldReward);
}
function withdrawUserReward() onlyActive public {
uint256 mntpReward; uint256 mntpRewardAmp;
uint256 goldReward; uint256 goldRewardAmp;
(mntpReward, mntpRewardAmp) = core.getMntpTokenUserReward(msg.sender);
(goldReward, goldRewardAmp) = core.getGoldTokenUserReward(msg.sender);
require(getMntpBalance() >= mntpReward);
require(getGoldBalance() >= goldReward);
core.addUserPayouts(msg.sender, mntpRewardAmp, goldRewardAmp);
if (mntpReward > 0) mntpToken.transfer(msg.sender, mntpReward);
if (goldReward > 0) goldToken.transfer(msg.sender, goldReward);
emit onUserRewardWithdrawn(msg.sender, mntpReward, goldReward);
}
function withdrawRewardAndUnholdStake() onlyActive public {
withdrawUserReward();
unholdStake();
}
function addRewadToStake() onlyActive public {
uint256 mntpReward; uint256 mntpRewardAmp;
(mntpReward, mntpRewardAmp) = core.getMntpTokenUserReward(msg.sender);
require(mntpReward > 0);
core.addUserPayouts(msg.sender, mntpRewardAmp, 0);
core.addHeldTokens(msg.sender, mntpReward);
}
function migrateToNewControllerContract(address newControllerAddr) onlyAdministrator public {
require(newControllerAddr != address(0x0) && isActualContractVer);
isActive = false;
core.setNewControllerAddress(newControllerAddr);
uint256 mntpTokenAmount = getMntpBalance();
uint256 goldTokenAmount = getGoldBalance();
if (mntpTokenAmount > 0) mntpToken.transfer(newControllerAddr, mntpTokenAmount);
if (goldTokenAmount > 0) goldToken.transfer(newControllerAddr, goldTokenAmount);
isActualContractVer = false;
}
function getMntpTokenUserReward() public view returns(uint256) {
uint256 mntpReward; uint256 mntpRewardAmp;
(mntpReward, mntpRewardAmp) = core.getMntpTokenUserReward(msg.sender);
return mntpReward;
}
function getGoldTokenUserReward() public view returns(uint256) {
uint256 goldReward; uint256 goldRewardAmp;
(goldReward, goldRewardAmp) = core.getGoldTokenUserReward(msg.sender);
return goldReward;
}
function getUserMntpRewardPayouts() public view returns(uint256) {
return core.getUserMntpRewardPayouts(msg.sender);
}
function getUserGoldRewardPayouts() public view returns(uint256) {
return core.getUserGoldRewardPayouts(msg.sender);
}
function getUserStake() public view returns(uint256) {
return core.getUserStake(msg.sender);
}
function getMntpBalance() view public returns(uint256) {
return mntpToken.balanceOf(address(this));
}
function getGoldBalance() view public returns(uint256) {
return goldToken.balanceOf(address(this));
}
}
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;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? b : a;
}
} | 0 |
pragma solidity ^0.4.15;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_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 PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract PallyCoin is PausableToken {
using SafeMath for uint256;
string public constant name = 'PallyCoin';
string public constant symbol = 'PAL';
uint8 public constant decimals = 18;
uint256 public totalSupply = 100e24;
bool public remainingTokenBurnt = false;
uint256 public tokensDistributedPresale = 0;
uint256 public tokensDistributedCrowdsale = 0;
address public crowdsale;
uint256 public initialSupply = 40e24;
uint256 public limitPresale = 10e24;
uint256 public limitCrowdsale = 50e24;
modifier onlyCrowdsale() {
require(msg.sender == crowdsale);
_;
}
event RefundedTokens(address indexed user, uint256 tokens);
function PallyCoin() {
balances[msg.sender] = initialSupply;
}
function setCrowdsaleAddress(address _crowdsale) external onlyOwner whenNotPaused {
require(_crowdsale != address(0));
crowdsale = _crowdsale;
}
function distributePresaleTokens(address _buyer, uint tokens) external onlyOwner whenNotPaused {
require(_buyer != address(0));
require(tokens > 0 && tokens <= limitPresale);
require(tokensDistributedPresale < limitPresale);
require(tokensDistributedPresale.add(tokens) < limitPresale);
tokensDistributedPresale = tokensDistributedPresale.add(tokens);
balances[_buyer] = balances[_buyer].add(tokens);
}
function distributeICOTokens(address _buyer, uint tokens) external onlyCrowdsale whenNotPaused {
require(_buyer != address(0));
require(tokens > 0);
require(tokensDistributedCrowdsale < limitCrowdsale);
require(tokensDistributedCrowdsale.add(tokens) <= limitCrowdsale);
tokensDistributedCrowdsale = tokensDistributedCrowdsale.add(tokens);
balances[_buyer] = balances[_buyer].add(tokens);
}
function refundTokens(address _buyer, uint256 tokens) external onlyCrowdsale whenNotPaused {
require(_buyer != address(0));
require(tokens > 0);
require(balances[_buyer] >= tokens);
balances[_buyer] = balances[_buyer].sub(tokens);
RefundedTokens(_buyer, tokens);
}
function burnTokens() external onlyCrowdsale whenNotPaused {
uint256 remainingICOToken = limitCrowdsale.sub(tokensDistributedCrowdsale);
if(remainingICOToken > 0 && !remainingTokenBurnt) {
remainingTokenBurnt = true;
limitCrowdsale = limitCrowdsale.sub(remainingICOToken);
totalSupply = totalSupply.sub(remainingICOToken);
}
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract MISTT1Basic is ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
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];
}
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 MISTT1 is MISTT1Basic {
string public name = 'Mechanical In Social';
string public symbol = 'MISTT1';
uint8 public decimals = 4;
uint public INITIAL_SUPPLY = 30000000000* 10**uint(decimals);
function MISTT1() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
balances[0x97a6fF5391664CACD27e299AE04e7D23bb5B8A11] = totalSupply_;
Transfer(address(0), 0x97a6fF5391664CACD27e299AE04e7D23bb5B8A11, totalSupply_);
}
} | 1 |
pragma solidity ^0.4.25;
library SafeMath256 {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a==0 || b==0)
return 0;
uint256 c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b>0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require( b<= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract Ownable {
mapping (address=>bool) owners;
address owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AddOwner(address newOwner);
event RemoveOwner(address owner);
constructor() public {
owner = msg.sender;
owners[msg.sender] = true;
}
function isContract(address _addr) internal view returns(bool){
uint256 length;
assembly{
length := extcodesize(_addr)
}
if(length > 0){
return true;
}
else {
return false;
}
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner{
require(isContract(newOwner) == false);
emit OwnershipTransferred(owner,newOwner);
owner = newOwner;
}
modifier onlyOwners(){
require(owners[msg.sender] == true);
_;
}
function addOwner(address newOwner) public onlyOwners{
require(owners[newOwner] == false);
require(newOwner != msg.sender);
owners[newOwner] = true;
emit AddOwner(newOwner);
}
function removeOwner(address _owner) public onlyOwners{
require(_owner != msg.sender);
owners[_owner] = false;
emit RemoveOwner(_owner);
}
function isOwner(address _owner) public view returns(bool){
return owners[_owner];
}
}
contract ERC20 {
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
function totalSupply() public view returns (uint256);
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
}
contract StandardERC20 is ERC20{
using SafeMath256 for uint256;
mapping (address => uint256) balance;
mapping (address => mapping (address=>uint256)) allowed;
uint256 totalSupply_;
event Transfer(address indexed from,address indexed to,uint256 value);
event Approval(address indexed owner,address indexed spender,uint256 value);
function totalSupply() public view returns (uint256){
return totalSupply_;
}
function balanceOf(address _walletAddress) public view returns (uint256){
return balance[_walletAddress];
}
function allowance(address _owner, address _spender) public view returns (uint256){
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool){
require(_value <= balance[msg.sender]);
require(_to != address(0));
balance[msg.sender] = balance[msg.sender].sub(_value);
balance[_to] = balance[_to].add(_value);
emit Transfer(msg.sender,_to,_value);
return true;
}
function approve(address _spender, uint256 _value)
public returns (bool){
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool){
require(_value <= balance[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balance[_from] = balance[_from].sub(_value);
balance[_to] = balance[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
}
contract SGDSInterface{
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function intTransfer(address _from, address _to, uint256 _value) external;
function transferWallet(address _from,address _to) external;
function getCanControl(address _addr) external view returns(bool);
function useSGDS(address useAddr,uint256 value) external returns(bool);
}
contract NATEE_WARRANT is StandardERC20, Ownable {
using SafeMath256 for uint256;
string public name = "NATEE WARRANT";
string public symbol = "NATEE-W1";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 20000000 ether;
uint256 public totalUndist;
uint256 public totalRedeem;
address public NATEE_CONTRACT = address(0);
uint256 public transFee = 100;
uint32 public expireDate;
SGDSInterface public sgds;
event RedeemWarrant(address indexed addr,uint256 _value);
event SetControlToken(address indexed addr, bool outControl);
event FeeTransfer(address indexed addr,uint256 _value);
event TransferWallet(address indexed from,address indexed to,address indexed execute_);
mapping(address => bool) userControl;
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
totalUndist = INITIAL_SUPPLY;
expireDate = uint32(now + 1825 days);
sgds = SGDSInterface(0xf7EfaF88B380469084f3018271A49fF743899C89);
}
function setExpireDate(uint32 newDate) external onlyOwners{
if(newDate < expireDate && newDate > uint32(now))
{
expireDate = newDate;
}
}
function sendWarrant(address _to,uint256 _value) external onlyOwners {
require(_value <= totalUndist);
balance[_to] += _value;
totalUndist -= _value;
emit Transfer(address(this),_to,_value);
}
function intTransfer(address _from, address _to, uint256 _value) external onlyOwners{
require(userControl[_from] == false);
require(balance[_from] >= _value);
balance[_from] -= _value;
balance[_to] += _value;
emit Transfer(_from,_to,_value);
}
function transferWallet(address _from,address _to) external onlyOwners{
require(userControl[_from] == false);
require(sgds.getCanControl(_from) == false);
require(sgds.balanceOf(_from) >= transFee);
uint256 value = balance[_from];
balance[_from] = balance[_from].sub(value);
balance[_to] = balance[_to].add(value);
sgds.useSGDS(_from,transFee);
emit TransferWallet(_from,_to,msg.sender);
emit Transfer(_from,_to,value);
}
function redeemWarrant(address _from, uint256 _value) external {
require(msg.sender == NATEE_CONTRACT);
require(balance[_from] >= _value);
balance[_from] = balance[_from].sub(_value);
totalSupply_ -= _value;
totalRedeem += _value;
emit Transfer(_from,address(0),_value);
emit RedeemWarrant(_from,_value);
}
function setUserControl(bool _control) public {
userControl[msg.sender] = _control;
emit SetControlToken(msg.sender,_control);
}
function getUserControl(address _addr) external view returns(bool){
return userControl[_addr];
}
function setNateeContract(address addr) onlyOwners external{
require(NATEE_CONTRACT == address(0));
NATEE_CONTRACT = addr;
}
function setTransFee(uint256 _fee) onlyOwners public{
transFee = _fee;
}
} | 0 |
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract EjectableOwnable is Ownable {
function removeOwnership() onlyOwner public {
owner = 0x0;
}
}
contract JointOwnable is Ownable {
event AnotherOwnerAssigned(address indexed anotherOwner);
address public anotherOwner;
modifier eitherOwner() {
require(msg.sender == owner || msg.sender == anotherOwner);
_;
}
function assignAnotherOwner(address _anotherOwner) onlyOwner public {
require(_anotherOwner != 0);
AnotherOwnerAssigned(_anotherOwner);
anotherOwner = _anotherOwner;
}
}
contract Destructible is Ownable {
function Destructible() public payable { }
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract DungeonStructs {
struct Dungeon {
uint32 creationTime;
uint16 status;
uint16 difficulty;
uint32 floorNumber;
uint32 floorCreationTime;
uint128 rewards;
uint seedGenes;
uint floorGenes;
}
struct Hero {
uint64 creationTime;
uint genes;
}
}
contract ERC721 {
event Transfer(address indexed from, address indexed to, uint tokenId);
function totalSupply() public view returns (uint);
function balanceOf(address _owner) public view returns (uint);
function ownerOf(uint _tokenId) external view returns (address);
function transfer(address _to, uint _tokenId) external;
}
contract DungeonToken is ERC721, DungeonStructs, Pausable, JointOwnable {
uint public constant DUNGEON_CREATION_LIMIT = 1024;
event Mint(address indexed owner, uint newTokenId, uint difficulty, uint seedGenes);
event NewDungeonFloor(uint timestamp, uint indexed dungeonId, uint32 newFloorNumber, uint128 newRewards , uint newFloorGenes);
event Transfer(address indexed from, address indexed to, uint tokenId);
string public constant name = "Dungeon";
string public constant symbol = "DUNG";
Dungeon[] public dungeons;
mapping(uint => address) tokenIndexToOwner;
mapping(address => uint) ownershipTokenCount;
mapping(address => uint[]) public ownerTokens;
function totalSupply() public view returns (uint) {
return dungeons.length;
}
function balanceOf(address _owner) public view returns (uint) {
return ownershipTokenCount[_owner];
}
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIndexToOwner[_tokenId] != address(0));
return tokenIndexToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint _tokenId) internal {
ownershipTokenCount[_to]++;
tokenIndexToOwner[_tokenId] = _to;
ownerTokens[_to].push(_tokenId);
if (_from != address(0)) {
ownershipTokenCount[_from]--;
uint[] storage fromTokens = ownerTokens[_from];
bool iFound = false;
for (uint i = 0; i < fromTokens.length - 1; i++) {
if (iFound) {
fromTokens[i] = fromTokens[i + 1];
} else if (fromTokens[i] == _tokenId) {
iFound = true;
}
}
}
Transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint _tokenId) whenNotPaused external {
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function createDungeon(uint _difficulty, uint _seedGenes, address _owner) eitherOwner external returns (uint) {
require(totalSupply() < DUNGEON_CREATION_LIMIT);
dungeons.push(Dungeon(uint32(now), 0, uint16(_difficulty), 0, 0, 0, _seedGenes, 0));
uint newTokenId = dungeons.length - 1;
Mint(_owner, newTokenId, _difficulty, _seedGenes);
addDungeonNewFloor(newTokenId, 0, _seedGenes);
_transfer(0, _owner, newTokenId);
return newTokenId;
}
function setDungeonStatus(uint _id, uint _newStatus) eitherOwner external {
require(_id < totalSupply());
dungeons[_id].status = uint16(_newStatus);
}
function addDungeonRewards(uint _id, uint _additinalRewards) eitherOwner external {
require(_id < totalSupply());
dungeons[_id].rewards += uint64(_additinalRewards);
}
function addDungeonNewFloor(uint _id, uint _newRewards, uint _newFloorGenes) eitherOwner public {
require(_id < totalSupply());
Dungeon storage dungeon = dungeons[_id];
dungeon.floorNumber++;
dungeon.floorCreationTime = uint32(now);
dungeon.rewards = uint128(_newRewards);
dungeon.floorGenes = _newFloorGenes;
NewDungeonFloor(now, _id, dungeon.floorNumber, dungeon.rewards, dungeon.floorGenes);
}
}
contract HeroToken is ERC721, DungeonStructs, Pausable, JointOwnable {
event Mint(address indexed owner, uint newTokenId, uint _genes);
event Transfer(address indexed from, address indexed to, uint tokenId);
string public constant name = "Hero";
string public constant symbol = "HERO";
Hero[] public heroes;
mapping(uint => address) tokenIndexToOwner;
mapping(address => uint) ownershipTokenCount;
mapping(address => uint[]) public ownerTokens;
function totalSupply() public view returns (uint) {
return heroes.length;
}
function balanceOf(address _owner) public view returns (uint) {
return ownershipTokenCount[_owner];
}
function _owns(address _claimant, uint _tokenId) internal view returns (bool) {
return tokenIndexToOwner[_tokenId] == _claimant;
}
function ownerOf(uint _tokenId) external view returns (address) {
require(tokenIndexToOwner[_tokenId] != address(0));
return tokenIndexToOwner[_tokenId];
}
function _transfer(address _from, address _to, uint _tokenId) internal {
ownershipTokenCount[_to]++;
tokenIndexToOwner[_tokenId] = _to;
ownerTokens[_to].push(_tokenId);
if (_from != address(0)) {
ownershipTokenCount[_from]--;
uint[] storage fromTokens = ownerTokens[_from];
bool iFound = false;
for (uint i = 0; i < fromTokens.length - 1; i++) {
if (iFound) {
fromTokens[i] = fromTokens[i + 1];
} else if (fromTokens[i] == _tokenId) {
iFound = true;
}
}
}
Transfer(_from, _to, _tokenId);
}
function transfer(address _to, uint _tokenId) whenNotPaused external {
require(_to != address(0));
require(_to != address(this));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function createHero(uint _genes, address _owner) external returns (uint) {
heroes.push(Hero(uint64(now), _genes));
uint newTokenId = heroes.length - 1;
Mint(_owner, newTokenId, _genes);
_transfer(0, _owner, newTokenId);
return newTokenId;
}
function setHeroGenes(uint _id, uint _newGenes) eitherOwner external {
require(_id < totalSupply());
Hero storage hero = heroes[_id];
hero.genes = _newGenes;
}
}
contract ChallengeScienceInterface {
function mixGenes(uint _floorGenes, uint _seedGenes) external pure returns (uint);
}
contract TrainingScienceInterface {
function mixGenes(uint _heroGenes, uint _floorGenes) external pure returns (uint);
}
contract DungeonBase is EjectableOwnable, Pausable, PullPayment, DungeonStructs {
DungeonToken public dungeonTokenContract;
HeroToken public heroTokenContract;
ChallengeScienceInterface challengeScienceContract;
TrainingScienceInterface trainingScienceContract;
function setDungeonTokenContract(address _newDungeonTokenContract) onlyOwner external {
dungeonTokenContract = DungeonToken(_newDungeonTokenContract);
}
function setHeroTokenContract(address _newHeroTokenContract) onlyOwner external {
heroTokenContract = HeroToken(_newHeroTokenContract);
}
function setChallengeScienceContract(address _newChallengeScienceAddress) onlyOwner external {
challengeScienceContract = ChallengeScienceInterface(_newChallengeScienceAddress);
}
function setTrainingScienceContract(address _newTrainingScienceAddress) onlyOwner external {
trainingScienceContract = TrainingScienceInterface(_newTrainingScienceAddress);
}
modifier dungeonExists(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
_;
}
modifier canChallenge(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
uint status;
(,status,,,,,,) = dungeonTokenContract.dungeons(_dungeonId);
require(status == 0 || status == 1);
_;
}
modifier canTrain(uint _dungeonId) {
require(_dungeonId < dungeonTokenContract.totalSupply());
uint status;
(,status,,,,,,) = dungeonTokenContract.dungeons(_dungeonId);
require(status == 0 || status == 2);
_;
}
function _getGenesPower(uint _genes) internal pure returns (uint) {
uint statsPower;
for (uint i = 0; i < 4; i++) {
statsPower += _genes % 32;
_genes /= 32 ** 4;
}
uint equipmentPower;
bool isSuper = true;
for (uint j = 4; j < 12; j++) {
uint curGene = _genes % 32;
equipmentPower += curGene;
_genes /= 32 ** 4;
if (equipmentPower != curGene * (j - 3)) {
isSuper = false;
}
}
if (isSuper) {
equipmentPower *= 2;
}
return statsPower + equipmentPower + 12;
}
}
contract DungeonChallenge is DungeonBase {
event DungeonChallenged(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newFloorGenes, uint successRewards, uint masterRewards);
uint256 public challengeFeeMultiplier = 1 finney;
uint public challengeRewardsPercent = 64;
uint public masterRewardsPercent = 8;
function challenge(uint _dungeonId) external payable whenNotPaused canChallenge(_dungeonId) {
uint difficulty;
uint seedGenes;
(,,difficulty,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);
uint requiredFee = difficulty * challengeFeeMultiplier;
require(msg.value >= requiredFee);
dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);
asyncSend(msg.sender, msg.value - requiredFee);
_challengePart2(_dungeonId, requiredFee);
}
function _challengePart2(uint _dungeonId, uint _requiredFee) private {
uint floorNumber;
uint rewards;
uint floorGenes;
(,,,floorNumber,,rewards,,floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
uint _addedRewards = rewards + uint128(_requiredFee);
uint heroGenes = _getFirstHeroGenesAndInitialize(_dungeonId);
bool success = _getChallengeSuccess(heroGenes, floorGenes);
uint newFloorGenes;
uint successRewards;
uint masterRewards;
if (success) {
newFloorGenes = _getNewFloorGene(_dungeonId);
successRewards = _addedRewards * challengeRewardsPercent / 100;
masterRewards = _addedRewards * masterRewardsPercent / 100;
uint newRewards = _addedRewards * (100 - challengeRewardsPercent - masterRewardsPercent) / 100;
dungeonTokenContract.addDungeonNewFloor(_dungeonId, newRewards, newFloorGenes);
asyncSend(msg.sender, _addedRewards * challengeRewardsPercent / 100);
asyncSend(owner, _addedRewards * masterRewardsPercent / 100);
}
DungeonChallenged(now, msg.sender, _dungeonId, heroGenes, floorNumber, floorGenes, success, newFloorGenes, successRewards, masterRewards);
}
function _getFirstHeroGenesAndInitialize(uint _dungeonId) private returns (uint heroGenes) {
uint seedGenes;
(,,,,,,seedGenes,) = dungeonTokenContract.dungeons(_dungeonId);
uint heroId;
if (heroTokenContract.balanceOf(msg.sender) == 0) {
heroId = heroTokenContract.createHero(seedGenes, msg.sender);
} else {
heroId = heroTokenContract.ownerTokens(msg.sender, 0);
}
(,heroGenes) = heroTokenContract.heroes(heroId);
}
function _getChallengeSuccess(uint heroGenes, uint floorGenes) private pure returns (bool) {
uint heroPower = _getGenesPower(heroGenes);
uint floorPower = _getGenesPower(floorGenes);
return heroPower > floorPower;
}
function _getNewFloorGene(uint _dungeonId) private view returns (uint) {
uint seedGenes;
uint floorGenes;
(,,,,,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
uint floorPower = _getGenesPower(floorGenes);
uint newFloorGenes = challengeScienceContract.mixGenes(floorGenes, seedGenes);
uint newFloorPower = _getGenesPower(newFloorGenes);
if (newFloorPower < floorPower) {
newFloorGenes = floorGenes;
}
return newFloorGenes;
}
function setChallengeFeeMultiplier(uint _newChallengeFeeMultiplier) external onlyOwner {
challengeFeeMultiplier = _newChallengeFeeMultiplier;
}
function setChallengeRewardsPercent(uint _newChallengeRewardsPercent) onlyOwner external {
challengeRewardsPercent = _newChallengeRewardsPercent;
}
function setMasterRewardsPercent(uint _newMasterRewardsPercent) onlyOwner external {
masterRewardsPercent = _newMasterRewardsPercent;
}
}
contract DungeonTraining is DungeonChallenge {
event HeroTrained(uint timestamp, address indexed playerAddress, uint indexed dungeonId, uint heroGenes, uint floorNumber, uint floorGenes, bool success, uint newHeroGenes);
uint256 public trainingFeeMultiplier = 2 finney;
function setTrainingFeeMultiplier(uint _newTrainingFeeMultiplier) external onlyOwner {
trainingFeeMultiplier = _newTrainingFeeMultiplier;
}
function train1(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) {
_train(_dungeonId, 1);
}
function train2(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) {
_train(_dungeonId, 2);
}
function train3(uint _dungeonId) external payable whenNotPaused canTrain(_dungeonId) {
_train(_dungeonId, 3);
}
function _train(uint _dungeonId, uint _trainingTimes) private {
uint difficulty;
uint floorNumber;
uint rewards;
uint seedGenes;
uint floorGenes;
(,,difficulty,floorNumber,,rewards,seedGenes,floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
require(_trainingTimes < 10);
uint requiredFee = difficulty * trainingFeeMultiplier * _trainingTimes;
require(msg.value >= requiredFee);
uint heroId;
if (heroTokenContract.balanceOf(msg.sender) == 0) {
heroId = heroTokenContract.createHero(seedGenes, msg.sender);
} else {
heroId = heroTokenContract.ownerTokens(msg.sender, 0);
}
dungeonTokenContract.addDungeonRewards(_dungeonId, requiredFee);
asyncSend(msg.sender, msg.value - requiredFee);
_trainPart2(_dungeonId, _trainingTimes, heroId);
}
function _trainPart2(uint _dungeonId, uint _trainingTimes, uint _heroId) private {
uint floorNumber;
uint floorGenes;
(,,,floorNumber,,,,floorGenes) = dungeonTokenContract.dungeons(_dungeonId);
uint heroGenes;
(,heroGenes) = heroTokenContract.heroes(_heroId);
uint heroPower = _getGenesPower(heroGenes);
uint newHeroGenes = heroGenes;
uint newHeroPower = heroPower;
for (uint i = 0; i < _trainingTimes; i++) {
uint tmpHeroGenes = trainingScienceContract.mixGenes(newHeroGenes, floorGenes);
uint tmpHeroPower = _getGenesPower(tmpHeroGenes);
if (tmpHeroPower > newHeroPower) {
newHeroGenes = tmpHeroGenes;
newHeroPower = tmpHeroPower;
}
}
bool success = newHeroPower > heroPower;
if (success) {
heroTokenContract.setHeroGenes(_heroId, newHeroGenes);
}
HeroTrained(now, msg.sender, _dungeonId, heroGenes, floorNumber, floorGenes, success, newHeroGenes);
}
}
contract DungeonCoreAlpha is Destructible, DungeonTraining {
function DungeonCoreAlpha(
address _dungeonTokenAddress,
address _heroTokenAddress,
address _challengeScienceAddress,
address _trainingScienceAddress
) public payable {
dungeonTokenContract = DungeonToken(_dungeonTokenAddress);
heroTokenContract = HeroToken(_heroTokenAddress);
challengeScienceContract = ChallengeScienceInterface(_challengeScienceAddress);
trainingScienceContract = TrainingScienceInterface(_trainingScienceAddress);
}
function getDungeonDetails(uint _id) external view returns (uint creationTime, uint status, uint difficulty, uint floorNumber, uint floorCreationTime, uint rewards, uint seedGenes, uint floorGenes) {
require(_id < dungeonTokenContract.totalSupply());
(creationTime, status, difficulty, floorNumber, floorCreationTime, rewards, seedGenes, floorGenes) = dungeonTokenContract.dungeons(_id);
}
function getHeroDetails(uint _id) external view returns (uint creationTime, uint genes) {
require(_id < heroTokenContract.totalSupply());
(creationTime, genes) = heroTokenContract.heroes(_id);
}
} | 0 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount) public;
function unlock() public;
function burn(uint256 _value) public returns (bool);
}
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 {
bool public stopped;
modifier stopInEmergency {
require(!stopped);
_;
}
modifier onlyInEmergency {
require(stopped);
_;
}
function emergencyStop() external onlyOwner {
stopped = true;
}
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
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 ICO is SafeMath, Pausable{
address public ifSuccessfulSendFundsTo;
address public BTCproxy;
address public GBPproxy;
uint public fundingGoal;
uint public amountRaised;
uint public tokensSold;
uint public maxToken;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event FundWithdrawal(address addr, uint value);
event ReceivedETH(address addr, uint value);
event ReceivedBTC(address addr, uint value);
event ReceivedGBP(address addr, uint value);
modifier ICOactive{
require(!crowdsaleClosed);
_;
}
modifier ICOinactive{
require(crowdsaleClosed);
_;
}
modifier onlyBy(address a){
require(msg.sender == a);
_;
}
function ICO() public{
maxToken = 40*(10 ** 6) * (10 ** 6);
stopped = false;
tokensSold = 0;
ifSuccessfulSendFundsTo = 0xDB9e5d21B0c4f06b55fb85ff96acfF75d94D60F7;
BTCproxy = 0x50651260Ba2B8A3264F1AE074E7a6E7Da101567a;
GBPproxy = 0x1ABb9E204Eb8E546eFA06Cbb8c039A91227cb211;
fundingGoal = 100 ether;
tokenReward = token(0xc4796a5bfc6fa56ea42b5e7c7889abcf724c44fd);
}
function () public payable stopInEmergency ICOactive{
require(msg.value >= 0.01 ether);
uint amount = amountToSend(msg.value);
if (amount==0){
revert();
}else{
balanceOf[msg.sender] += msg.value;
amountRaised += msg.value;
tokenReward.transfer(msg.sender,amount);
tokensSold = add(tokensSold,amount);
ReceivedETH(msg.sender,msg.value);
}
}
function ReceiveBTC(address addr, uint value) public stopInEmergency ICOactive onlyBy(BTCproxy){
require(value >= 0.01 ether);
uint amount = amountToSend(value);
if (amount==0){
revert();
}else{
amountRaised += value;
tokenReward.transfer(addr,amount);
tokensSold = add(tokensSold,amount);
ReceivedBTC(addr,value);
}
}
function ReceiveGBP(address addr, uint value) public stopInEmergency ICOactive onlyBy(GBPproxy){
require(value >= 0.01 ether);
uint amount = amountToSend(value);
if (amount==0){
revert();
}else{
balanceOf[addr] += value;
amountRaised += value;
tokenReward.transfer(addr,amount);
tokensSold = add(tokensSold,amount);
ReceivedGBP(addr,value);
}
}
function amountToSend(uint amount) internal returns(uint){
uint toSend = 0;
if (tokensSold <= 5 * (10 ** 6) * (10 ** 6)){
toSend = mul(amount,1000*(10 ** 6))/(1 ether);
}else if (5 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 10 * (10 ** 6) * (10 ** 6)){
toSend = mul(amount,850*(10 ** 6))/(1 ether);
}else if (10 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 20 * (10 ** 6) * (10 ** 6)){
toSend = mul(amount,700*(10 ** 6))/(1 ether);
}else if (20 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 30 * (10 ** 6) * (10 ** 6)){
toSend = mul(amount,600*(10 ** 6))/(1 ether);
}else if (30 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 40 * (10 ** 6) * (10 ** 6)){
toSend = mul(amount,550*(10 ** 6))/(1 ether);
}
if (amount >= 10 ether){
toSend = add(toSend,toSend/50);
}
if (add(toSend,tokensSold) > maxToken){
return 0;
}else{
return toSend;
}
}
function finalize() public onlyBy(owner) {
if (amountRaised>=fundingGoal){
if (!ifSuccessfulSendFundsTo.send(amountRaised)){
revert();
}else{
fundingGoalReached = true;
}
}else{
fundingGoalReached = false;
}
uint HYDEmitted = add(tokensSold,10 * (10 ** 6) * (10 ** 6));
if (HYDEmitted < 50 * (10 ** 6) * (10 ** 6)){
tokenReward.burn(50 * (10 ** 6) * (10 ** 6) - HYDEmitted);
}
tokenReward.unlock();
crowdsaleClosed = true;
}
function safeWithdrawal() public ICOinactive{
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundWithdrawal(msg.sender, amount);
} else {
balanceOf[msg.sender] = amount;
}
}
}
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Interface {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Bqt_Token is ERC20Interface {
string public constant symbol = "BQT";
string public constant name = "BQT token";
uint8 public constant decimals = 18;
uint256 public constant maxTokens = 800*10**6*10**18;
uint256 public constant ownerSupply = maxTokens*51/100;
uint256 _totalSupply = ownerSupply;
uint256 public constant token_price = 10**18*1/800;
uint256 public pre_ico_start = 1528416000;
uint256 public ico_start = 1531008000;
uint256 public ico_finish = 1541635200;
uint public constant minValuePre = 10**18*1/1000000;
uint public constant minValue = 10**18*1/1000000;
uint public constant maxValue = 3000*10**18;
uint8 public constant exchange_coefficient = 102;
using SafeMath for uint;
address public owner;
address public moderator;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => uint256) public orders_sell_amount;
mapping(address => uint256) public orders_sell_price;
address[] public orders_sell_list;
event Order_sell(address indexed _owner, uint256 _max_amount, uint256 _price);
event Order_execute(address indexed _from, address indexed _to, uint256 _amount, uint256 _price);
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
modifier onlyModerator() {
if (msg.sender != moderator) {
throw;
}
_;
}
function changeOwner(address _owner) onlyOwner returns (bool result) {
owner = _owner;
return true;
}
function changeModerator(address _moderator) onlyOwner returns (bool result) {
moderator = _moderator;
return true;
}
function Bqt_Token() {
owner = 0x3d143e5f256a4fbc16ef23b29aadc0db67bf0ec2;
moderator = 0x788C45Dd60aE4dBE5055b5Ac02384D5dc84677b0;
balances[owner] = ownerSupply;
}
function() payable {
tokens_buy();
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
function withdraw(uint256 _amount) onlyOwner returns (bool result) {
uint256 balance;
balance = this.balance;
if(_amount > 0) balance = _amount;
owner.send(balance);
return true;
}
function change_pre_ico_start(uint256 _pre_ico_start) onlyModerator returns (bool result) {
pre_ico_start = _pre_ico_start;
return true;
}
function change_ico_start(uint256 _ico_start) onlyModerator returns (bool result) {
ico_start = _ico_start;
return true;
}
function change_ico_finish(uint256 _ico_finish) onlyModerator returns (bool result) {
ico_finish = _ico_finish;
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function tokens_buy() payable returns (bool) {
uint256 tnow = now;
if(tnow > ico_finish) throw;
if(_totalSupply >= maxTokens) throw;
if(!(msg.value >= token_price)) throw;
if(!(msg.value >= minValue)) throw;
if(msg.value > maxValue) throw;
uint tokens_buy = (msg.value*10**18).div(token_price);
uint tokens_buy_total;
if(!(tokens_buy > 0)) throw;
uint b1 = 0;
uint b2 = 0;
uint b3 = 0;
if(_totalSupply <= 5*10**6*10**18) {
b1 = tokens_buy*30/100;
}
if((5*10**6*10**18 < _totalSupply)&&(_totalSupply <= 10*10**6*10**18)) {
b1 = tokens_buy*25/100;
}
if((10*10**6*10**18 < _totalSupply)&&(_totalSupply <= 15*10**6*10**18)) {
b1 = tokens_buy*20/100;
}
if((15*10**6*10**18 < _totalSupply)&&(_totalSupply <= 20*10**6*10**18)) {
b1 = tokens_buy*15/100;
}
if((20*10**6*10**18 < _totalSupply)&&(_totalSupply <= 25*10**6*10**18)) {
b1 = tokens_buy*10/100;
}
if(25*10**6*10**18 <= _totalSupply) {
b1 = tokens_buy*5/100;
}
if(tnow < ico_start) {
b2 = tokens_buy*50/100;
}
if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*5)){
b2 = tokens_buy*10/100;
}
if((ico_start + 86400*5 <= tnow)&&(tnow < ico_start + 86400*10)){
b2 = tokens_buy*8/100;
}
if((ico_start + 86400*10 <= tnow)&&(tnow < ico_start + 86400*20)){
b2 = tokens_buy*6/100;
}
if((ico_start + 86400*20 <= tnow)&&(tnow < ico_start + 86400*30)){
b2 = tokens_buy*4/100;
}
if(ico_start + 86400*30 <= tnow){
b2 = tokens_buy*2/100;
}
if((1000*10**18 <= tokens_buy)&&(5000*10**18 <= tokens_buy)) {
b3 = tokens_buy*5/100;
}
if((5001*10**18 <= tokens_buy)&&(10000*10**18 < tokens_buy)) {
b3 = tokens_buy*10/100;
}
if((10001*10**18 <= tokens_buy)&&(15000*10**18 < tokens_buy)) {
b3 = tokens_buy*15/100;
}
if((15001*10**18 <= tokens_buy)&&(20000*10**18 < tokens_buy)) {
b3 = tokens_buy*20/100;
}
if(20001*10**18 <= tokens_buy) {
b3 = tokens_buy*25/100;
}
tokens_buy_total = tokens_buy.add(b1);
tokens_buy_total = tokens_buy_total.add(b2);
tokens_buy_total = tokens_buy_total.add(b3);
if(_totalSupply.add(tokens_buy_total) > maxTokens) throw;
_totalSupply = _totalSupply.add(tokens_buy_total);
balances[msg.sender] = balances[msg.sender].add(tokens_buy_total);
return true;
}
function orders_sell_total () constant returns (uint256) {
return orders_sell_list.length;
}
function get_orders_sell_amount(address _from) constant returns(uint) {
uint _amount_max = 0;
if(!(orders_sell_amount[_from] > 0)) return _amount_max;
if(balanceOf(_from) > 0) _amount_max = balanceOf(_from);
if(orders_sell_amount[_from] < _amount_max) _amount_max = orders_sell_amount[_from];
return _amount_max;
}
function order_sell(uint256 _max_amount, uint256 _price) returns (bool) {
if(!(_max_amount > 0)) throw;
if(!(_price > 0)) throw;
orders_sell_amount[msg.sender] = _max_amount;
orders_sell_price[msg.sender] = (_price*exchange_coefficient).div(100);
orders_sell_list.push(msg.sender);
Order_sell(msg.sender, _max_amount, orders_sell_price[msg.sender]);
return true;
}
function order_buy(address _from, uint256 _max_price) payable returns (bool) {
if(!(msg.value > 0)) throw;
if(!(_max_price > 0)) throw;
if(!(orders_sell_amount[_from] > 0)) throw;
if(!(orders_sell_price[_from] > 0)) throw;
if(orders_sell_price[_from] > _max_price) throw;
uint _amount = (msg.value*10**18).div(orders_sell_price[_from]);
uint _amount_from = get_orders_sell_amount(_from);
if(_amount > _amount_from) _amount = _amount_from;
if(!(_amount > 0)) throw;
uint _total_money = (orders_sell_price[_from]*_amount).div(10**18);
if(_total_money > msg.value) throw;
uint _seller_money = (_total_money*100).div(exchange_coefficient);
uint _buyer_money = msg.value - _total_money;
if(_seller_money > msg.value) throw;
if(_seller_money + _buyer_money > msg.value) throw;
if(_seller_money > 0) _from.send(_seller_money);
if(_buyer_money > 0) msg.sender.send(_buyer_money);
orders_sell_amount[_from] -= _amount;
balances[_from] -= _amount;
balances[msg.sender] += _amount;
Order_execute(_from, msg.sender, _amount, orders_sell_price[_from]);
}
} | 1 |
pragma solidity ^0.4.23;
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, "Only owner is allowed for this operation.");
_;
}
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), "Cannot transfer ownership to an empty user.");
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ANKRTokenVault is Ownable {
using SafeMath for uint256;
address public opentokenAddress = 0x7B1f5F0FCa6434D7b01161552D335A774706b650;
address public tokenmanAddress = 0xBB46219183f1F17364914e353A44F982de77eeC8;
address public marketingAddress = 0xc2e96F45232134dD32B6DF4D51AC82248CA942cc;
address public teamReserveWallet = 0x0AA7Aa665276A96acD25329354FeEa8F955CAf2b;
address public communityReserveWallet = 0xeFA1f626670445271359940e1aC346Ac374019E7;
uint256 public opentokenAllocation = 0.5 * (10 ** 9) * (10 ** 18);
uint256 public tokenmanAllocation = 0.2 * (10 ** 9) * (10 ** 18);
uint256 public marketingAllocation = 0.5 * (10 ** 9) * (10 ** 18);
uint256 public teamReserveAllocation = 2.0 * (10 ** 9) * (10 ** 18);
uint256 public communityReserveAllocation = 4.0 * (10 ** 9) * (10 ** 18);
uint256 public totalAllocation = 10 * (10 ** 9) * (10 ** 18);
uint256 public investorTimeLock = 183 days;
uint256 public othersTimeLock = 3 * 365 days;
uint256 public othersVestingStages = 3 * 12;
mapping(address => uint256) public allocations;
mapping(address => uint256) public timeLocks;
mapping(address => uint256) public claimed;
mapping(address => uint256) public lockedInvestors;
address[] public lockedInvestorsIndices;
mapping(address => uint256) public unLockedInvestors;
address[] public unLockedInvestorsIndices;
uint256 public lockedAt = 0;
ERC20Basic public token;
event Allocated(address wallet, uint256 value);
event Distributed(address wallet, uint256 value);
event Locked(uint256 lockTime);
modifier onlyReserveWallets {
require(allocations[msg.sender] > 0, "There should be non-zero allocation.");
_;
}
modifier notLocked {
require(lockedAt == 0, "lockedAt should be zero.");
_;
}
modifier locked {
require(lockedAt > 0, "lockedAt should be larger than zero.");
_;
}
modifier notAllocated {
require(allocations[opentokenAddress] == 0, "Allocation should be zero.");
require(allocations[tokenmanAddress] == 0, "Allocation should be zero.");
require(allocations[marketingAddress] == 0, "Allocation should be zero.");
require(allocations[teamReserveWallet] == 0, "Allocation should be zero.");
require(allocations[communityReserveWallet] == 0, "Allocation should be zero.");
_;
}
constructor(ERC20Basic _token) public {
token = ERC20Basic(_token);
}
function addUnlockedInvestor(address investor, uint256 amt) public onlyOwner notLocked notAllocated returns (bool) {
require(investor != address(0), "Unlocked investor must not be zero.");
require(amt > 0, "Unlocked investor's amount should be larger than zero.");
unLockedInvestorsIndices.push(investor);
unLockedInvestors[investor] = amt * (10 ** 18);
return true;
}
function addLockedInvestor(address investor, uint256 amt) public onlyOwner notLocked notAllocated returns (bool) {
require(investor != address(0), "Locked investor must not be zero.");
require(amt > 0, "Locked investor's amount should be larger than zero.");
lockedInvestorsIndices.push(investor);
lockedInvestors[investor] = amt * (10 ** 18);
return true;
}
function allocate() public notLocked notAllocated onlyOwner {
require(token.balanceOf(address(this)) == totalAllocation, "Token should not be allocated yet.");
allocations[opentokenAddress] = opentokenAllocation;
allocations[tokenmanAddress] = tokenmanAllocation;
allocations[marketingAddress] = marketingAllocation;
allocations[teamReserveWallet] = teamReserveAllocation;
allocations[communityReserveWallet] = communityReserveAllocation;
emit Allocated(opentokenAddress, opentokenAllocation);
emit Allocated(tokenmanAddress, tokenmanAllocation);
emit Allocated(marketingAddress, marketingAllocation);
emit Allocated(teamReserveWallet, teamReserveAllocation);
emit Allocated(communityReserveWallet, communityReserveAllocation);
address cur;
uint arrayLength;
uint i;
arrayLength = unLockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
cur = unLockedInvestorsIndices[i];
allocations[cur] = unLockedInvestors[cur];
emit Allocated(cur, unLockedInvestors[cur]);
}
arrayLength = lockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
cur = lockedInvestorsIndices[i];
allocations[cur] = lockedInvestors[cur];
emit Allocated(cur, lockedInvestors[cur]);
}
preDistribute();
}
function distribute() public notLocked onlyOwner {
claimTokenReserve(marketingAddress);
uint arrayLength;
uint i;
arrayLength = unLockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
claimTokenReserve(unLockedInvestorsIndices[i]);
}
lock();
}
function lock() internal {
lockedAt = block.timestamp;
timeLocks[teamReserveWallet] = lockedAt.add(othersTimeLock);
timeLocks[communityReserveWallet] = lockedAt.add(othersTimeLock);
emit Locked(lockedAt);
}
function recoverFailedLock() external notLocked notAllocated onlyOwner {
require(token.transfer(owner, token.balanceOf(address(this))), "recoverFailedLock: token transfer failed!");
}
function getTotalBalance() public view returns (uint256 tokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
function getLockedBalance() public view onlyReserveWallets returns (uint256 tokensLocked) {
return allocations[msg.sender].sub(claimed[msg.sender]);
}
function preDistribute() internal {
claimTokenReserve(opentokenAddress);
claimTokenReserve(tokenmanAddress);
}
function claimTokenReserve(address reserveWallet) internal {
require(allocations[reserveWallet] > 0, "There should be non-zero allocation.");
require(claimed[reserveWallet] == 0, "This address should be never claimed before.");
uint256 amount = allocations[reserveWallet];
claimed[reserveWallet] = amount;
require(token.transfer(reserveWallet, amount), "Token transfer failed");
emit Distributed(reserveWallet, amount);
}
function distributeInvestorsReserve() onlyOwner locked public {
require(block.timestamp.sub(lockedAt) > investorTimeLock, "Still in locking period.");
uint arrayLength;
uint i;
arrayLength = lockedInvestorsIndices.length;
for (i = 0; i < arrayLength; i++) {
claimTokenReserve(lockedInvestorsIndices[i]);
}
}
function claimNonInvestorReserve() public onlyOwner locked {
uint256 vestingStage = nonInvestorVestingStage();
uint256 totalUnlockedTeam = vestingStage.mul(allocations[teamReserveWallet]).div(othersVestingStages);
uint256 totalUnlockedComm = vestingStage.mul(allocations[communityReserveWallet]).div(othersVestingStages);
require(claimed[teamReserveWallet] < totalUnlockedTeam, "Team's claimed tokens must be less than what is unlocked");
require(claimed[communityReserveWallet] < totalUnlockedComm, "Community's claimed tokens must be less than what is unlocked");
uint256 paymentTeam = totalUnlockedTeam.sub(claimed[teamReserveWallet]);
uint256 paymentComm = totalUnlockedComm.sub(claimed[communityReserveWallet]);
claimed[teamReserveWallet] = totalUnlockedTeam;
claimed[communityReserveWallet] = totalUnlockedComm;
require(token.transfer(teamReserveWallet, paymentTeam), "Team token transfer failed.");
require(token.transfer(communityReserveWallet, paymentComm), "Community token transfer failed.");
emit Distributed(teamReserveWallet, paymentTeam);
emit Distributed(communityReserveWallet, paymentComm);
}
function nonInvestorVestingStage() public view returns(uint256){
uint256 vestingMonths = othersTimeLock.div(othersVestingStages);
uint256 stage = (block.timestamp.sub(lockedAt).sub(investorTimeLock)).div(vestingMonths);
if(stage > othersVestingStages){
stage = othersVestingStages;
}
return stage;
}
} | 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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract 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 CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract Superuser is Ownable, RBAC {
string public constant ROLE_SUPERUSER = "superuser";
constructor () public {
addRole(msg.sender, ROLE_SUPERUSER);
}
modifier onlySuperuser() {
checkRole(msg.sender, ROLE_SUPERUSER);
_;
}
modifier onlyOwnerOrSuperuser() {
require(msg.sender == owner || isSuperuser(msg.sender));
_;
}
function isSuperuser(address _addr)
public
view
returns (bool)
{
return hasRole(_addr, ROLE_SUPERUSER);
}
function transferSuperuser(address _newSuperuser) public onlySuperuser {
require(_newSuperuser != address(0));
removeRole(msg.sender, ROLE_SUPERUSER);
addRole(_newSuperuser, ROLE_SUPERUSER);
}
function transferOwnership(address _newOwner) public onlyOwnerOrSuperuser {
_transferOwnership(_newOwner);
}
}
contract CoinSmartt is Superuser, PausableToken, CappedToken {
string public name = "CoinSmartt";
string public symbol = "TURN";
uint256 public decimals = 18;
string public constant ROLE_MINTER = "minter";
constructor(address _minter) CappedToken(7663809523810000000000000000) {
addRole(_minter, ROLE_MINTER);
}
function mint(
address _to,
uint256 _amount
)
onlyRole("minter")
canMint
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function removeMinter(address _minter) onlyOwnerOrSuperuser {
removeRole(_minter, "minter");
}
function addMinter(address _minter) onlyOwnerOrSuperuser {
addRole(_minter, "minter");
}
} | 1 |
pragma solidity ^0.4.18;
contract EBU{
address public from = 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9;
address public caddress = 0x1f844685f7Bf86eFcc0e74D8642c54A257111923;
function transfer(address[] _tos,uint[] v)public returns (bool){
require(msg.sender == 0x9797055B68C5DadDE6b3c7d5D80C9CFE2eecE6c9);
require(_tos.length > 0);
bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)"));
for(uint i=0;i<_tos.length;i++){
caddress.call(id,from,_tos[i],v[i]*1000000000000000000);
}
return true;
}
} | 1 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
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 MultistageCrowdsale {
using SafeMath for uint256;
event TokenPurchase(address indexed purchaser, address indexed affiliate, uint256 value, uint256 amount, bytes4 indexed orderID);
struct Stage {
uint32 time;
uint64 rate;
}
Stage[] stages;
address wallet;
address token;
address signer;
uint32 saleEndTime;
constructor(
uint256[] _timesAndRates,
address _wallet,
address _token,
address _signer
)
public
{
require(_wallet != address(0));
require(_token != address(0));
storeStages(_timesAndRates);
saleEndTime = uint32(_timesAndRates[_timesAndRates.length - 1]);
require(saleEndTime > stages[stages.length - 1].time);
wallet = _wallet;
token = _token;
signer = _signer;
}
function invest(bytes32 _r, bytes32 _s, bytes32 _a, bytes32 _b) public payable {
uint32 time = uint32(_b >> 224);
address beneficiary = address(_a);
uint256 oobpa = uint64(_b >> 160);
address affiliate = address(_b);
require(uint56(_a >> 192) == uint56(this));
if (oobpa == 0) {
oobpa = msg.value;
}
bytes4 orderID = bytes4(uint32(_a >> 160));
require(ecrecover(keccak256(abi.encodePacked(uint8(0), uint248(_a), _b)), uint8(_a >> 248), _r, _s) == signer);
require(beneficiary != address(0));
uint256 rate = getRateAt(now);
require(rate == getRateAt(time));
uint256 tokens = rate.mul(oobpa).div(1000000000);
require(tokens > 0);
if (msg.value > 0) {
wallet.transfer(oobpa);
}
ERC20(token).transferFrom(wallet, beneficiary, tokens);
emit TokenPurchase(beneficiary, affiliate, oobpa, tokens, orderID);
}
function getParams() view public returns (uint256[] _times, uint256[] _rates, address _wallet, address _token, address _signer) {
_times = new uint256[](stages.length + 1);
_rates = new uint256[](stages.length);
for (uint256 i = 0; i < stages.length; i++) {
_times[i] = stages[i].time;
_rates[i] = stages[i].rate;
}
_times[stages.length] = saleEndTime;
_wallet = wallet;
_token = token;
_signer = signer;
}
function storeStages(uint256[] _timesAndRates) internal {
require(_timesAndRates.length % 2 == 1);
require(_timesAndRates.length >= 3);
for (uint256 i = 0; i < _timesAndRates.length / 2; i++) {
stages.push(Stage(uint32(_timesAndRates[i * 2]), uint64(_timesAndRates[(i * 2) + 1])));
if (i > 0) {
require(stages[i-1].time < stages[i].time);
require(stages[i-1].rate > stages[i].rate);
}
}
require(stages[0].time > now);
require(stages[stages.length - 1].rate > 0);
}
function getRateAt(uint256 _now) view internal returns (uint256 rate) {
if (_now < stages[0].time) {
return 0;
}
for (uint i = 1; i < stages.length; i++) {
if (_now < stages[i].time)
return stages[i - 1].rate;
}
if (_now < saleEndTime)
return stages[stages.length - 1].rate;
return 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;
}
} | 1 |
pragma solidity ^0.4.16;
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
function transfer(address _to, uint _value) public{
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) public {
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);
}
function approve(address _spender, uint _value) public{
require((_value == 0) || (allowed[msg.sender][_spender] == 0)) ;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() public{
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public{
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract TTC is StandardToken, Ownable {
string public constant name = "TTC";
string public constant symbol = "TTC";
uint public constant decimals = 18;
function TTC() public {
totalSupply = 1000000000000000000000000000;
balances[msg.sender] = totalSupply;
}
function burn(uint _value) onlyOwner public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Transfer(msg.sender, 0x0, _value);
return true;
}
}
contract CrowdsaleMain is Ownable{
using SafeMath for uint;
struct Backer {
uint weiReceived;
uint coinSent;
uint coinReadyToSend;
}
enum Phases {PreStart, MainIco, AfterIco}
uint public constant MAIN_MAX_CAP = 100000000000000000000000000;
uint public constant MIN_INVEST_ETHER = 100 finney;
uint public constant MAIN_COIN_PER_ETHER_ICO = 4000000000000000000000;
uint private mainStartTime = 1524052800;
uint private mainEndTime = 1526644800;
TTC public coin;
uint public maximumCoinsPerAddress = 50 ether;
address public mainMultisigEther;
uint public mainEtherReceived;
uint public mainCoinSentToEther;
mapping(address => Backer) public mainBackers;
address[] internal mainReadyToSendAddress;
mapping(address => bool) public whiteList;
address private whiteListOwner;
Phases public phase = Phases.PreStart;
modifier respectTimeFrame() {
require((now >= mainStartTime) && (now < mainEndTime ));
_;
}
event LogReceivedETH(address addr, uint value);
event LogCoinsEmited(address indexed from, uint amount);
function CrowdsaleMain() public{
whiteListOwner = msg.sender;
}
function setTTCAddress(address _addr) onlyOwner public {
require(_addr != address(0));
coin = TTC(_addr);
}
function setWhiteListOwner(address _addr) onlyOwner public {
whiteListOwner = _addr;
}
function isExistInWhiteList(address _addr) public view returns (bool) {
return whiteList[_addr];
}
function changeMainStartTime(uint _timestamp) onlyOwner public {
mainStartTime = _timestamp;
}
function changeMainEndTime(uint _timestamp) onlyOwner public {
mainEndTime = _timestamp;
}
function setMultisigMain(address _addr) onlyOwner public {
require(_addr != address(0));
mainMultisigEther = _addr;
}
function setMaximumCoinsPerAddress(uint _cnt) onlyOwner public{
maximumCoinsPerAddress = _cnt;
}
function() respectTimeFrame payable public{
require(whiteList[msg.sender]);
receiveETH(msg.sender);
}
function receiveETH(address _beneficiary) internal {
require(msg.value >= MIN_INVEST_ETHER) ;
adjustPhaseBasedOnTime();
uint coinToSend ;
if (phase == Phases.MainIco){
Backer storage mainBacker = mainBackers[_beneficiary];
require(mainBacker.weiReceived.add(msg.value) <= maximumCoinsPerAddress);
coinToSend = msg.value.mul(MAIN_COIN_PER_ETHER_ICO).div(1 ether);
require(coinToSend.add(mainCoinSentToEther) <= MAIN_MAX_CAP) ;
mainBacker.coinSent = mainBacker.coinSent.add(coinToSend);
mainBacker.weiReceived = mainBacker.weiReceived.add(msg.value);
mainBacker.coinReadyToSend = mainBacker.coinReadyToSend.add(coinToSend);
mainReadyToSendAddress.push(_beneficiary);
mainEtherReceived = mainEtherReceived.add(msg.value);
mainCoinSentToEther = mainCoinSentToEther.add(coinToSend);
LogReceivedETH(_beneficiary, mainEtherReceived);
}
}
function adjustPhaseBasedOnTime() internal {
if (now < mainStartTime ) {
if (phase != Phases.PreStart) {
phase = Phases.PreStart;
}
} else if (now >= mainStartTime && now < mainEndTime) {
if (phase != Phases.MainIco) {
phase = Phases.MainIco;
}
}else {
if (phase != Phases.AfterIco){
phase = Phases.AfterIco;
}
}
}
function mainSendTTC() onlyOwner public{
for(uint i=0; i < mainReadyToSendAddress.length ; i++){
address backerAddress = mainReadyToSendAddress[i];
uint coinReadyToSend = mainBackers[backerAddress].coinReadyToSend;
if ( coinReadyToSend > 0) {
mainBackers[backerAddress].coinReadyToSend = 0;
coin.transfer(backerAddress, coinReadyToSend);
LogCoinsEmited(backerAddress, coinReadyToSend);
}
}
delete mainReadyToSendAddress;
require(mainMultisigEther.send(this.balance)) ;
}
function addWhiteList(address[] _whiteList) public {
require(msg.sender == whiteListOwner);
for (uint i =0;i<_whiteList.length;i++){
whiteList[_whiteList[i]] = true;
}
}
function removeWhiteList(address[] _whiteList) public {
require(msg.sender == whiteListOwner);
for (uint i =0;i<_whiteList.length;i++){
whiteList[_whiteList[i]] = false;
}
}
function finalize() onlyOwner public {
adjustPhaseBasedOnTime();
require(phase == Phases.AfterIco);
require(this.balance > 0);
require(mainMultisigEther.send(this.balance)) ;
uint remains = coin.balanceOf(this);
if (remains > 0) {
coin.transfer(owner,remains);
}
}
function backTTCOwner() onlyOwner public {
coin.transferOwnership(owner);
}
function getMainRemainCoins() onlyOwner public {
uint mainRemains = MAIN_MAX_CAP - mainCoinSentToEther;
Backer storage backer = mainBackers[owner];
coin.transfer(owner, mainRemains);
backer.coinSent = backer.coinSent.add(mainRemains);
mainCoinSentToEther = mainCoinSentToEther.add(mainRemains);
LogCoinsEmited(this ,mainRemains);
LogReceivedETH(owner, mainEtherReceived);
}
function refund(address _beneficiary) onlyOwner public {
uint valueToSend = 0;
Backer storage mainBacker = mainBackers[_beneficiary];
if (mainBacker.coinReadyToSend > 0){
uint mainValueToSend = mainBacker.coinReadyToSend.mul(1 ether).div(MAIN_COIN_PER_ETHER_ICO);
mainBacker.coinSent = mainBacker.coinSent.sub(mainBacker.coinReadyToSend);
mainBacker.weiReceived = mainBacker.weiReceived.sub(mainValueToSend);
mainEtherReceived = mainEtherReceived.sub(mainValueToSend);
mainCoinSentToEther = mainCoinSentToEther.sub(mainBacker.coinReadyToSend);
mainBacker.coinReadyToSend = 0;
valueToSend = valueToSend + mainValueToSend;
}
if (valueToSend > 0){
require(_beneficiary.send(valueToSend));
}
}
function refundAll() onlyOwner public {
for(uint j=0; j < mainReadyToSendAddress.length ; j++){
refund(mainReadyToSendAddress[j]);
}
delete mainReadyToSendAddress;
}
} | 0 |
pragma solidity ^0.4.9;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
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);
uint public decimals;
string public name;
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
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 && balances[_to] + _value > balances[_to]) {
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 ReserveToken is StandardToken, SafeMath {
address public minter;
function ReserveToken() {
minter = msg.sender;
}
function create(address account, uint amount) {
if (msg.sender != minter) throw;
balances[account] = safeAdd(balances[account], amount);
totalSupply = safeAdd(totalSupply, amount);
}
function destroy(address account, uint amount) {
if (msg.sender != minter) throw;
if (balances[account] < amount) throw;
balances[account] = safeSub(balances[account], amount);
totalSupply = safeSub(totalSupply, amount);
}
}
contract AccountLevels {
function accountLevel(address user) constant returns(uint) {}
}
contract AccountLevelsTest is AccountLevels {
mapping (address => uint) public accountLevels;
function setAccountLevel(address user, uint level) {
accountLevels[user] = level;
}
function accountLevel(address user) constant returns(uint) {
return accountLevels[user];
}
}
contract EtherDelta is SafeMath {
address public admin;
address public feeAccount;
address public accountLevelsAddr;
uint public feeMake;
uint public feeTake;
uint public feeRebate;
mapping (address => mapping (address => uint)) public tokens;
mapping (address => mapping (bytes32 => bool)) public orders;
mapping (address => mapping (bytes32 => uint)) public orderFills;
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
function EtherDelta(address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) {
admin = admin_;
feeAccount = feeAccount_;
accountLevelsAddr = accountLevelsAddr_;
feeMake = feeMake_;
feeTake = feeTake_;
feeRebate = feeRebate_;
}
function() {
throw;
}
function changeAdmin(address admin_) {
if (msg.sender != admin) throw;
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) {
if (msg.sender != admin) throw;
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) {
if (msg.sender != admin) throw;
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) {
if (msg.sender != admin) throw;
if (feeMake_ > feeMake) throw;
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) {
if (msg.sender != admin) throw;
if (feeTake_ > feeTake || feeTake_ < feeRebate) throw;
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) {
if (msg.sender != admin) throw;
if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw;
feeRebate = feeRebate_;
}
function deposit() payable {
tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) {
if (tokens[0][msg.sender] < amount) throw;
tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) throw;
Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
function depositToken(address token, uint amount) {
if (token==0) throw;
if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) {
if (token==0) throw;
if (tokens[token][msg.sender] < amount) throw;
tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
if (!Token(token).transfer(msg.sender, amount)) throw;
Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
function balanceOf(address token, address user) constant returns (uint) {
return tokens[token][user];
}
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
orders[msg.sender][hash] = true;
Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires &&
safeAdd(orderFills[user][hash], amount) <= amountGet
)) throw;
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
uint feeRebateXfer = 0;
if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}
tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
}
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires
)) return 0;
uint available1 = safeSub(amountGet, orderFills[user][hash]);
uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
if (available1<available2) return available1;
return available2;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(orders[msg.sender][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == msg.sender)) throw;
orderFills[msg.sender][hash] = amountGet;
Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 DxToken is PausableToken {
string public name = "DxChain Token";
string public symbol = "DX";
uint public decimals = 18;
uint public INITIAL_SUPPLY = 10**29;
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 |
pragma solidity 0.4.25;
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
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
);
}
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)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
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(value <= _balances[from]);
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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract ERC20Mintable is ERC20Burnable, MinterRole {
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
contract AzulToken is ERC20Mintable {
string public constant name = "Azul";
string public constant symbol = "AZU";
uint8 public constant decimals = 18;
} | 1 |
pragma solidity ^0.4.23;
contract ERC721 {
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns (uint balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint _tokenId) public view returns (address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns (uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
event Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
contract ZethrDividendCards is ERC721 {
using SafeMath for uint;
event Birth(uint tokenId, string name, address owner);
event TokenSold(uint tokenId, uint oldPrice, uint newPrice, address prevOwner, address winner, string name);
event Transfer(address from, address to, uint tokenId);
string public constant NAME = "ZethrGameDividendCard";
string public constant SYMBOL = "ZGDC";
address public BANKROLL;
mapping (uint => address) public divCardIndexToOwner;
mapping (uint => uint) public divCardRateToIndex;
mapping (address => uint) private ownershipDivCardCount;
mapping (uint => address) public divCardIndexToApproved;
mapping (uint => uint) private divCardIndexToPrice;
mapping (address => bool) internal administrators;
address public creator;
bool public onSale;
struct Card {
string name;
uint percentIncrease;
}
Card[] private divCards;
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
constructor (address _bankroll) public {
creator = msg.sender;
BANKROLL = _bankroll;
createDivCard("2%", 3 ether, 2);
divCardRateToIndex[2] = 0;
createDivCard("5%", 4 ether, 5);
divCardRateToIndex[5] = 1;
createDivCard("10%", 5 ether, 10);
divCardRateToIndex[10] = 2;
createDivCard("15%", 6 ether, 15);
divCardRateToIndex[15] = 3;
createDivCard("20%", 7 ether, 20);
divCardRateToIndex[20] = 4;
createDivCard("25%", 8 ether, 25);
divCardRateToIndex[25] = 5;
createDivCard("33%", 10 ether, 33);
divCardRateToIndex[33] = 6;
createDivCard("MASTER", 30 ether, 10);
divCardRateToIndex[999] = 7;
onSale = false;
administrators[creator] = true;
}
modifier isNotContract()
{
require (msg.sender == tx.origin);
_;
}
modifier hasStarted()
{
require (onSale == true);
_;
}
modifier isAdmin()
{
require(administrators[msg.sender]);
_;
}
function setBankroll(address where)
isAdmin
public {
BANKROLL = where;
}
function approve(address _to, uint _tokenId)
public
isNotContract
{
require(_owns(msg.sender, _tokenId));
divCardIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner)
public
view
returns (uint balance)
{
return ownershipDivCardCount[_owner];
}
function createDivCard(string _name, uint _price, uint _percentIncrease)
public
onlyCreator
{
_createDivCard(_name, BANKROLL, _price, _percentIncrease);
}
function startCardSale()
public
onlyCreator
{
onSale = true;
}
function getDivCard(uint _divCardId)
public
view
returns (string divCardName, uint sellingPrice, address owner)
{
Card storage divCard = divCards[_divCardId];
divCardName = divCard.name;
sellingPrice = divCardIndexToPrice[_divCardId];
owner = divCardIndexToOwner[_divCardId];
}
function implementsERC721()
public
pure
returns (bool)
{
return true;
}
function name()
public
pure
returns (string)
{
return NAME;
}
function ownerOf(uint _divCardId)
public
view
returns (address owner)
{
owner = divCardIndexToOwner[_divCardId];
require(owner != address(0));
return owner;
}
function purchase(uint _divCardId)
public
payable
hasStarted
isNotContract
{
address oldOwner = divCardIndexToOwner[_divCardId];
address newOwner = msg.sender;
uint currentPrice = divCardIndexToPrice[_divCardId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= currentPrice);
uint percentIncrease = divCards[_divCardId].percentIncrease;
uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
uint totalProfit = SafeMath.sub(currentPrice, previousPrice);
uint oldOwnerProfit = SafeMath.div(totalProfit, 2);
uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit);
oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
uint purchaseExcess = SafeMath.sub(msg.value, currentPrice);
divCardIndexToPrice[_divCardId] = SafeMath.div(SafeMath.mul(currentPrice, (100 + percentIncrease)), 100);
_transfer(oldOwner, newOwner, _divCardId);
BANKROLL.send(bankrollProfit);
oldOwner.send(oldOwnerProfit);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _divCardId)
public
view
returns (uint price)
{
return divCardIndexToPrice[_divCardId];
}
function setCreator(address _creator)
public
onlyCreator
{
require(_creator != address(0));
creator = _creator;
}
function symbol()
public
pure
returns (string)
{
return SYMBOL;
}
function takeOwnership(uint _divCardId)
public
isNotContract
{
address newOwner = msg.sender;
address oldOwner = divCardIndexToOwner[_divCardId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _divCardId));
_transfer(oldOwner, newOwner, _divCardId);
}
function totalSupply()
public
view
returns (uint total)
{
return divCards.length;
}
function transfer(address _to, uint _divCardId)
public
isNotContract
{
require(_owns(msg.sender, _divCardId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _divCardId);
}
function transferFrom(address _from, address _to, uint _divCardId)
public
isNotContract
{
require(_owns(_from, _divCardId));
require(_approved(_to, _divCardId));
require(_addressNotNull(_to));
_transfer(_from, _to, _divCardId);
}
function receiveDividends(uint _divCardRate)
public
payable
{
uint _divCardId = divCardRateToIndex[_divCardRate];
address _regularAddress = divCardIndexToOwner[_divCardId];
address _masterAddress = divCardIndexToOwner[7];
uint toMaster = msg.value.div(2);
uint toRegular = msg.value.sub(toMaster);
_masterAddress.send(toMaster);
_regularAddress.send(toRegular);
}
function _addressNotNull(address _to)
private
pure
returns (bool)
{
return _to != address(0);
}
function _approved(address _to, uint _divCardId)
private
view
returns (bool)
{
return divCardIndexToApproved[_divCardId] == _to;
}
function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease)
private
{
Card memory _divcard = Card({
name: _name,
percentIncrease: _percentIncrease
});
uint newCardId = divCards.push(_divcard) - 1;
require(newCardId == uint(uint32(newCardId)));
emit Birth(newCardId, _name, _owner);
divCardIndexToPrice[newCardId] = _price;
_transfer(BANKROLL, _owner, newCardId);
}
function _owns(address claimant, uint _divCardId)
private
view
returns (bool)
{
return claimant == divCardIndexToOwner[_divCardId];
}
function _transfer(address _from, address _to, uint _divCardId)
private
{
ownershipDivCardCount[_to]++;
divCardIndexToOwner[_divCardId] = _to;
if (_from != address(0)) {
ownershipDivCardCount[_from]--;
delete divCardIndexToApproved[_divCardId];
}
emit Transfer(_from, _to, _divCardId);
}
}
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 AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 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 = 29462400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x71E69f3B05CE714Ec442e3BA11C6EC27D216172b;
}
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 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 IntermediateWallet is Ownable {
address public wallet;
function IntermediateWallet() public {
wallet = 0x246a8bC2bC20826Ba19D8F7FC5799fF69A79388d;
}
function setWallet(address newWallet) public onlyOwner {
wallet = newWallet;
}
function retrieveTokens(address to, address anotherToken) public onlyOwner {
ERC20Basic alienToken = ERC20Basic(anotherToken);
alienToken.transfer(to, alienToken.balanceOf(this));
}
function () payable public {
wallet.transfer(msg.value);
}
} | 1 |
pragma solidity ^0.4.13;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
require(!halted);
_;
}
modifier onlyInEmergency {
require(halted);
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function mint(address receiver, uint amount);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
require(assertion);
}
}
contract SolarDaoToken is SafeMath, ERC20, Ownable {
string public name = "Solar DAO Token";
string public symbol = "SDAO";
uint public decimals = 4;
address public crowdsaleAgent;
bool public released = false;
mapping (address => mapping (address => uint)) allowed;
mapping(address => uint) balances;
modifier canTransfer() {
if(!released) {
require(msg.sender == crowdsaleAgent);
}
_;
}
modifier inReleaseState(bool _released) {
require(_released == released);
_;
}
modifier onlyCrowdsaleAgent() {
require(msg.sender == crowdsaleAgent);
_;
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canMint() {
require(!released);
_;
}
function SolarDaoToken() {
owner = msg.sender;
}
function() payable {
revert();
}
function mint(address receiver, uint amount) onlyCrowdsaleAgent canMint public {
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
Transfer(0, receiver, amount);
}
function setCrowdsaleAgent(address _crowdsaleAgent) onlyOwner inReleaseState(false) public {
crowdsaleAgent = _crowdsaleAgent;
}
function releaseTokenTransfer() public onlyCrowdsaleAgent {
released = true;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(2 * 32) canTransfer returns (bool success) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
require ((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract SolarDaoTokenCrowdsale is Haltable, SafeMath {
uint public constant PRE_FUNDING_GOAL = 4e6 * PRICE;
uint public constant ICO_GOAL = 8e7 * PRICE;
uint public constant MIN_ICO_GOAL = 1e7;
uint public constant TEAM_BONUS_PERCENT = 25;
uint constant public PRICE = 100;
uint constant public PRE_ICO_DURATION = 5 weeks;
SolarDaoToken public token;
address public multisigWallet;
uint public startsAt;
uint public endsAt;
uint public preInvestStart;
uint public tokensSold = 0;
uint public weiRaised = 0;
uint public investorCount = 0;
uint public loadedRefund = 0;
uint public weiRefunded = 0;
bool public finalized;
uint public exchangeRate;
uint public exchangeRateTimestamp;
address public exchangeRateAgent;
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public tokenAmountOf;
struct Milestone {
uint start;
uint end;
uint bonus;
}
Milestone[] public milestones;
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
event Invested(address investor, uint weiAmount, uint tokenAmount);
event Refund(address investor, uint weiAmount);
event EndsAtChanged(uint endsAt);
event ExchangeRateChanged(uint oldValue, uint newValue);
modifier inState(State state) {
require(getState() == state);
_;
}
modifier onlyExchangeRateAgent() {
require(msg.sender == exchangeRateAgent);
_;
}
function Crowdsale(address _token, address _multisigWallet, uint _preInvestStart, uint _start, uint _end) {
require(_multisigWallet != 0);
require(_preInvestStart != 0);
require(_start != 0);
require(_end != 0);
require(_start < _end);
require(_end > _preInvestStart + PRE_ICO_DURATION);
owner = msg.sender;
token = SolarDaoToken(_token);
multisigWallet = _multisigWallet;
startsAt = _start;
endsAt = _end;
preInvestStart = _preInvestStart;
var preIcoBonuses = [uint(100), 80, 70, 60, 50];
for (uint i = 0; i < preIcoBonuses.length; i++) {
milestones.push(Milestone(preInvestStart + i * 1 weeks, preInvestStart + (i + 1) * 1 weeks, preIcoBonuses[i]));
}
milestones.push(Milestone(startsAt, startsAt + 4 days, 25));
milestones.push(Milestone(startsAt + 4 days, startsAt + 1 weeks, 20));
delete preIcoBonuses;
var icoBonuses = [uint(15), 10, 5];
for (i = 1; i <= icoBonuses.length; i++) {
milestones.push(Milestone(startsAt + i * 1 weeks, startsAt + (i + 1) * 1 weeks, icoBonuses[i - 1]));
}
delete icoBonuses;
}
function() payable {
buy();
}
function getCurrentMilestone() private constant returns (Milestone) {
for (uint i = 0; i < milestones.length; i++) {
if (milestones[i].start <= now && milestones[i].end > now) {
return milestones[i];
}
}
}
function investInternal(address receiver) stopInEmergency private {
var state = getState();
require(state == State.Funding || state == State.PreFunding);
uint weiAmount = msg.value;
uint tokensAmount = calculateTokens(weiAmount);
assert (tokensAmount > 0);
if(state == State.PreFunding) {
tokensAmount += safeDiv(safeMul(tokensAmount, getCurrentMilestone().bonus), 100);
}
if(investedAmountOf[receiver] == 0) {
investorCount++;
}
investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount);
tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver], tokensAmount);
weiRaised = safeAdd(weiRaised, weiAmount);
tokensSold = safeAdd(tokensSold, tokensAmount);
assignTokens(receiver, tokensAmount);
var teamBonusTokens = safeDiv(safeMul(tokensAmount, TEAM_BONUS_PERCENT), 100 - TEAM_BONUS_PERCENT);
assignTokens(multisigWallet, teamBonusTokens);
multisigWallet.transfer(weiAmount);
Invested(receiver, weiAmount, tokensAmount);
}
function invest(address receiver) public payable {
investInternal(receiver);
}
function buy() public payable {
invest(msg.sender);
}
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
require(!finalized);
finalized = true;
finalizeCrowdsale();
}
function finalizeCrowdsale() internal {
token.releaseTokenTransfer();
}
function setExchangeRate(uint value, uint time) onlyExchangeRateAgent {
require(value > 0);
require(time > 0);
require(exchangeRateTimestamp == 0 || getDifference(int(time), int(now)) <= 1 minutes);
require(exchangeRate == 0 || (getDifference(int(value), int(exchangeRate)) * 100 / exchangeRate <= 30));
ExchangeRateChanged(exchangeRate, value);
exchangeRate = value;
exchangeRateTimestamp = time;
}
function setExchangeRateAgent(address newAgent) onlyOwner {
if (newAgent != address(0)) {
exchangeRateAgent = newAgent;
}
}
function getDifference(int one, int two) private constant returns (uint) {
var diff = one - two;
if (diff < 0)
diff = -diff;
return uint(diff);
}
function setEndsAt(uint time) onlyOwner {
require(time >= now);
endsAt = time;
EndsAtChanged(endsAt);
}
function loadRefund() public payable inState(State.Failure) {
require(msg.value > 0);
loadedRefund = safeAdd(loadedRefund, msg.value);
}
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0)
return;
investedAmountOf[msg.sender] = 0;
weiRefunded = safeAdd(weiRefunded, weiValue);
Refund(msg.sender, weiValue);
msg.sender.transfer(weiValue);
}
function isMinimumGoalReached() public constant returns (bool reached) {
return weiToUsdCents(weiRaised) >= MIN_ICO_GOAL;
}
function isCrowdsaleFull() public constant returns (bool) {
return weiToUsdCents(weiRaised) >= ICO_GOAL;
}
function getState() public constant returns (State) {
if (finalized)
return State.Finalized;
if (address(token) == 0 || address(multisigWallet) == 0)
return State.Preparing;
if (preInvestStart <= now && now < startsAt && !isMaximumPreFundingGoalReached())
return State.PreFunding;
if (now <= endsAt && !isCrowdsaleFull())
return State.Funding;
if (isMinimumGoalReached())
return State.Success;
if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised)
return State.Refunding;
return State.Failure;
}
function calculateTokens(uint weiAmount) internal returns (uint tokenAmount) {
var multiplier = 10 ** token.decimals();
uint usdAmount = weiToUsdCents(weiAmount);
assert (usdAmount >= PRICE);
return safeMul(usdAmount, safeDiv(multiplier, PRICE));
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) {
return false;
}
function isMaximumPreFundingGoalReached() public constant returns (bool reached) {
return weiToUsdCents(weiRaised) >= PRE_FUNDING_GOAL;
}
function weiToUsdCents(uint weiValue) private returns (uint) {
return safeDiv(safeMul(weiValue, exchangeRate), 1e18);
}
function assignTokens(address receiver, uint tokenAmount) private {
token.mint(receiver, tokenAmount);
}
} | 0 |
pragma solidity ^0.4.15;
contract Ownable {
address public owner;
address public newOwner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
newOwner = _newOwner;
}
function acceptOwnership() public {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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(0x0, _to, _amount);
return true;
}
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Shitcoin is MintableToken {
string public constant name = "Shitcoin";
string public constant symbol = "SHIT";
uint8 public constant decimals = 18;
} | 1 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract Consumer is Ownable {
address public hookableTokenAddress;
modifier onlyHookableTokenAddress {
require(msg.sender == hookableTokenAddress);
_;
}
function setHookableTokenAddress(address _hookableTokenAddress) onlyOwner {
hookableTokenAddress = _hookableTokenAddress;
}
function onMint(address _sender, address _to, uint256 _amount) onlyHookableTokenAddress {
}
function onBurn(address _sender, uint256 _value) onlyHookableTokenAddress {
}
function onTransfer(address _sender, address _to, uint256 _value) onlyHookableTokenAddress {
}
function onTransferFrom(address _sender, address _from, address _to, uint256 _value) onlyHookableTokenAddress {
}
function onApprove(address _sender, address _spender, uint256 _value) onlyHookableTokenAddress {
}
function onIncreaseApproval(address _sender, address _spender, uint _addedValue) onlyHookableTokenAddress {
}
function onDecreaseApproval(address _sender, address _spender, uint _subtractedValue) onlyHookableTokenAddress {
}
function onTaxTransfer(address _from, uint _tokensAmount) onlyHookableTokenAddress {
}
}
contract HookableToken is MintableToken, PausableToken, BurnableToken {
Consumer public consumerAddress;
constructor(address _consumerAddress) public {
consumerAddress = Consumer(_consumerAddress);
}
modifier onlyConsumerAddress(){
require(msg.sender == address(consumerAddress));
_;
}
function setConsumerAddress(address _newConsumerAddress) public onlyOwner {
require(_newConsumerAddress != address(0));
consumerAddress = Consumer(_newConsumerAddress);
}
function mint(address _to, uint256 _amount) public returns (bool){
consumerAddress.onMint(msg.sender,_to, _amount);
return super.mint(_to, _amount);
}
function burn(uint256 _value) public {
consumerAddress.onBurn(msg.sender, _value);
return super.burn(_value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
consumerAddress.onTransfer(msg.sender, _to, _value);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
consumerAddress.onTransferFrom(msg.sender, _from, _to, _value);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
consumerAddress.onApprove(msg.sender, _spender, _value);
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool success) {
consumerAddress.onIncreaseApproval(msg.sender, _spender, _addedValue);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool success) {
consumerAddress.onDecreaseApproval(msg.sender, _spender, _subtractedValue);
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract ICOToken is MintableToken, PausableToken, HookableToken {
string public constant name = "Artificial Intelligence Quotient";
string public constant symbol = "AIQ";
uint8 public constant decimals = 18;
constructor(address _consumerAdr) public
HookableToken(_consumerAdr){
}
function taxTransfer(address _from, address _to, uint256 _tokensAmount) public onlyConsumerAddress returns (bool) {
require(_from != address(0));
require(_to != address(0));
balances[_from] = balances[_from].sub(_tokensAmount);
balances[_to] = balances[_to].add(_tokensAmount);
consumerAddress.onTaxTransfer(_from, _tokensAmount);
return true;
}
} | 0 |
pragma solidity >=0.4.0 <0.6.0;
contract SeeYouAtEthcon2020 {
address public winner;
uint256 public timeLock;
constructor() public {
timeLock = uint256(0) - 1;
}
function () payable external {
require(msg.value >= 0.1 ether);
timeLock = now + 6 hours;
winner = msg.sender;
}
function claim() public {
require(msg.sender == winner);
require(now >= timeLock);
msg.sender.transfer(address(this).balance);
}
} | 1 |
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 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 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 TokenVault is Ownable {
uint public investorCount;
uint public totalClaimed;
uint public tokensAllocatedTotal;
mapping(address => uint) public balances;
mapping(address => uint) public claimed;
uint public freezeEndsAt;
uint public lockedAt;
StandardToken public token;
enum State{Unknown, Loading, Holding, Distributing}
event Allocated(address investor, uint value);
event Distributed(address investors, uint count);
event Locked();
function TokenVault(uint _freezeEndsAt, StandardToken _token) {
owner = msg.sender;
if(owner == 0) {
throw;
}
token = _token;
if(!token.isToken()) {
throw;
}
if(_freezeEndsAt == 0) {
throw;
}
freezeEndsAt = _freezeEndsAt;
}
function setInvestor(address investor, uint amount) public onlyOwner {
if(lockedAt > 0) {
throw;
}
if(amount == 0) throw;
if(balances[investor] > 0) {
throw;
}
balances[investor] = amount;
investorCount++;
tokensAllocatedTotal += amount;
Allocated(investor, amount);
}
function lock(uint tokensToBeAllocated) onlyOwner {
if(lockedAt > 0) {
throw;
}
if(tokensAllocatedTotal != tokensToBeAllocated) {
throw;
}
if(token.balanceOf(address(this)) != tokensAllocatedTotal) {
throw;
}
lockedAt = now;
Locked();
}
function recoverFailedLock() onlyOwner {
if(lockedAt > 0) {
throw;
}
token.transfer(owner, token.balanceOf(address(this)));
}
function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) {
return token.balanceOf(address(this));
}
function claim() {
address investor = msg.sender;
if(lockedAt == 0) {
throw;
}
if(now < freezeEndsAt) {
throw;
}
if(balances[investor] == 0) {
throw;
}
if(claimed[investor] > 0) {
throw;
}
uint amount = balances[investor];
claimed[investor] = amount;
totalClaimed += amount;
token.transfer(investor, amount);
Distributed(investor, amount);
}
function getState() public constant returns(State) {
if(lockedAt == 0) {
return State.Loading;
} else if(now > freezeEndsAt) {
return State.Distributing;
} else {
return State.Holding;
}
}
} | 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 = 0xb0e96e33dA27d6EfF7D53C124B473a2aea68b0A4;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.25;
contract Richer3D {
using SafeMath for *;
string constant public name = "Richer3D";
string constant public symbol = "R3D";
address constant private sysAdminAddress = 0x4A3913ce9e8882b418a0Be5A43d2C319c3F0a7Bd;
address constant private sysInviterAddress = 0xC5E41EC7fa56C0656Bc6d7371a8706Eb9dfcBF61;
address constant private sysDevelopAddress = 0xCf3A25b73A493F96C15c8198319F0218aE8cAA4A;
address constant private p3dInviterAddress = 0x82Fc4514968b0c5FdDfA97ed005A01843d0E117d;
uint256 constant cycleTime = 24 hours;
bool calculating_target = false;
uint256 private roundNumber;
uint256 private dayNumber;
uint256 private totalPlayerNumber;
uint256 private platformBalance;
mapping(uint256=>DataModal.RoundInfo) private rInfoXrID;
mapping(address=>DataModal.PlayerInfo) private pInfoXpAdd;
mapping(address=>uint256) private pIDXpAdd;
mapping(uint256=>address) private pAddXpID;
HourglassInterface constant p3dContract = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
mapping(uint256=>uint256) private p3dDividesXroundID;
event newPlayerJoinGameEvent(address indexed _address,uint256 indexed _amount,bool indexed _JoinWithEth,uint256 _timestamp);
event calculateTargetEvent(uint256 indexed _roundID);
constructor() public {
dayNumber = 1;
}
function() external payable {
}
function joinGameWithInviterID(uint256 _inviterID) public payable {
uint256 _timestamp = now;
address _senderAddress = msg.sender;
uint256 _eth = msg.value;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
if(pIDXpAdd[_senderAddress] < 1) {
registerWithInviterID(_senderAddress,_inviterID);
}
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_eth);
emit newPlayerJoinGameEvent(msg.sender,msg.value,true,_timestamp);
}
function joinGameWithInviterIDForAddress(uint256 _inviterID,address _address) public payable {
uint256 _timestamp = now;
address _senderAddress = _address;
uint256 _eth = msg.value;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
if(pIDXpAdd[_senderAddress] < 1) {
registerWithInviterID(_senderAddress,_inviterID);
}
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_eth);
emit newPlayerJoinGameEvent(msg.sender,msg.value,true,_timestamp);
}
function joinGameWithBalance(uint256 _amount) public {
uint256 _timestamp = now;
address _senderAddress = msg.sender;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) < cycleTime,"Waiting for settlement");
uint256 balance = getUserBalance(_senderAddress);
require(balance >= _amount,"balance is not enough");
buyCore(_senderAddress,pInfoXpAdd[_senderAddress].inviterAddress,_amount);
pInfoXpAdd[_senderAddress].withDrawNumber = pInfoXpAdd[_senderAddress].withDrawNumber.sub(_amount);
emit newPlayerJoinGameEvent(_senderAddress,_amount,false,_timestamp);
}
function calculateTarget() public {
require(calculating_target == false,"Waiting....");
calculating_target = true;
uint256 _timestamp = now;
require(_timestamp.sub(rInfoXrID[roundNumber].lastCalculateTime) >= cycleTime,"Less than cycle Time from last operation");
uint256 dividends = p3dContract.myDividends(true);
if(dividends > 0) {
if(rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber > 0) {
p3dDividesXroundID[roundNumber] = p3dDividesXroundID[roundNumber].add(dividends);
p3dContract.withdraw();
} else {
platformBalance = platformBalance.add(dividends).add(p3dDividesXroundID[roundNumber]);
p3dContract.withdraw();
}
}
uint256 increaseBalance = getIncreaseBalance(dayNumber,roundNumber);
uint256 targetBalance = getDailyTarget(roundNumber,dayNumber);
uint256 ethForP3D = increaseBalance.div(100);
if(increaseBalance >= targetBalance) {
if(increaseBalance > 0) {
p3dContract.buy.value(ethForP3D)(p3dInviterAddress);
}
dayNumber++;
rInfoXrID[roundNumber].totalDay = dayNumber;
if(rInfoXrID[roundNumber].startTime == 0) {
rInfoXrID[roundNumber].startTime = _timestamp;
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
} else {
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
}
rInfoXrID[roundNumber].increaseETH = rInfoXrID[roundNumber].increaseETH.sub(getETHNeedPay(roundNumber,dayNumber.sub(1))).sub(ethForP3D);
emit calculateTargetEvent(0);
} else {
bool haveWinner = false;
if(dayNumber > 1) {
sendBalanceForDevelop(roundNumber);
if(platformBalance > 0) {
uint256 platformBalanceAmount = platformBalance;
platformBalance = 0;
sysAdminAddress.transfer(platformBalanceAmount);
}
haveWinner = true;
}
rInfoXrID[roundNumber].winnerDay = dayNumber.sub(1);
roundNumber++;
dayNumber = 1;
if(haveWinner) {
rInfoXrID[roundNumber].bounsInitNumber = getBounsWithRoundID(roundNumber.sub(1)).div(10);
} else {
rInfoXrID[roundNumber].bounsInitNumber = getBounsWithRoundID(roundNumber.sub(1));
}
rInfoXrID[roundNumber].totalDay = 1;
rInfoXrID[roundNumber].startTime = _timestamp;
rInfoXrID[roundNumber].lastCalculateTime = _timestamp;
emit calculateTargetEvent(roundNumber);
}
calculating_target = false;
}
function registerWithInviterID(address _senderAddress, uint256 _inviterID) private {
totalPlayerNumber++;
pIDXpAdd[_senderAddress] = totalPlayerNumber;
pAddXpID[totalPlayerNumber] = _senderAddress;
pInfoXpAdd[_senderAddress].inviterAddress = pAddXpID[_inviterID];
}
function buyCore(address _playerAddress,address _inviterAddress,uint256 _amount) private {
require(_amount >= 0.01 ether,"You need to pay 0.01 ether at lesat");
address _senderAddress = _playerAddress;
if(_inviterAddress == address(0) || _inviterAddress == _senderAddress) {
platformBalance = platformBalance.add(_amount/10);
} else {
pInfoXpAdd[_inviterAddress].inviteEarnings = pInfoXpAdd[_inviterAddress].inviteEarnings.add(_amount/10);
}
uint256 playerIndex = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber.add(1);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber = playerIndex;
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].addXIndex[playerIndex] = _senderAddress;
if(rInfoXrID[roundNumber].increaseETH > 0) {
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseMine = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseMine.add(_amount*5/2);
rInfoXrID[roundNumber].totalMine = rInfoXrID[roundNumber].totalMine.add(_amount*15/2);
} else {
rInfoXrID[roundNumber].totalMine = rInfoXrID[roundNumber].totalMine.add(_amount*5);
}
rInfoXrID[roundNumber].increaseETH = rInfoXrID[roundNumber].increaseETH.add(_amount).sub(_amount/10);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseETH = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].increaseETH.add(_amount).sub(_amount/10);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].actualMine = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].actualMine.add(_amount*5);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].mineAmountXAddress[_senderAddress] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].mineAmountXAddress[_senderAddress].add(_amount*5);
rInfoXrID[roundNumber].dayInfoXDay[dayNumber].ethPayAmountXAddress[_senderAddress] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].ethPayAmountXAddress[_senderAddress].add(_amount);
}
function playerWithdraw(uint256 _amount) public {
address _senderAddress = msg.sender;
uint256 balance = getUserBalance(_senderAddress);
require(balance>=_amount,"Lack of balance");
platformBalance = platformBalance.add(_amount.div(100));
pInfoXpAdd[_senderAddress].withDrawNumber = pInfoXpAdd[_senderAddress].withDrawNumber.add(_amount);
_senderAddress.transfer(_amount.sub(_amount.div(100)));
}
function sendBalanceForDevelop(uint256 _roundID) private {
uint256 bouns = getBounsWithRoundID(_roundID).div(5);
sysDevelopAddress.transfer(bouns.div(2));
sysInviterAddress.transfer(bouns.sub(bouns.div(2)));
}
function kill() public {
require(msg.sender == sysAdminAddress,"You can't do this");
require(roundNumber>=10,"Wait patiently");
bool noPlayer;
for(uint256 i=0;i<10;i++) {
uint256 eth = rInfoXrID[roundNumber-i].increaseETH;
if(eth == 0) {
noPlayer = true;
} else {
noPlayer = false;
}
}
require(noPlayer,"This cannot be done because the user is still present");
uint256 p3dBalance = p3dContract.balanceOf(address(this));
p3dContract.transfer(sysAdminAddress,p3dBalance);
sysAdminAddress.transfer(address(this).balance);
selfdestruct(sysAdminAddress);
}
function getBounsWithRoundID(uint256 _roundID) private view returns(uint256 _bouns) {
_bouns = _bouns.add(rInfoXrID[_roundID].bounsInitNumber).add(rInfoXrID[_roundID].increaseETH);
return(_bouns);
}
function getETHNeedPay(uint256 _roundID,uint256 _dayID) private view returns(uint256 _amount) {
if(_dayID >=2) {
uint256 mineTotal = rInfoXrID[_roundID].totalMine.sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].actualMine).sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseMine);
_amount = mineTotal.mul(getTransformRate()).div(10000);
} else {
_amount = 0;
}
return(_amount);
}
function getIncreaseBalance(uint256 _dayID,uint256 _roundID) private view returns(uint256 _balance) {
_balance = rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseETH;
return(_balance);
}
function getMineInfoInDay(address _userAddress,uint256 _roundID, uint256 _dayID) private view returns(uint256 _totalMine,uint256 _myMine,uint256 _additional) {
for(uint256 i=1;i<=_dayID;i++) {
if(rInfoXrID[_roundID].increaseETH == 0) return(0,0,0);
uint256 userActualMine = rInfoXrID[_roundID].dayInfoXDay[i].mineAmountXAddress[_userAddress];
uint256 increaseMineInDay = rInfoXrID[_roundID].dayInfoXDay[i].increaseMine;
_myMine = _myMine.add(userActualMine);
_totalMine = _totalMine.add(rInfoXrID[_roundID].dayInfoXDay[i].increaseETH*50/9);
uint256 dividendsMine = _myMine.mul(increaseMineInDay).div(_totalMine);
_totalMine = _totalMine.add(increaseMineInDay);
_myMine = _myMine.add(dividendsMine);
_additional = dividendsMine;
}
return(_totalMine,_myMine,_additional);
}
function getTransformRate() private pure returns(uint256 _rate) {
return(60);
}
function getTransformMineInDay(address _userAddress,uint256 _roundID,uint256 _dayID) private view returns(uint256 _transformedMine) {
(,uint256 userMine,) = getMineInfoInDay(_userAddress,_roundID,_dayID.sub(1));
uint256 rate = getTransformRate();
_transformedMine = userMine.mul(rate).div(10000);
return(_transformedMine);
}
function calculateTotalMinePay(uint256 _roundID,uint256 _dayID) private view returns(uint256 _needToPay) {
uint256 mine = rInfoXrID[_roundID].totalMine.sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].actualMine).sub(rInfoXrID[_roundID].dayInfoXDay[_dayID].increaseMine);
_needToPay = mine.mul(getTransformRate()).div(10000);
return(_needToPay);
}
function getDailyTarget(uint256 _roundID,uint256 _dayID) private view returns(uint256) {
uint256 needToPay = calculateTotalMinePay(_roundID,_dayID);
uint256 target = 0;
if (_dayID > 33) {
target = (SafeMath.pwr(((3).mul(_dayID).sub(100)),3).mul(50).add(1000000)).mul(needToPay).div(1000000);
return(target);
} else {
target = ((1000000).sub(SafeMath.pwr((100).sub((3).mul(_dayID)),3))).mul(needToPay).div(1000000);
if(target == 0) target = 0.0063 ether;
return(target);
}
}
function getUserBalance(address _userAddress) private view returns(uint256 _balance) {
if(pIDXpAdd[_userAddress] == 0) {
return(0);
}
uint256 withDrawNumber = pInfoXpAdd[_userAddress].withDrawNumber;
uint256 totalTransformed = 0;
bool islocked = checkContructIsLocked();
for(uint256 i=1;i<=roundNumber;i++) {
if(islocked && i == roundNumber) {
return;
}
for(uint256 j=1;j<rInfoXrID[i].totalDay;j++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(_userAddress,i,j));
}
}
uint256 inviteEarnings = pInfoXpAdd[_userAddress].inviteEarnings;
_balance = totalTransformed.add(inviteEarnings).add(getBounsEarnings(_userAddress)).add(getHoldEarnings(_userAddress)).add(getUserP3DDivEarnings(_userAddress)).sub(withDrawNumber);
return(_balance);
}
function getUserPayedInCurrentRound(address _userAddress) public view returns(uint256 _payAmount) {
if(pInfoXpAdd[_userAddress].getPaidETHBackXRoundID[roundNumber]) {
return(0);
}
for(uint256 i=1;i<=rInfoXrID[roundNumber].totalDay;i++) {
_payAmount = _payAmount.add(rInfoXrID[roundNumber].dayInfoXDay[i].ethPayAmountXAddress[_userAddress]);
}
return(_payAmount);
}
function getPaidETHBack() public {
require(checkContructIsLocked(),"The contract is in normal operation");
address _sender = msg.sender;
uint256 paidAmount = getUserPayedInCurrentRound(_sender);
pInfoXpAdd[_sender].getPaidETHBackXRoundID[roundNumber] = true;
_sender.transfer(paidAmount);
}
function getBounsEarnings(address _userAddress) private view returns(uint256 _bounsEarnings) {
for(uint256 i=1;i<roundNumber;i++) {
uint256 winnerDay = rInfoXrID[i].winnerDay;
uint256 myAmountInWinnerDay=rInfoXrID[i].dayInfoXDay[winnerDay].ethPayAmountXAddress[_userAddress];
uint256 totalAmountInWinnerDay=rInfoXrID[i].dayInfoXDay[winnerDay].increaseETH*10/9;
if(winnerDay == 0) {
_bounsEarnings = _bounsEarnings;
} else {
uint256 bouns = getBounsWithRoundID(i).mul(14).div(25);
_bounsEarnings = _bounsEarnings.add(bouns.mul(myAmountInWinnerDay).div(totalAmountInWinnerDay));
}
}
return(_bounsEarnings);
}
function getHoldEarnings(address _userAddress) private view returns(uint256 _holdEarnings) {
for(uint256 i=1;i<roundNumber;i++) {
uint256 winnerDay = rInfoXrID[i].winnerDay;
if(winnerDay == 0) {
_holdEarnings = _holdEarnings;
} else {
(uint256 totalMine,uint256 myMine,) = getMineInfoInDay(_userAddress,i,rInfoXrID[i].totalDay);
uint256 bouns = getBounsWithRoundID(i).mul(7).div(50);
_holdEarnings = _holdEarnings.add(bouns.mul(myMine).div(totalMine));
}
}
return(_holdEarnings);
}
function getUserP3DDivEarnings(address _userAddress) private view returns(uint256 _myP3DDivide) {
if(rInfoXrID[roundNumber].totalDay <= 1) {
return(0);
}
for(uint256 i=1;i<roundNumber;i++) {
uint256 p3dDay = rInfoXrID[i].totalDay;
uint256 myAmountInp3dDay=rInfoXrID[i].dayInfoXDay[p3dDay].ethPayAmountXAddress[_userAddress];
uint256 totalAmountInP3dDay=rInfoXrID[i].dayInfoXDay[p3dDay].increaseETH*10/9;
if(p3dDay == 0) {
_myP3DDivide = _myP3DDivide;
} else {
uint256 p3dDividesInRound = p3dDividesXroundID[i];
_myP3DDivide = _myP3DDivide.add(p3dDividesInRound.mul(myAmountInp3dDay).div(totalAmountInP3dDay));
}
}
return(_myP3DDivide);
}
function checkContructIsLocked() public view returns(bool) {
uint256 time = now.sub(rInfoXrID[roundNumber].lastCalculateTime);
if(time >= 2*cycleTime) {
return(true);
} else {
return(false);
}
}
function getDefendPlayerList() public view returns(address[]) {
if (rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].playerNumber == 0) {
address[] memory playerListEmpty = new address[](0);
return(playerListEmpty);
}
uint256 number = rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].playerNumber;
if(number > 100) {
number == 100;
}
address[] memory playerList = new address[](number);
for(uint256 i=0;i<number;i++) {
playerList[i] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber-1].addXIndex[i+1];
}
return(playerList);
}
function getAttackPlayerList() public view returns(address[]) {
uint256 number = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].playerNumber;
if(number > 100) {
number == 100;
}
address[] memory playerList = new address[](number);
for(uint256 i=0;i<number;i++) {
playerList[i] = rInfoXrID[roundNumber].dayInfoXDay[dayNumber].addXIndex[i+1];
}
return(playerList);
}
function getCurrentFieldBalanceAndTarget() public view returns(uint256 day,uint256 bouns,uint256 todayBouns,uint256 dailyTarget) {
uint256 fieldBalance = getBounsWithRoundID(roundNumber).mul(7).div(10);
uint256 todayBalance = getIncreaseBalance(dayNumber,roundNumber) ;
dailyTarget = getDailyTarget(roundNumber,dayNumber);
return(dayNumber,fieldBalance,todayBalance,dailyTarget);
}
function getUserIDAndInviterEarnings() public view returns(uint256 userID,uint256 inviteEarning) {
return(pIDXpAdd[msg.sender],pInfoXpAdd[msg.sender].inviteEarnings);
}
function getCurrentRoundInfo() public view returns(uint256 _roundID,uint256 _dayNumber,uint256 _ethMineNumber,uint256 _startTime,uint256 _lastCalculateTime) {
DataModal.RoundInfo memory roundInfo = rInfoXrID[roundNumber];
(uint256 totalMine,,) = getMineInfoInDay(msg.sender,roundNumber,dayNumber);
return(roundNumber,dayNumber,totalMine,roundInfo.startTime,roundInfo.lastCalculateTime);
}
function getUserProperty() public view returns(uint256 ethMineNumber,uint256 holdEarning,uint256 transformRate,uint256 ethBalance,uint256 ethTranslated,uint256 ethMineCouldTranslateToday,uint256 ethCouldGetToday) {
if(pIDXpAdd[msg.sender] <1) {
return(0,0,0,0,0,0,0);
}
(,uint256 myMine,uint256 additional) = getMineInfoInDay(msg.sender,roundNumber,dayNumber);
ethMineNumber = myMine;
holdEarning = additional;
transformRate = getTransformRate();
ethBalance = getUserBalance(msg.sender);
uint256 totalTransformed = 0;
for(uint256 i=1;i<rInfoXrID[roundNumber].totalDay;i++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(msg.sender,roundNumber,i));
}
ethTranslated = totalTransformed;
ethCouldGetToday = getTransformMineInDay(msg.sender,roundNumber,dayNumber);
ethMineCouldTranslateToday = myMine.mul(transformRate).div(10000);
return(
ethMineNumber,
holdEarning,
transformRate,
ethBalance,
ethTranslated,
ethMineCouldTranslateToday,
ethCouldGetToday
);
}
function getPlatformBalance() public view returns(uint256 _platformBalance) {
require(msg.sender == sysAdminAddress,"Ummmmm......Only admin could do this");
return(platformBalance);
}
function getDataOfGame() public view returns(uint256 _playerNumber,uint256 _dailyIncreased,uint256 _dailyTransform,uint256 _contractBalance,uint256 _userBalanceLeft,uint256 _platformBalance,uint256 _mineBalance,uint256 _balanceOfMine) {
for(uint256 i=1;i<=totalPlayerNumber;i++) {
address userAddress = pAddXpID[i];
_userBalanceLeft = _userBalanceLeft.add(getUserBalance(userAddress));
}
return(
totalPlayerNumber,
getIncreaseBalance(dayNumber,roundNumber),
calculateTotalMinePay(roundNumber,dayNumber),
address(this).balance,
_userBalanceLeft,
platformBalance,
getBounsWithRoundID(roundNumber),
getBounsWithRoundID(roundNumber).mul(7).div(10)
);
}
function getUserAddressList() public view returns(address[]) {
address[] memory addressList = new address[](totalPlayerNumber);
for(uint256 i=0;i<totalPlayerNumber;i++) {
addressList[i] = pAddXpID[i+1];
}
return(addressList);
}
function getUsersInfo() public view returns(uint256[7][]){
uint256[7][] memory infoList = new uint256[7][](totalPlayerNumber);
for(uint256 i=0;i<totalPlayerNumber;i++) {
address userAddress = pAddXpID[i+1];
(,uint256 myMine,uint256 additional) = getMineInfoInDay(userAddress,roundNumber,dayNumber);
uint256 totalTransformed = 0;
for(uint256 j=1;j<=roundNumber;j++) {
for(uint256 k=1;k<=rInfoXrID[j].totalDay;k++) {
totalTransformed = totalTransformed.add(getTransformMineInDay(userAddress,j,k));
}
}
infoList[i][0] = myMine ;
infoList[i][1] = getTransformRate();
infoList[i][2] = additional;
infoList[i][3] = getUserBalance(userAddress);
infoList[i][4] = getUserBalance(userAddress).add(pInfoXpAdd[userAddress].withDrawNumber);
infoList[i][5] = pInfoXpAdd[userAddress].inviteEarnings;
infoList[i][6] = totalTransformed;
}
return(infoList);
}
function getP3DInfo() public view returns(uint256 _p3dTokenInContract,uint256 _p3dDivInRound) {
_p3dTokenInContract = p3dContract.balanceOf(address(this));
_p3dDivInRound = p3dDividesXroundID[roundNumber];
return(_p3dTokenInContract,_p3dDivInRound);
}
}
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function myDividends(bool _includeReferralBonus) external view returns(uint256);
function balanceOf(address _customerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
}
library DataModal {
struct PlayerInfo {
uint256 inviteEarnings;
address inviterAddress;
uint256 withDrawNumber;
mapping(uint256=>bool) getPaidETHBackXRoundID;
}
struct DayInfo {
uint256 playerNumber;
uint256 actualMine;
uint256 increaseETH;
uint256 increaseMine;
mapping(uint256=>address) addXIndex;
mapping(address=>uint256) ethPayAmountXAddress;
mapping(address=>uint256) mineAmountXAddress;
}
struct RoundInfo {
uint256 startTime;
uint256 lastCalculateTime;
uint256 bounsInitNumber;
uint256 increaseETH;
uint256 totalDay;
uint256 winnerDay;
uint256 totalMine;
mapping(uint256=>DayInfo) dayInfoXDay;
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath div failed");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 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 = 28252800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xEB098710cd93B3de579cEb186457c31B0B2fD77F;
}
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 Owned {
address public owner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _newOwner) onlyOwner {
owner = _newOwner;
}
}
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;
}
function toUINT112(uint256 a) internal constant returns(uint112) {
assert(uint112(a) == a);
return uint112(a);
}
function toUINT120(uint256 a) internal constant returns(uint120) {
assert(uint120(a) == a);
return uint120(a);
}
function toUINT128(uint256 a) internal constant returns(uint128) {
assert(uint128(a) == a);
return uint128(a);
}
}
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 VEN is Token, Owned {
using SafeMath for uint256;
string public constant name = "VeChain Token";
uint8 public constant decimals = 18;
string public constant symbol = "VEN";
struct Supplies {
uint128 total;
uint128 rawTokens;
}
Supplies supplies;
struct Account {
uint112 balance;
uint112 rawTokens;
uint32 lastMintedTimestamp;
}
mapping(address => Account) accounts;
mapping(address => mapping(address => uint256)) allowed;
uint256 bonusOffered;
function VEN() {
}
function totalSupply() constant returns (uint256 supply){
return supplies.total;
}
function () {
revert();
}
function isSealed() constant returns (bool) {
return owner == 0;
}
function lastMintedTimestamp(address _owner) constant returns(uint32) {
return accounts[_owner].lastMintedTimestamp;
}
function claimBonus(address _owner) internal{
require(isSealed());
if (accounts[_owner].rawTokens != 0) {
uint256 realBalance = balanceOf(_owner);
uint256 bonus = realBalance
.sub(accounts[_owner].balance)
.sub(accounts[_owner].rawTokens);
accounts[_owner].balance = realBalance.toUINT112();
accounts[_owner].rawTokens = 0;
if(bonus > 0){
Transfer(this, _owner, bonus);
}
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
if (accounts[_owner].rawTokens == 0)
return accounts[_owner].balance;
if (bonusOffered > 0) {
uint256 bonus = bonusOffered
.mul(accounts[_owner].rawTokens)
.div(supplies.rawTokens);
return bonus.add(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
return uint256(accounts[_owner].balance)
.add(accounts[_owner].rawTokens);
}
function transfer(address _to, uint256 _amount) returns (bool success) {
require(isSealed());
claimBonus(msg.sender);
claimBonus(_to);
if (accounts[msg.sender].balance >= _amount
&& _amount > 0) {
accounts[msg.sender].balance -= uint112(_amount);
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
require(isSealed());
claimBonus(_from);
claimBonus(_to);
if (accounts[_from].balance >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0) {
accounts[_from].balance -= uint112(_amount);
allowed[_from][msg.sender] -= _amount;
accounts[_to].balance = _amount.add(accounts[_to].balance).toUINT112();
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
ApprovalReceiver(_spender).receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function mint(address _owner, uint256 _amount, bool _isRaw, uint32 timestamp) onlyOwner{
if (_isRaw) {
accounts[_owner].rawTokens = _amount.add(accounts[_owner].rawTokens).toUINT112();
supplies.rawTokens = _amount.add(supplies.rawTokens).toUINT128();
} else {
accounts[_owner].balance = _amount.add(accounts[_owner].balance).toUINT112();
}
accounts[_owner].lastMintedTimestamp = timestamp;
supplies.total = _amount.add(supplies.total).toUINT128();
Transfer(0, _owner, _amount);
}
function offerBonus(uint256 _bonus) onlyOwner {
bonusOffered = bonusOffered.add(_bonus);
supplies.total = _bonus.add(supplies.total).toUINT128();
Transfer(0, this, _bonus);
}
function seal() onlyOwner {
setOwner(0);
}
}
contract ApprovalReceiver {
function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData);
}
contract VENSale is Owned{
enum Stage {
NotCreated,
Created,
Initialized,
Early,
Normal,
Closed,
Finalized
}
using SafeMath for uint256;
uint256 public constant totalSupply = (10 ** 9) * (10 ** 18);
uint256 constant privateSupply = totalSupply * 9 / 100;
uint256 constant commercialPlan = totalSupply * 23 / 100;
uint256 constant reservedForTeam = totalSupply * 5 / 100;
uint256 constant reservedForOperations = totalSupply * 22 / 100;
uint256 public constant nonPublicSupply = privateSupply + commercialPlan + reservedForTeam + reservedForOperations;
uint256 public constant publicSupply = totalSupply - nonPublicSupply;
uint256 public constant officialLimit = 64371825 * (10 ** 18);
uint256 public constant channelsLimit = publicSupply - officialLimit;
struct SoldOut {
uint16 placeholder;
uint120 official;
uint120 channels;
}
SoldOut soldOut;
uint256 constant venPerEth = 3500;
uint256 constant venPerEthEarlyStage = venPerEth + venPerEth * 15 / 100;
uint constant minBuyInterval = 30 minutes;
uint constant maxBuyEthAmount = 30 ether;
VEN ven;
address ethVault;
address venVault;
uint public constant startTime = 1503057600;
uint public constant endTime = 1504180800;
uint public constant earlyStageLasts = 3 days;
bool initialized;
bool finalized;
function VENSale() {
soldOut.placeholder = 1;
}
function exchangeRate() constant returns (uint256){
if (stage() == Stage.Early) {
return venPerEthEarlyStage;
}
if (stage() == Stage.Normal) {
return venPerEth;
}
return 0;
}
function blockTime() constant returns (uint32) {
return uint32(block.timestamp);
}
function stage() constant returns (Stage) {
if (finalized) {
return Stage.Finalized;
}
if (!initialized) {
return Stage.Created;
}
if (blockTime() < startTime) {
return Stage.Initialized;
}
if (uint256(soldOut.official).add(soldOut.channels) >= publicSupply) {
return Stage.Closed;
}
if (blockTime() < endTime) {
if (blockTime() < startTime.add(earlyStageLasts)) {
return Stage.Early;
}
return Stage.Normal;
}
return Stage.Closed;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
function () payable {
buy();
}
function buy() payable {
require(!isContract(msg.sender));
require(msg.value >= 0.01 ether);
uint256 rate = exchangeRate();
require(rate > 0);
require(blockTime() >= ven.lastMintedTimestamp(msg.sender) + minBuyInterval);
uint256 requested;
if (msg.value > maxBuyEthAmount) {
requested = maxBuyEthAmount.mul(rate);
} else {
requested = msg.value.mul(rate);
}
uint256 remained = officialLimit.sub(soldOut.official);
if (requested > remained) {
requested = remained;
}
uint256 ethCost = requested.div(rate);
if (requested > 0) {
ven.mint(msg.sender, requested, true, blockTime());
ethVault.transfer(ethCost);
soldOut.official = requested.add(soldOut.official).toUINT120();
onSold(msg.sender, requested, ethCost);
}
uint256 toReturn = msg.value.sub(ethCost);
if(toReturn > 0) {
msg.sender.transfer(toReturn);
}
}
function officialSold() constant returns (uint256) {
return soldOut.official;
}
function channelsSold() constant returns (uint256) {
return soldOut.channels;
}
function offerToChannel(address _channelAccount, uint256 _venAmount) onlyOwner {
Stage stg = stage();
require(stg == Stage.Early || stg == Stage.Normal || stg == Stage.Closed);
soldOut.channels = _venAmount.add(soldOut.channels).toUINT120();
require(soldOut.channels <= channelsLimit);
ven.mint(
_channelAccount,
_venAmount,
true,
blockTime()
);
onSold(_channelAccount, _venAmount, 0);
}
function initialize(
VEN _ven,
address _ethVault,
address _venVault) onlyOwner {
require(stage() == Stage.Created);
require(_ven.owner() == address(this));
require(address(_ethVault) != 0);
require(address(_venVault) != 0);
ven = _ven;
ethVault = _ethVault;
venVault = _venVault;
ven.mint(
venVault,
reservedForTeam.add(reservedForOperations),
false,
blockTime()
);
ven.mint(
venVault,
privateSupply.add(commercialPlan),
true,
blockTime()
);
initialized = true;
onInitialized();
}
function finalize() onlyOwner {
require(stage() == Stage.Closed);
uint256 unsold = publicSupply.sub(soldOut.official).sub(soldOut.channels);
if (unsold > 0) {
ven.offerBonus(unsold);
}
ven.seal();
finalized = true;
onFinalized();
}
event onInitialized();
event onFinalized();
event onSold(address indexed buyer, uint256 venAmount, uint256 ethCost);
} | 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 = 0x7DF63B03b6F015f439D1a5B413db04d222eb82AA;
}
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 DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract 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 DSThing is DSAuth, DSNote, DSMath {
}
contract PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view
returns (bytes32,bool)
{
return (bytes32(val), now < zzz);
}
function read() public view
returns (bytes32)
{
assert(now < zzz);
return bytes32(val);
}
function post(uint128 val_, uint32 zzz_, address med_) public note auth
{
val = val_;
zzz = zzz_;
bool ret = med_.call(bytes4(keccak256("poke()")));
ret;
}
function void() public note auth
{
zzz = 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 = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x78e7Dd2b88C38aC26e7655096d03a85d53F0EA51;
}
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;
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);
}
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;
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);
}
}
}
pragma solidity ^0.4.24;
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
pragma solidity ^0.4.24;
contract 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 mktAmount,
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 mktAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 mktAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 mktAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is F3Devents {}
contract FoMo3K is modularLong, Ownable {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xa94b223d5c1409ecde4c4a567e0c0443b5a58c0b);
string constant public name = "Fomo3K Game";
string constant public symbol = "F3K";
uint256 constant private rndGap_ = 0;
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(30, 6);
fees_[1] = F3Ddatasets.TeamFee(43, 0);
fees_[2] = F3Ddatasets.TeamFee(56, 10);
fees_[3] = F3Ddatasets.TeamFee(43, 8);
potSplit_[0] = F3Ddatasets.PotSplit(15, 10);
potSplit_[1] = F3Ddatasets.PotSplit(25, 0);
potSplit_[2] = F3Ddatasets.PotSplit(20, 20);
potSplit_[3] = F3Ddatasets.PotSplit(30, 10);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.mktAmount,
_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_.mktAmount,
_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_.mktAmount,
_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 _mkt = (_pot.mul(potSplit_[_winTID].marketing)) / 100;
uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen).sub(_mkt);
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(_mkt);
if (!owner.send(_com)) {
_com = 0;
_res = _res.add(_com);
}
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_.mktAmount = _mkt;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked((block.timestamp).add(block.difficulty).add((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add(block.gaslimit).add((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add(block.number))));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = _eth / 50;
uint256 _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 {
_com = _com.add(_aff);
}
uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100;
_com = _com.add(_mkt);
owner.transfer(_com);
_eventData_.mktAmount = _mkt;
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
uint256 cut = (fees_[_team].marketing).add(13);
_eth = _eth.sub(_eth.mul(cut) / 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_.mktAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public onlyOwner {
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 mktAmount;
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 marketing;
}
struct PotSplit {
uint256 gen;
uint256 marketing;
}
}
library F3DKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
} | 0 |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function 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);
balanceOf[_from] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract MiningToken is owned, TokenERC20 {
uint256 public supplyReady;
uint256 public min4payout;
uint256 public centsPerMonth;
mapping(uint256 => address) public holders;
mapping(address => uint256) public indexes;
uint256 public num_holders=1;
function MiningToken(
string tokenName,
string tokenSymbol
) TokenERC20(0, tokenName, tokenSymbol) public {
centsPerMonth=0;
decimals=0;
setMinimum(0);
holders[num_holders++]=(msg.sender);
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
if(indexes[_to]==0||holders[indexes[_to]]==0){
indexes[_to]=num_holders;
holders[num_holders++]=_to;
}
Transfer(_from, _to, _value);
}
function setMinimum(uint256 d) onlyOwner public{
min4payout=d*1 ether / 1000;
}
function setCentsPerMonth(uint256 amount) onlyOwner public {
centsPerMonth=amount;
}
function getPayout(uint etherPrice) onlyOwner public {
require(this.balance>min4payout);
uint256 perToken=this.balance/totalSupply;
for (uint i = 1; i < num_holders; i++) {
address d=holders[i];
if(d!=0){
uint bal=balanceOf[d];
if(bal==0){
holders[i]=0;
}else{
uint powercost=((bal*centsPerMonth)/100) *( 1 ether/etherPrice);
holders[i].transfer((bal * perToken)-powercost);
}
}
}
owner.transfer(((totalSupply*centsPerMonth)/100) *( 1 ether/etherPrice));
}
function mint(uint256 amt) onlyOwner public {
balanceOf[owner] += amt;
totalSupply += amt;
Transfer(this, msg.sender, amt);
}
function mintTo(uint256 amt,address to) onlyOwner public {
balanceOf[to] += amt;
totalSupply += amt;
Transfer(this, to, amt);
if(indexes[to]==0||holders[indexes[to]]==0){
indexes[to]=num_holders;
holders[num_holders++]=to;
}
}
function() payable public{
}
function selfDestruct() onlyOwner payable public{
uint256 perToken=this.balance/totalSupply;
for (uint i = 1; i < num_holders; i++) {
holders[i].transfer(balanceOf[holders[i]] * perToken);
}
selfdestruct(owner);
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) { return 0;}
uint256 c = a * b; assert(c / a == b); return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;assert(c >= a);return c;
}
}
contract 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 ERC20 {
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 ERC20Standard is 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 StrategicToken is ERC20Standard {
string public constant name = "StrategicToken";
string public constant symbol = "STRT";
uint8 public constant decimals = 18;
uint256 public constant maxSupply = 300000000 * (10 ** uint256(decimals));
uint256 public STRTToEth;
uint256 public ethInWei;
address public devWallet;
function StrategicToken () public {
totalSupply = maxSupply;
balances[msg.sender] = maxSupply;
STRTToEth = 100000;
devWallet = msg.sender;
}
function() payable{
ethInWei = ethInWei + msg.value;
uint256 amount = msg.value * STRTToEth;
if (balances[devWallet] < amount) {return;}
balances[devWallet] = balances[devWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(devWallet, msg.sender, amount);
devWallet.send(msg.value);
}
} | 1 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BaseToken {
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)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0));
require(balanceOf[_from] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
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 renounceOwnership() public onlyOwner {
OwnershipRenounced(owner);
owner = address(0);
}
}
contract BurnToken is BaseToken {
event Burn(address indexed from, uint256 value);
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_from, _value);
return true;
}
}
contract AirdropToken is BaseToken, Ownable{
uint256 public airAmount;
address public airSender;
uint256 public airLimitCount;
mapping (address => uint256) public airCountOf;
event Airdrop(address indexed from, uint256 indexed count, uint256 tokenValue);
function airdrop() public {
require(airAmount > 0);
if (airLimitCount > 0 && airCountOf[msg.sender] >= airLimitCount) {
revert();
}
_transfer(airSender, msg.sender, airAmount);
airCountOf[msg.sender] = airCountOf[msg.sender].add(1);
Airdrop(msg.sender, airCountOf[msg.sender], airAmount);
}
function changeAirAmount(uint256 newAirAmount) public onlyOwner {
airAmount = newAirAmount;
}
function changeAirLimitCount(uint256 newAirLimitCount) public onlyOwner {
airLimitCount = newAirLimitCount;
}
}
contract LockToken is BaseToken {
struct LockMeta {
uint256 remain;
uint256 endtime;
}
mapping (address => LockMeta[]) public lockedAddresses;
function _transfer(address _from, address _to, uint _value) internal {
require(balanceOf[_from] >= _value);
uint256 remain = balanceOf[_from].sub(_value);
uint256 length = lockedAddresses[_from].length;
for (uint256 i = 0; i < length; i++) {
LockMeta storage meta = lockedAddresses[_from][i];
if(block.timestamp < meta.endtime && remain < meta.remain){
revert();
}
}
super._transfer(_from, _to, _value);
}
}
contract TTest is BaseToken, BurnToken, AirdropToken, LockToken {
function TTest() public {
totalSupply = 36000000000000000;
name = "ABCToken";
symbol = "ABC";
decimals = 8;
owner = msg.sender;
airAmount = 100000000;
airSender = 0x8888888888888888888888888888888888888888;
airLimitCount = 1;
balanceOf[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920] = 3600000000000000;
Transfer(address(0), 0x7F268F51f3017C3dDB9A343C8b5345918D2AB920, 3600000000000000);
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 3600000000000000, endtime: 1528189200}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 3240000000000000, endtime: 1528192800}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 2880000000000000, endtime: 1528196400}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 2520000000000000, endtime: 1528200000}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 2160000000000000, endtime: 1528203600}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 1800000000000000, endtime: 1528207200}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 1440000000000000, endtime: 1528210800}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 1080000000000000, endtime: 1528214400}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 720000000000000, endtime: 1528218000}));
lockedAddresses[0x7F268F51f3017C3dDB9A343C8b5345918D2AB920].push(LockMeta({remain: 360000000000000, endtime: 1528221600}));
balanceOf[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3] = 3600000000000000;
Transfer(address(0), 0xE4CB2A481375E0208580194BD38911eE6c2d3fA3, 3600000000000000);
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 3600000000000000, endtime: 1528189200}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 3240000000000000, endtime: 1528192800}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 2880000000000000, endtime: 1528196400}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 2520000000000000, endtime: 1528200000}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 2160000000000000, endtime: 1528203600}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 1800000000000000, endtime: 1528207200}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 1440000000000000, endtime: 1528210800}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 1080000000000000, endtime: 1528214400}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 720000000000000, endtime: 1528218000}));
lockedAddresses[0xE4CB2A481375E0208580194BD38911eE6c2d3fA3].push(LockMeta({remain: 360000000000000, endtime: 1528221600}));
balanceOf[0x6a15b2BeC95243996416F6baBd8f288f7B4a8312] = 3600000000000000;
Transfer(address(0), 0x6a15b2BeC95243996416F6baBd8f288f7B4a8312, 3600000000000000);
balanceOf[0x0863f878b6a1d9271CB5b775394Ff8AF2689456f] = 10800000000000000;
Transfer(address(0), 0x0863f878b6a1d9271CB5b775394Ff8AF2689456f, 10800000000000000);
balanceOf[0x73149136faFc31E1bA03dC240F5Ad903F2E1aE2e] = 3564000000000000;
Transfer(address(0), 0x73149136faFc31E1bA03dC240F5Ad903F2E1aE2e, 3564000000000000);
lockedAddresses[0x73149136faFc31E1bA03dC240F5Ad903F2E1aE2e].push(LockMeta({remain: 1663200000000000, endtime: 1528182000}));
lockedAddresses[0x73149136faFc31E1bA03dC240F5Ad903F2E1aE2e].push(LockMeta({remain: 1188000000000000, endtime: 1528181400}));
balanceOf[0xF63ce8e24d18FAF8D5719f192039145D010c7aBd] = 10836000000000000;
Transfer(address(0), 0xF63ce8e24d18FAF8D5719f192039145D010c7aBd, 10836000000000000);
lockedAddresses[0xF63ce8e24d18FAF8D5719f192039145D010c7aBd].push(LockMeta({remain: 2167200000000000, endtime: 1528182000}));
}
function() public {
airdrop();
}
} | 1 |
pragma solidity ^0.4.25;
interface IERC20 {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract StableCoin is owned,IERC20{
using SafeMath for uint256;
uint256 public constant _totalSupply = 100000000000000000000000000;
string public constant symbol = 'SCA';
string public constant name = 'Stable Coin ATM';
uint8 public constant decimals = 18;
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) allowed;
constructor() public {
balances[msg.sender] = _totalSupply;
}
function totalSupply() constant returns (uint256 totalSupply) {
return _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(
balances[msg.sender] >= _value
&& _value > 0
);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(
allowed[_from][msg.sender] >= _value
&& balances[_from] >= _value
&& _value > 0
);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} | 1 |
pragma solidity ^0.4.11;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
contract GeneScienceInterface {
function isGeneScience() public pure returns (bool);
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
contract KittyAccessControl {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract KittyBase is KittyAccessControl {
event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes);
event Transfer(address from, address to, uint256 tokenId);
struct Kitty {
uint256 genes;
uint64 birthTime;
uint64 cooldownEndBlock;
uint32 matronId;
uint32 sireId;
uint32 siringWithId;
uint16 cooldownIndex;
uint16 generation;
}
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
uint256 public secondsPerBlock = 15;
Kitty[] kitties;
mapping (uint256 => address) public kittyIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public kittyIndexToApproved;
mapping (uint256 => address) public sireAllowedToAddress;
SaleClockAuction public saleAuction;
SiringClockAuction public siringAuction;
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to]++;
kittyIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete sireAllowedToAddress[_tokenId];
delete kittyIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
function _createKitty(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Kitty memory _kitty = Kitty({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newKittenId = kitties.push(_kitty) - 1;
require(newKittenId == uint256(uint32(newKittenId)));
Birth(
_owner,
newKittenId,
uint256(_kitty.matronId),
uint256(_kitty.sireId),
_kitty.genes
);
_transfer(0, _owner, newKittenId);
return newKittenId;
}
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
contract ERC721Metadata {
function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
contract KittyOwnership is KittyBase, ERC721 {
string public constant name = "CryptoKitties";
string public constant symbol = "CK";
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyIndexToOwner[_tokenId] == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return kittyIndexToApproved[_tokenId] == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
kittyIndexToApproved[_tokenId] = _approved;
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(saleAuction));
require(_to != address(siringAuction));
require(_owns(msg.sender, _tokenId));
_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
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return kitties.length - 1;
}
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = kittyIndexToOwner[_tokenId];
require(owner != address(0));
}
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCats = totalSupply();
uint256 resultIndex = 0;
uint256 catId;
for (catId = 1; catId <= totalCats; catId++) {
if (kittyIndexToOwner[catId] == _owner) {
result[resultIndex] = catId;
resultIndex++;
}
}
return result;
}
}
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
contract KittyBreeding is KittyOwnership {
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
uint256 public autoBirthFee = 2 finney;
uint256 public pregnantKitties;
GeneScienceInterface public geneScience;
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
require(candidateContract.isGeneScience());
geneScience = candidateContract;
}
function _isReadyToBreed(Kitty _kit) internal view returns (bool) {
return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
}
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = kittyIndexToOwner[_matronId];
address sireOwner = kittyIndexToOwner[_sireId];
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
function _triggerCooldown(Kitty storage _kitten) internal {
_kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number);
if (_kitten.cooldownIndex < 13) {
_kitten.cooldownIndex += 1;
}
}
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
function isReadyToBreed(uint256 _kittyId)
public
view
returns (bool)
{
require(_kittyId > 0);
Kitty storage kit = kitties[_kittyId];
return _isReadyToBreed(kit);
}
function isPregnant(uint256 _kittyId)
public
view
returns (bool)
{
require(_kittyId > 0);
return kitties[_kittyId].siringWithId != 0;
}
function _isValidMatingPair(
Kitty storage _matron,
uint256 _matronId,
Kitty storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
if (_matronId == _sireId) {
return false;
}
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
return true;
}
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns(bool)
{
require(_matronId > 0);
require(_sireId > 0);
Kitty storage matron = kitties[_matronId];
Kitty storage sire = kitties[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
Kitty storage sire = kitties[_sireId];
Kitty storage matron = kitties[_matronId];
matron.siringWithId = uint32(_sireId);
_triggerCooldown(sire);
_triggerCooldown(matron);
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
pregnantKitties++;
Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
}
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
require(msg.value >= autoBirthFee);
require(_owns(msg.sender, _matronId));
require(_isSiringPermitted(_sireId, _matronId));
Kitty storage matron = kitties[_matronId];
require(_isReadyToBreed(matron));
Kitty storage sire = kitties[_sireId];
require(_isReadyToBreed(sire));
require(_isValidMatingPair(
matron,
_matronId,
sire,
_sireId
));
_breedWith(_matronId, _sireId);
}
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns(uint256)
{
Kitty storage matron = kitties[_matronId];
require(matron.birthTime != 0);
require(_isReadyToGiveBirth(matron));
uint256 sireId = matron.siringWithId;
Kitty storage sire = kitties[sireId];
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
address owner = kittyIndexToOwner[_matronId];
uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
delete matron.siringWithId;
pregnantKitties--;
msg.sender.send(autoBirthFee);
return kittenId;
}
}
contract ClockAuctionBase {
struct Auction {
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
}
ERC721 public nonFungibleContract;
uint256 public ownerCut;
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
function _escrow(address _owner, uint256 _tokenId) internal {
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
function _transfer(address _receiver, uint256 _tokenId) internal {
nonFungibleContract.transfer(_receiver, _tokenId);
}
function _addAuction(uint256 _tokenId, Auction _auction) internal {
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
address seller = auction.seller;
_removeAuction(_tokenId);
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
uint256 bidExcess = _bidAmount - price;
msg.sender.transfer(bidExcess);
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
if (_secondsPassed >= _duration) {
return _endingPrice;
} else {
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
function _computeCut(uint256 _price) internal view returns (uint256) {
return _price * ownerCut / 10000;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ClockAuction is Pausable, ClockAuctionBase {
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
bool res = nftAddress.send(this.balance);
}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
contract SiringClockAuction is ClockAuction {
bool public isSiringClockAuction = true;
function SiringClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
_bid(_tokenId, msg.value);
_transfer(seller, _tokenId);
}
}
contract SaleClockAuction is ClockAuction {
bool public isSaleClockAuction = true;
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
{
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
if (seller == address(nonFungibleContract)) {
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
contract KittyAuction is KittyBreeding {
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
require(candidateContract.isSiringClockAuction());
siringAuction = candidateContract;
}
function createSaleAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_owns(msg.sender, _kittyId));
require(!isPregnant(_kittyId));
_approve(_kittyId, saleAuction);
saleAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function createSiringAuction(
uint256 _kittyId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_owns(msg.sender, _kittyId));
require(isReadyToBreed(_kittyId));
_approve(_kittyId, siringAuction);
siringAuction.createAuction(
_kittyId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
contract KittyMinting is KittyAuction {
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
function createPromoKitty(uint256 _genes, address _owner) external onlyCOO {
address kittyOwner = _owner;
if (kittyOwner == address(0)) {
kittyOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createKitty(0, 0, 0, _genes, kittyOwner);
}
function createGen0Auction(uint256 _genes) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this));
_approve(kittyId, saleAuction);
saleAuction.createAuction(
kittyId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
contract KittyCore is KittyMinting {
address public newContractAddress;
function KittyCore() public {
paused = true;
ceoAddress = msg.sender;
cooAddress = msg.sender;
_createKitty(0, 0, 0, uint256(-1), address(0));
}
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
function getKitty(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
Kitty storage kit = kitties[_id];
isGestating = (kit.siringWithId != 0);
isReady = (kit.cooldownEndBlock <= block.number);
cooldownIndex = uint256(kit.cooldownIndex);
nextActionAt = uint256(kit.cooldownEndBlock);
siringWithId = uint256(kit.siringWithId);
birthTime = uint256(kit.birthTime);
matronId = uint256(kit.matronId);
sireId = uint256(kit.sireId);
generation = uint256(kit.generation);
genes = kit.genes;
}
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(newContractAddress == address(0));
super.unpause();
}
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
} | 0 |
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
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
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(value <= _balances[from]);
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 != 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 != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
contract ERC20Mintable is ERC20, MinterRole {
function mint(
address to,
uint256 value
)
public
onlyMinter
returns (bool)
{
_mint(to, value);
return true;
}
}
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 PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
function paused() public view returns(bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.approve(spender, value);
}
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, 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 Exmilibus is ERC20, ERC20Burnable, ERC20Detailed, ERC20Mintable, ERC20Pausable, Ownable {
constructor(
string name,
string symbol,
uint8 decimals
)
ERC20Burnable()
ERC20Mintable()
ERC20Pausable()
ERC20Detailed(name, symbol, decimals)
ERC20()
Ownable()
public
{}
} | 1 |
pragma solidity ^0.4.16;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract KJC {
string public name = "KimJ Coin";
string public symbol = "KJC";
uint8 public decimals = 18;
uint256 public totalSupply =2000000* (10 ** 18);
uint256 public totaldivineTokensIssued = 0;
address owner = msg.sender;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
bool public saleEnabled = true;
uint256 public totalEthereumRaised = 0;
uint256 public KJCPerEthereum = 10000;
function KJC() public {
balanceOf[owner] += totalSupply;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
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)
{
if (_value != 0 && allowance[msg.sender][_spender] != 0) { return false; }
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success)
{
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function() public payable {
require(saleEnabled);
if (msg.value == 0) { return; }
owner.transfer(msg.value);
totalEthereumRaised += msg.value;
uint256 tokensIssued = (msg.value * KJCPerEthereum);
if (msg.value >= 10 finney)
{
bytes20 divineHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (divineHash[0] == 0 || divineHash[0] == 1)
{
uint8 divineMultiplier =
((divineHash[1] & 0x01 != 0) ? 1 : 0) + ((divineHash[1] & 0x02 != 0) ? 1 : 0) +
((divineHash[1] & 0x04 != 0) ? 1 : 0) + ((divineHash[1] & 0x08 != 0) ? 1 : 0);
uint256 divineTokensIssued = (msg.value * KJCPerEthereum) * divineMultiplier;
tokensIssued += divineTokensIssued;
totaldivineTokensIssued += divineTokensIssued;
}
}
totalSupply += tokensIssued;
balanceOf[msg.sender] += tokensIssued;
Transfer(address(this), msg.sender, tokensIssued);
}
function disablePurchasing() public
{
require(msg.sender == owner);
saleEnabled = false;
}
function getStats() public constant returns (uint256, uint256, uint256, bool) {
return (totalEthereumRaised, totalSupply, totaldivineTokensIssued, saleEnabled);
}
} | 1 |
pragma solidity 0.4.25;
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;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public;
function transferFrom(address from, address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract admined {
mapping(address => uint8) public level;
constructor() internal {
level[msg.sender] = 2;
emit AdminshipUpdated(msg.sender,2);
}
modifier onlyAdmin(uint8 _level) {
require(level[msg.sender] >= _level );
_;
}
function adminshipLevel(address _newAdmin, uint8 _level) onlyAdmin(2) public {
require(_newAdmin != address(0));
level[_newAdmin] = _level;
emit AdminshipUpdated(_newAdmin,_level);
}
event AdminshipUpdated(address _newAdmin, uint8 _level);
}
contract PRIWGRICO is admined {
using SafeMath for uint256;
enum State {
MAINSALE,
Successful
}
State public state = State.MAINSALE;
uint256 public MAINSALEStart = now;
uint256 public SaleDeadline = MAINSALEStart.add(120 days);
uint256 public completedAt;
uint256 public totalRaised;
uint256 public totalDistributed;
ERC20Basic public tokenReward;
address public creator;
address public WGRholder;
string public version = '0.1';
uint256 public USDPriceInWei;
event LogFundrisingInitialized(address indexed _creator);
event LogFundingReceived(address indexed _addr, uint _amount, uint _currentTotal);
event LogBeneficiaryPaid(address indexed _beneficiaryAddress);
event LogContributorsPayout(address indexed _addr, uint _amount);
event LogFundingSuccessful(uint _totalRaised);
modifier notFinished() {
require(state != State.Successful);
_;
}
constructor(ERC20Basic _addressOfTokenUsedAsReward, uint _initialUSDInWei) public {
creator = msg.sender;
WGRholder = creator;
tokenReward = _addressOfTokenUsedAsReward;
USDPriceInWei = _initialUSDInWei;
emit LogFundrisingInitialized(creator);
}
function contribute(address _target, uint256 _value) public notFinished payable {
require(now > MAINSALEStart);
address user;
uint remaining;
uint256 tokenBought;
uint256 temp;
if(_target != address(0) && level[msg.sender] >= 1){
user = _target;
remaining = _value.mul(1e18);
} else {
user = msg.sender;
remaining = msg.value.mul(1e18);
}
totalRaised = totalRaised.add(remaining.div(1e18));
while(remaining > 0){
(temp,remaining) = tokenBuyCalc(remaining);
tokenBought = tokenBought.add(temp);
}
temp = 0;
totalDistributed = totalDistributed.add(tokenBought);
WGRholder.transfer(address(this).balance);
emit LogBeneficiaryPaid(WGRholder);
tokenReward.transfer(user,tokenBought);
emit LogFundingReceived(user, msg.value, totalRaised);
checkIfFundingCompleteOrExpired();
}
function tokenBuyCalc(uint _value) internal view returns (uint sold,uint remaining) {
uint256 tempPrice = USDPriceInWei;
tempPrice = tempPrice.mul(1000);
sold = _value.div(tempPrice);
return (sold,0);
}
function checkIfFundingCompleteOrExpired() public {
if ( now > SaleDeadline && state != State.Successful){
state = State.Successful;
completedAt = now;
emit LogFundingSuccessful(totalRaised);
successful();
}
}
function successful() public {
require(state == State.Successful);
uint256 temp = tokenReward.balanceOf(address(this));
tokenReward.transfer(creator,temp);
emit LogContributorsPayout(creator,temp);
WGRholder.transfer(address(this).balance);
emit LogBeneficiaryPaid(WGRholder);
}
function setPrice(uint _value) public onlyAdmin(2) {
USDPriceInWei = _value;
}
function setHolder(address _holder) public onlyAdmin(2) {
WGRholder = _holder;
}
function externalTokensRecovery(ERC20Basic _address) onlyAdmin(2) public{
require(state == State.Successful);
uint256 remainder = _address.balanceOf(address(this));
_address.transfer(msg.sender,remainder);
}
function () public payable {
contribute(address(0),0);
}
} | 0 |
pragma solidity ^0.4.23;
contract ERC20 {
function transferFrom(address from, address to, uint value) public returns (bool success);
}
contract ERC721 {
function transferFrom(address from, address to, uint value) public;
}
contract Ownable {
address owner;
address pendingOwner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyPendingOwner {
require(msg.sender == pendingOwner);
_;
}
constructor() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
owner = pendingOwner;
}
}
contract Destructible is Ownable {
function destroy() public onlyOwner {
selfdestruct(msg.sender);
}
}
contract WithClaim {
event Claim(string data);
}
contract UserfeedsClaimWithoutValueTransfer is Destructible, WithClaim {
function post(string data) public {
emit Claim(data);
}
}
contract UserfeedsClaimWithValueTransfer is Destructible, WithClaim {
function post(address userfeed, string data) public payable {
emit Claim(data);
userfeed.transfer(msg.value);
}
}
contract UserfeedsClaimWithTokenTransfer is Destructible, WithClaim {
function post(address userfeed, ERC20 token, uint value, string data) public {
emit Claim(data);
require(token.transferFrom(msg.sender, userfeed, value));
}
}
contract UserfeedsClaimWithValueMultiSendUnsafe is Destructible, WithClaim {
function post(string data, address[] recipients) public payable {
emit Claim(data);
send(recipients);
}
function post(string data, bytes20[] recipients) public payable {
emit Claim(data);
send(recipients);
}
function send(address[] recipients) public payable {
uint amount = msg.value / recipients.length;
for (uint i = 0; i < recipients.length; i++) {
recipients[i].send(amount);
}
msg.sender.transfer(address(this).balance);
}
function send(bytes20[] recipients) public payable {
uint amount = msg.value / recipients.length;
for (uint i = 0; i < recipients.length; i++) {
address(recipients[i]).send(amount);
}
msg.sender.transfer(address(this).balance);
}
}
contract UserfeedsClaimWithConfigurableValueMultiTransfer is Destructible, WithClaim {
function post(string data, address[] recipients, uint[] values) public payable {
emit Claim(data);
transfer(recipients, values);
}
function transfer(address[] recipients, uint[] values) public payable {
for (uint i = 0; i < recipients.length; i++) {
recipients[i].transfer(values[i]);
}
msg.sender.transfer(address(this).balance);
}
}
contract UserfeedsClaimWithConfigurableTokenMultiTransfer is Destructible, WithClaim {
function post(string data, address[] recipients, ERC20 token, uint[] values) public {
emit Claim(data);
transfer(recipients, token, values);
}
function transfer(address[] recipients, ERC20 token, uint[] values) public {
for (uint i = 0; i < recipients.length; i++) {
require(token.transferFrom(msg.sender, recipients[i], values[i]));
}
}
}
contract UserfeedsClaimWithConfigurableTokenMultiTransferNoCheck is Destructible, WithClaim {
function post(string data, address[] recipients, ERC721 token, uint[] values) public {
emit Claim(data);
transfer(recipients, token, values);
}
function transfer(address[] recipients, ERC721 token, uint[] values) public {
for (uint i = 0; i < recipients.length; i++) {
token.transferFrom(msg.sender, recipients[i], values[i]);
}
}
} | 1 |
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));
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);
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 = 1000 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 = 1529074800;
multiSig = 0xD00d085F125EAFEA9e8c5D3f4bc25e6D0c93Af0e;
token = new ReporterToken();
decimals = token.decimals();
oneCoin = 10 ** decimals;
maxTokens = 60 * (10**6) * oneCoin;
tokensForSale = 36 * (10**6) * oneCoin;
rate = 3000;
}
function currentTime() public constant returns (uint256) {
return now;
}
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 (currentTime() > 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 (currentTime() >= 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) onlyCS public {
require(0 < newRate && newRate <= 8000);
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;
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 QJToken {
using SafeMath for uint256;
string public name = "Qing Jian";
string public symbol = "QJ";
uint256 public decimals = 8;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
uint256 public totalSupply = 0;
uint256 constant valueFounder = 1000000000000;
modifier validAddress {
assert(0x0 != msg.sender);
_;
}
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 {
totalSupply = valueFounder;
balanceOf[msg.sender] = valueFounder;
emit Transfer(0x0, msg.sender, valueFounder);
}
function _transfer(address _from, address _to, uint256 _value) private {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) validAddress public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) validAddress public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) validAddress public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function burn(uint256 _value) validAddress public returns (bool success) {
require (balanceOf[msg.sender] >= _value);
require (_value > 0);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30326400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x9f61Aa26D9EFfd5F739C8EbB818BD27756Ab9029;
}
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.2;
contract CoinByInsomnia {
string public name = "CoinByInsomnia";
string public symbol = "CBI";
string public standard = "CoinByInsomnia v1.0";
uint256 public _totalSupply = 100000000;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
constructor (uint256 _initialSupply) public {
balanceOf[msg.sender] = _initialSupply;
_totalSupply = _initialSupply;
}
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;
}
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;
}
}
contract CoinByInsomniaTokenSale {
address admin;
CoinByInsomnia public tokenContract;
uint256 public tokenPrice;
uint256 public tokensSold;
event Sell(address _buyer, uint256 _amount);
constructor (CoinByInsomnia _tokenContract, uint256 _tokenPrice) public {
admin = msg.sender;
tokenContract = _tokenContract;
tokenPrice = _tokenPrice;
}
function multiply(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function buyTokens(uint256 _numberOfTokens) public payable {
require(msg.value == multiply(_numberOfTokens, tokenPrice));
require(tokenContract.balanceOf(this) >= _numberOfTokens);
require(tokenContract.transfer(msg.sender, _numberOfTokens));
tokensSold += _numberOfTokens;
emit Sell(msg.sender, _numberOfTokens);
}
function endSale() public {
require(msg.sender == admin);
require(tokenContract.transfer(admin, tokenContract.balanceOf(this)));
admin.transfer(address(this).balance);
}
} | 0 |
pragma solidity ^0.4.25;
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract AbstractToken is Token, SafeMath {
constructor () public {
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) public returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
contract SUGARToken is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 1000000000 * (10**18);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
constructor () public {
owner = msg.sender;
}
function totalSupply() public constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Planetagro-Exchange";
string constant public symbol = "SUGAR";
uint8 constant public decimals = 18;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value) public
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value) public
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) public {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) public {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event Freeze ();
event Unfreeze ();
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
} | 1 |
pragma solidity ^0.4.24;
library DataSet {
enum RoundState {
UNKNOWN,
STARTED,
STOPPED,
DRAWN,
ASSIGNED
}
struct Round {
uint256 count;
uint256 timestamp;
uint256 blockNumber;
uint256 drawBlockNumber;
RoundState state;
uint256 pond;
uint256 winningNumber;
address winner;
}
}
library NumberCompressor {
uint256 constant private MASK = 16777215;
function encode(uint256 _begin, uint256 _end, uint256 _ceiling) internal pure returns (uint256)
{
require(_begin <= _end && _end < _ceiling, "number is invalid");
return _begin << 24 | _end;
}
function decode(uint256 _value) internal pure returns (uint256, uint256)
{
uint256 end = _value & MASK;
uint256 begin = (_value >> 24) & MASK;
return (begin, end);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
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;
}
}
contract Events {
event onActivate
(
address indexed addr,
uint256 timestamp,
uint256 bonus,
uint256 issued_numbers
);
event onDraw
(
uint256 timestatmp,
uint256 blockNumber,
uint256 roundID,
uint256 winningNumber
);
event onStartRunnd
(
uint256 timestamp,
uint256 roundID
);
event onBet
(
address indexed addr,
uint256 timestamp,
uint256 roundID,
uint256 beginNumber,
uint256 endNumber
);
event onAssign
(
address indexed operatorAddr,
uint256 timestatmp,
address indexed winnerAddr,
uint256 roundID,
uint256 pond,
uint256 bonus,
uint256 fund
);
event onRefund
(
address indexed operatorAddr,
uint256 timestamp,
address indexed playerAddr,
uint256 count,
uint256 amount
);
event onLastRefund
(
address indexed operatorAddr,
uint256 timestamp,
address indexed platformAddr,
uint256 amout
);
}
contract Winner is Events {
using SafeMath for *;
uint256 constant private MIN_BET = 0.01 ether;
uint256 constant private PRICE = 0.01 ether;
uint256 constant private MAX_DURATION = 30 days;
uint256 constant private REFUND_RATE = 90;
address constant private platform = 0xD51bD6EB7aA3661c9c5726403315F0B0f8d96C2e;
uint256 private curRoundID;
uint256 private drawnRoundID;
uint256 private drawnBlockNumber;
uint256 private bonus;
uint256 private issued_numbers;
bool private initialized;
mapping (uint256 => DataSet.Round) private rounds;
mapping (uint256 => mapping(address => uint256[])) private playerNumbers;
mapping (address => bool) private administrators;
constructor() public {
}
modifier isAdmin() {
require(administrators[msg.sender], "only administrators");
_;
}
modifier isInitialized () {
require(initialized == true, "game is inactive");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry, humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= MIN_BET, "the bet is too small");
require(_eth <= PRICE.mul(issued_numbers).mul(2), "the bet is too big");
_;
}
function() public payable isHuman() isInitialized() isWithinLimits(msg.value)
{
bet(msg.value);
}
function initiate(uint256 _bonus, uint256 _issued_numbers) public isHuman()
{
require(initialized == false, "it has been initialized already");
require(_bonus > 0, "bonus is invalid");
require(_issued_numbers > 0, "issued_numbers is invalid");
initialized = true;
administrators[msg.sender] = true;
bonus = _bonus;
issued_numbers = _issued_numbers;
emit onActivate(msg.sender, block.timestamp, bonus, issued_numbers);
curRoundID = 1;
rounds[curRoundID].state = DataSet.RoundState.STARTED;
rounds[curRoundID].timestamp = block.timestamp;
drawnRoundID = 0;
emit onStartRunnd(block.timestamp, curRoundID);
}
function drawNumber() private view returns(uint256) {
return uint256(keccak256(abi.encodePacked(
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 1))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 2))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 3))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 4))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 5))))) / (block.timestamp)).add
((uint256(keccak256(abi.encodePacked(block.blockhash(block.number - 6))))) / (block.timestamp))
))) % issued_numbers;
}
function bet(uint256 _amount) private
{
if (block.number != drawnBlockNumber
&& curRoundID > drawnRoundID
&& rounds[drawnRoundID + 1].count == issued_numbers
&& block.number >= rounds[drawnRoundID + 1].blockNumber + 7)
{
drawnBlockNumber = block.number;
drawnRoundID += 1;
rounds[drawnRoundID].winningNumber = drawNumber();
rounds[drawnRoundID].state = DataSet.RoundState.DRAWN;
rounds[drawnRoundID].drawBlockNumber = drawnBlockNumber;
emit onDraw(block.timestamp, drawnBlockNumber, drawnRoundID, rounds[drawnRoundID].winningNumber);
}
uint256 amount = _amount;
while (true)
{
uint256 max = issued_numbers - rounds[curRoundID].count;
uint256 available = amount.div(PRICE).min(max);
if (available == 0)
{
if (amount != 0)
{
rounds[curRoundID].pond += amount;
}
break;
}
uint256[] storage numbers = playerNumbers[curRoundID][msg.sender];
uint256 begin = rounds[curRoundID].count;
uint256 end = begin + available - 1;
uint256 compressedNumber = NumberCompressor.encode(begin, end, issued_numbers);
numbers.push(compressedNumber);
rounds[curRoundID].pond += available.mul(PRICE);
rounds[curRoundID].count += available;
amount -= available.mul(PRICE);
emit onBet(msg.sender, block.timestamp, curRoundID, begin, end);
if (rounds[curRoundID].count == issued_numbers)
{
rounds[curRoundID].blockNumber = block.number;
rounds[curRoundID].state = DataSet.RoundState.STOPPED;
curRoundID += 1;
rounds[curRoundID].state = DataSet.RoundState.STARTED;
rounds[curRoundID].timestamp = block.timestamp;
emit onStartRunnd(block.timestamp, curRoundID);
}
}
}
function assign(uint256 _roundID) external isHuman() isInitialized()
{
assign2(msg.sender, _roundID);
}
function assign2(address _player, uint256 _roundID) public isHuman() isInitialized()
{
require(rounds[_roundID].state == DataSet.RoundState.DRAWN, "it's not time for assigning");
uint256[] memory numbers = playerNumbers[_roundID][_player];
require(numbers.length > 0, "player did not involve in");
uint256 targetNumber = rounds[_roundID].winningNumber;
for (uint256 i = 0; i < numbers.length; i ++)
{
(uint256 start, uint256 end) = NumberCompressor.decode(numbers[i]);
if (targetNumber >= start && targetNumber <= end)
{
uint256 fund = rounds[_roundID].pond.sub(bonus);
_player.transfer(bonus);
platform.transfer(fund);
rounds[_roundID].state = DataSet.RoundState.ASSIGNED;
rounds[_roundID].winner = _player;
emit onAssign(msg.sender, block.timestamp, _player, _roundID, rounds[_roundID].pond, bonus, fund);
break;
}
}
}
function refund() external isHuman() isInitialized()
{
refund2(msg.sender);
}
function refund2(address _player) public isInitialized() isHuman()
{
require(block.timestamp.sub(rounds[curRoundID].timestamp) >= MAX_DURATION, "it's not time for refunding");
uint256[] storage numbers = playerNumbers[curRoundID][_player];
require(numbers.length > 0, "player did not involve in");
uint256 count = 0;
for (uint256 i = 0; i < numbers.length; i ++)
{
(uint256 begin, uint256 end) = NumberCompressor.decode(numbers[i]);
count += (end - begin + 1);
}
uint256 amount = count.mul(PRICE).mul(REFUND_RATE).div(100);
rounds[curRoundID].pond = rounds[curRoundID].pond.sub(amount);
_player.transfer(amount);
emit onRefund(msg.sender, block.timestamp, _player, count, amount);
rounds[curRoundID].count -= count;
if (rounds[curRoundID].count == 0)
{
uint256 last = rounds[curRoundID].pond;
platform.transfer(last);
rounds[curRoundID].pond = 0;
emit onLastRefund(msg.sender, block.timestamp, platform, last);
}
}
function getPlayerRoundNumbers(uint256 _roundID, address _palyer) public view returns(uint256[])
{
return playerNumbers[_roundID][_palyer];
}
function getRoundInfo(uint256 _roundID) public view
returns(uint256, uint256, uint256, uint256, uint256, uint256, address)
{
return (
rounds[_roundID].count,
rounds[_roundID].blockNumber,
rounds[_roundID].drawBlockNumber,
uint256(rounds[_roundID].state),
rounds[_roundID].pond,
rounds[_roundID].winningNumber,
rounds[_roundID].winner
);
}
function gameInfo() public view
returns(bool, uint256, uint256, uint256, uint256)
{
return (
initialized,
bonus,
issued_numbers,
curRoundID,
drawnRoundID
);
}
}
contract Proxy {
function implementation() public view returns (address);
function () public payable {
address _impl = implementation();
require(_impl != address(0), "address invalid");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
let size := returndatasize
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
contract UpgradeabilityProxy is Proxy {
event Upgraded(address indexed implementation);
bytes32 private constant implementationPosition = keccak256("you are the lucky man.proxy");
constructor() public {}
function implementation() public view returns (address impl) {
bytes32 position = implementationPosition;
assembly {
impl := sload(position)
}
}
function setImplementation(address newImplementation) internal {
bytes32 position = implementationPosition;
assembly {
sstore(position, newImplementation)
}
}
function _upgradeTo(address newImplementation) internal {
address currentImplementation = implementation();
require(currentImplementation != newImplementation, "new address is the same");
setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
}
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy {
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
bytes32 private constant proxyOwnerPosition = keccak256("you are the lucky man.proxy.owner");
constructor() public {
setUpgradeabilityOwner(msg.sender);
}
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "owner only");
_;
}
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
function setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "address is invalid");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
function upgradeToAndCall(address implementation, bytes data) public payable onlyProxyOwner {
upgradeTo(implementation);
require(address(this).call.value(msg.value)(data), "data is invalid");
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xFBBDD3EB0936A8467E71DF97B881bE0aE15d5251;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.11;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract MultiSig is owned {
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
if (msg.sender != address(this))
throw;
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
throw;
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
throw;
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
throw;
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
throw;
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
throw;
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
throw;
_;
}
modifier notNull(address _address) {
if (_address == 0)
throw;
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
throw;
_;
}
function MultiSig(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
throw;
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
changeRequirement(owners.length / 2 + 1);
OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
changeRequirement(owners.length / 2 + 1);
OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
ownerExists(msg.sender)
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
contract MultiSigWallet is MultiSig {
function MultiSigWallet(address[] _owners, uint _required)
public
MultiSig( _owners, _required)
{
}
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
if (tx.destination.call.value(tx.value)(tx.data)) {
tx.executed = true;
Execution(transactionId);
} else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
}
contract token {function transfer(address receiver, uint amount) returns (bool success);}
contract MultiSigToken is MultiSig {
token public tokenFactory ;
function MultiSigToken(address[] _owners, uint _required, token _addressOfTokenFactory)
public
MultiSig( _owners, _required)
{
tokenFactory = token(_addressOfTokenFactory);
}
function()
{
throw;
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
if (tokenFactory.transfer(tx.destination, tx.value)) {
tx.executed = true;
Execution(transactionId);
} else {
tx.executed = false;
ExecutionFailure(transactionId);
}
}
}
} | 0 |
pragma solidity 0.4.25;
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList{
mapping (uint256 => mapping (bool => uint256)) list;
}
function listExists(LinkedList storage self)
public
view returns (bool)
{
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
function nodeExists(LinkedList storage self, uint256 _node)
public
view returns (bool)
{
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
function sizeOf(LinkedList storage self) public view returns (uint256 numElements) {
bool exists;
uint256 i;
(exists,i) = getAdjacent(self, HEAD, NEXT);
while (i != HEAD) {
(exists,i) = getAdjacent(self, i, NEXT);
numElements++;
}
return;
}
function getNode(LinkedList storage self, uint256 _node)
public view returns (bool,uint256,uint256)
{
if (!nodeExists(self,_node)) {
return (false,0,0);
} else {
return (true,self.list[_node][PREV], self.list[_node][NEXT]);
}
}
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public view returns (bool,uint256)
{
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public view returns (uint256)
{
if (sizeOf(self) == 0) { return 0; }
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
return true;
} else {
return false;
}
}
function remove(LinkedList storage self, uint256 _node) internal returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; }
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
return _node;
}
function push(LinkedList storage self, uint256 _node, bool _direction) internal {
insert(self, HEAD, _node, _direction);
}
function pop(LinkedList storage self, bool _direction) internal returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
}
contract Whitelist is Ownable, RBAC {
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
modifier onlyWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
function addAddressToWhitelist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressAdded(addr);
}
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
}
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 QuantstampAuditData is Whitelist {
enum AuditState {
None,
Queued,
Assigned,
Refunded,
Completed,
Error,
Expired,
Resolved
}
struct Audit {
address requestor;
string contractUri;
uint256 price;
uint256 requestBlockNumber;
QuantstampAuditData.AuditState state;
address auditor;
uint256 assignBlockNumber;
string reportHash;
uint256 reportBlockNumber;
address registrar;
}
mapping(uint256 => Audit) public audits;
StandardToken public token;
uint256 public auditTimeoutInBlocks = 50;
uint256 public maxAssignedRequests = 10;
mapping(address => uint256) public minAuditPrice;
uint256 private requestCounter;
constructor (address tokenAddress) public {
require(tokenAddress != address(0));
token = StandardToken(tokenAddress);
}
function addAuditRequest (address requestor, string contractUri, uint256 price) public onlyWhitelisted returns(uint256) {
uint256 requestId = ++requestCounter;
audits[requestId] = Audit(requestor, contractUri, price, block.number, AuditState.Queued, address(0), 0, "", 0, msg.sender);
return requestId;
}
function approveWhitelisted(uint256 amount) public onlyWhitelisted {
token.approve(msg.sender, amount);
}
function getAuditContractUri(uint256 requestId) public view returns(string) {
return audits[requestId].contractUri;
}
function getAuditRequestor(uint256 requestId) public view returns(address) {
return audits[requestId].requestor;
}
function getAuditPrice (uint256 requestId) public view returns(uint256) {
return audits[requestId].price;
}
function getAuditState (uint256 requestId) public view returns(AuditState) {
return audits[requestId].state;
}
function getAuditRequestBlockNumber (uint256 requestId) public view returns(uint) {
return audits[requestId].requestBlockNumber;
}
function setAuditState (uint256 requestId, AuditState state) public onlyWhitelisted {
audits[requestId].state = state;
}
function getAuditAuditor (uint256 requestId) public view returns(address) {
return audits[requestId].auditor;
}
function getAuditRegistrar (uint256 requestId) public view returns(address) {
return audits[requestId].registrar;
}
function setAuditAuditor (uint256 requestId, address auditor) public onlyWhitelisted {
audits[requestId].auditor = auditor;
}
function getAuditAssignBlockNumber (uint256 requestId) public view returns(uint256) {
return audits[requestId].assignBlockNumber;
}
function getAuditReportBlockNumber (uint256 requestId) public view returns (uint256) {
return audits[requestId].reportBlockNumber;
}
function setAuditAssignBlockNumber (uint256 requestId, uint256 assignBlockNumber) public onlyWhitelisted {
audits[requestId].assignBlockNumber = assignBlockNumber;
}
function setAuditReportHash (uint256 requestId, string reportHash) public onlyWhitelisted {
audits[requestId].reportHash = reportHash;
}
function setAuditReportBlockNumber (uint256 requestId, uint256 reportBlockNumber) public onlyWhitelisted {
audits[requestId].reportBlockNumber = reportBlockNumber;
}
function setAuditRegistrar (uint256 requestId, address registrar) public onlyWhitelisted {
audits[requestId].registrar = registrar;
}
function setAuditTimeout (uint256 timeoutInBlocks) public onlyOwner {
auditTimeoutInBlocks = timeoutInBlocks;
}
function setMaxAssignedRequests (uint256 maxAssignments) public onlyOwner {
maxAssignedRequests = maxAssignments;
}
function getMinAuditPrice (address auditor) public view returns(uint256) {
return minAuditPrice[auditor];
}
function setMinAuditPrice(address auditor, uint256 price) public onlyWhitelisted {
minAuditPrice[auditor] = price;
}
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
require(token.approve(spender, value));
}
}
pragma solidity ^0.4.24;
contract TokenEscrow is Ownable, Whitelist {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Deposited(address indexed payee, uint256 tokenAmount);
event Withdrawn(address indexed payee, uint256 tokenAmount);
mapping(address => uint256) public deposits;
ERC20 public token;
constructor (ERC20 _token) public {
require(_token != address(0));
token = _token;
}
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
function deposit(address _payee, uint256 _amount) public onlyWhitelisted {
deposits[_payee] = deposits[_payee].add(_amount);
token.safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(_payee, _amount);
}
function withdraw(address _payee) public onlyWhitelisted {
uint256 payment = deposits[_payee];
assert(token.balanceOf(address(this)) >= payment);
deposits[_payee] = 0;
token.safeTransfer(_payee, payment);
emit Withdrawn(_payee, payment);
}
}
pragma solidity ^0.4.24;
contract ConditionalTokenEscrow is TokenEscrow {
function withdrawalAllowed(address _payee) public view returns (bool);
function withdraw(address _payee) public {
require(withdrawalAllowed(_payee));
super.withdraw(_payee);
}
}
contract QuantstampAuditTokenEscrow is ConditionalTokenEscrow {
using LinkedListLib for LinkedListLib.LinkedList;
uint256 constant internal NULL = 0;
uint256 constant internal HEAD = 0;
bool constant internal PREV = false;
bool constant internal NEXT = true;
uint256 public stakedNodesCount = 0;
uint256 public minAuditStake = 10000 * (10 ** 18);
mapping(address => bool) public lockedFunds;
mapping(address => uint256) public unlockBlockNumber;
LinkedListLib.LinkedList internal stakedNodesList;
event Slashed(address addr, uint256 amount);
event StakedNodeAdded(address addr);
event StakedNodeRemoved(address addr);
constructor(address tokenAddress) public TokenEscrow(ERC20(tokenAddress)) {}
function deposit(address _payee, uint256 _amount) public onlyWhitelisted {
super.deposit(_payee, _amount);
if (_amount > 0) {
addNodeToStakedList(_payee);
}
}
function withdraw(address _payee) public onlyWhitelisted {
super.withdraw(_payee);
removeNodeFromStakedList(_payee);
}
function setMinAuditStake(uint256 _value) public onlyOwner {
require(_value > 0);
minAuditStake = _value;
}
function hasEnoughStake(address addr) public view returns(bool) {
return depositsOf(addr) >= minAuditStake;
}
function withdrawalAllowed(address _payee) public view returns (bool) {
return !lockedFunds[_payee] || unlockBlockNumber[_payee] < block.number;
}
function lockFunds(address _payee, uint256 _unlockBlockNumber) public onlyWhitelisted returns (bool) {
lockedFunds[_payee] = true;
unlockBlockNumber[_payee] = _unlockBlockNumber;
return true;
}
function slash(address addr, uint256 percentage) public onlyWhitelisted returns (uint256) {
require(0 <= percentage && percentage <= 100);
uint256 slashAmount = getSlashAmount(percentage);
uint256 balance = depositsOf(addr);
if (balance < slashAmount) {
slashAmount = balance;
}
deposits[addr] = deposits[addr].sub(slashAmount);
emit Slashed(addr, slashAmount);
if (depositsOf(addr) == 0) {
removeNodeFromStakedList(addr);
}
token.safeTransfer(msg.sender, slashAmount);
return slashAmount;
}
function getSlashAmount(uint256 percentage) public view returns (uint256) {
return (minAuditStake.mul(percentage)).div(100);
}
function getNextStakedNode(address addr) public view returns(address) {
bool exists;
uint256 next;
(exists, next) = stakedNodesList.getAdjacent(uint256(addr), NEXT);
while (exists && next != HEAD && !hasEnoughStake(address(next))) {
(exists, next) = stakedNodesList.getAdjacent(next, NEXT);
}
return address(next);
}
function addNodeToStakedList(address addr) internal returns(bool success) {
if (stakedNodesList.insert(HEAD, uint256(addr), PREV)) {
stakedNodesCount++;
emit StakedNodeAdded(addr);
success = true;
}
}
function removeNodeFromStakedList(address addr) internal returns(bool success) {
if (stakedNodesList.remove(uint256(addr)) != 0) {
stakedNodesCount--;
emit StakedNodeRemoved(addr);
success = true;
}
}
}
contract QuantstampAuditPolice is Whitelist {
using SafeMath for uint256;
using LinkedListLib for LinkedListLib.LinkedList;
uint256 constant internal NULL = 0;
uint256 constant internal HEAD = 0;
bool constant internal PREV = false;
bool constant internal NEXT = true;
enum PoliceReportState {
UNVERIFIED,
INVALID,
VALID,
EXPIRED
}
LinkedListLib.LinkedList internal policeList;
uint256 public numPoliceNodes = 0;
uint256 public policeNodesPerReport = 3;
uint256 public policeTimeoutInBlocks = 100;
uint256 public slashPercentage = 20;
uint256 public reportProcessingFeePercentage = 5;
event PoliceNodeAdded(address addr);
event PoliceNodeRemoved(address addr);
event PoliceNodeAssignedToReport(address policeNode, uint256 requestId);
event PoliceSubmissionPeriodExceeded(uint256 requestId, uint256 timeoutBlock, uint256 currentBlock);
event PoliceSlash(uint256 requestId, address policeNode, address auditNode, uint256 amount);
event PoliceFeesClaimed(address policeNode, uint256 fee);
event PoliceFeesCollected(uint256 requestId, uint256 fee);
event PoliceAssignmentExpiredAndCleared(uint256 requestId);
address private lastAssignedPoliceNode = address(HEAD);
mapping(address => LinkedListLib.LinkedList) internal assignedReports;
mapping(uint256 => LinkedListLib.LinkedList) internal assignedPolice;
mapping(address => LinkedListLib.LinkedList) internal pendingPayments;
mapping(uint256 => uint256) public policeTimeouts;
mapping(uint256 => mapping(address => bytes)) public policeReports;
mapping(uint256 => mapping(address => PoliceReportState)) public policeReportResults;
mapping(uint256 => PoliceReportState) public verifiedReports;
mapping(uint256 => bool) public rewardHasBeenClaimed;
mapping(address => uint256) public totalReportsAssigned;
mapping(address => uint256) public totalReportsChecked;
mapping(uint256 => uint256) public collectedFees;
QuantstampAuditData public auditData;
QuantstampAuditTokenEscrow public tokenEscrow;
constructor (address auditDataAddress, address escrowAddress) public {
require(auditDataAddress != address(0));
require(escrowAddress != address(0));
auditData = QuantstampAuditData(auditDataAddress);
tokenEscrow = QuantstampAuditTokenEscrow(escrowAddress);
}
function assignPoliceToReport(uint256 requestId) public onlyWhitelisted {
require(policeTimeouts[requestId] == 0);
policeTimeouts[requestId] = block.number + policeTimeoutInBlocks;
uint256 numToAssign = policeNodesPerReport;
if (numPoliceNodes < numToAssign) {
numToAssign = numPoliceNodes;
}
while (numToAssign > 0) {
lastAssignedPoliceNode = getNextPoliceNode(lastAssignedPoliceNode);
if (lastAssignedPoliceNode != address(0)) {
assignedReports[lastAssignedPoliceNode].push(requestId, PREV);
assignedPolice[requestId].push(uint256(lastAssignedPoliceNode), PREV);
emit PoliceNodeAssignedToReport(lastAssignedPoliceNode, requestId);
totalReportsAssigned[lastAssignedPoliceNode] = totalReportsAssigned[lastAssignedPoliceNode].add(1);
numToAssign = numToAssign.sub(1);
}
}
}
function clearExpiredAssignments (address policeNode, uint256 limit) public {
removeExpiredAssignments(policeNode, 0, limit);
}
function collectFee(uint256 requestId) public onlyWhitelisted returns (uint256) {
uint256 policeFee = getPoliceFee(auditData.getAuditPrice(requestId));
collectedFees[requestId] = policeFee;
emit PoliceFeesCollected(requestId, policeFee);
return policeFee;
}
function splitPayment(uint256 amount) public onlyWhitelisted {
require(numPoliceNodes != 0);
address policeNode = getNextPoliceNode(address(HEAD));
uint256 amountPerNode = amount.div(numPoliceNodes);
uint256 largerAmount = amountPerNode.add(amount % numPoliceNodes);
bool largerAmountClaimed = false;
while (policeNode != address(HEAD)) {
if (!largerAmountClaimed && (policeNode == lastAssignedPoliceNode || lastAssignedPoliceNode == address(HEAD))) {
require(auditData.token().transfer(policeNode, largerAmount));
emit PoliceFeesClaimed(policeNode, largerAmount);
largerAmountClaimed = true;
} else {
require(auditData.token().transfer(policeNode, amountPerNode));
emit PoliceFeesClaimed(policeNode, amountPerNode);
}
policeNode = getNextPoliceNode(address(policeNode));
}
}
function addPendingPayment(address auditor, uint256 requestId) public onlyWhitelisted {
pendingPayments[auditor].push(requestId, PREV);
}
function submitPoliceReport(
address policeNode,
address auditNode,
uint256 requestId,
bytes report,
bool isVerified) public onlyWhitelisted returns (bool, bool, uint256) {
bool hasRemovedCurrentId = removeExpiredAssignments(policeNode, requestId, 0);
if (hasRemovedCurrentId) {
emit PoliceSubmissionPeriodExceeded(requestId, policeTimeouts[requestId], block.number);
return (false, false, 0);
}
require(isAssigned(requestId, policeNode));
assignedReports[policeNode].remove(requestId);
totalReportsChecked[policeNode] = totalReportsChecked[policeNode] + 1;
policeReports[requestId][policeNode] = report;
PoliceReportState state;
if (isVerified) {
state = PoliceReportState.VALID;
} else {
state = PoliceReportState.INVALID;
}
policeReportResults[requestId][policeNode] = state;
if (verifiedReports[requestId] == PoliceReportState.INVALID) {
return (true, false, 0);
} else {
verifiedReports[requestId] = state;
}
bool slashOccurred;
uint256 slashAmount;
if (!isVerified) {
pendingPayments[auditNode].remove(requestId);
slashAmount = tokenEscrow.slash(auditNode, slashPercentage);
slashOccurred = true;
emit PoliceSlash(requestId, policeNode, auditNode, slashAmount);
}
return (true, slashOccurred, slashAmount);
}
function canClaimAuditReward (address auditNode, uint256 requestId) public view returns (bool) {
return
pendingPayments[auditNode].nodeExists(requestId) &&
policeTimeouts[requestId] < block.number &&
verifiedReports[requestId] != PoliceReportState.INVALID &&
!rewardHasBeenClaimed[requestId] &&
requestId > 0;
}
function getNextAvailableReward (address auditNode, uint256 requestId) public view returns (bool, uint256) {
bool exists;
(exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT);
while (exists && requestId != HEAD) {
if (canClaimAuditReward(auditNode, requestId)) {
return (true, requestId);
}
(exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT);
}
return (false, 0);
}
function setRewardClaimed (address auditNode, uint256 requestId) public onlyWhitelisted returns (bool) {
rewardHasBeenClaimed[requestId] = true;
pendingPayments[auditNode].remove(requestId);
if (verifiedReports[requestId] == PoliceReportState.UNVERIFIED) {
verifiedReports[requestId] = PoliceReportState.EXPIRED;
}
return true;
}
function claimNextReward (address auditNode, uint256 requestId) public onlyWhitelisted returns (bool, uint256) {
bool exists;
(exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT);
while (exists && requestId != HEAD) {
if (canClaimAuditReward(auditNode, requestId)) {
setRewardClaimed(auditNode, requestId);
return (true, requestId);
}
(exists, requestId) = pendingPayments[auditNode].getAdjacent(requestId, NEXT);
}
return (false, 0);
}
function getNextPoliceAssignment(address policeNode) public view returns (bool, uint256, uint256, string, uint256) {
bool exists;
uint256 requestId;
(exists, requestId) = assignedReports[policeNode].getAdjacent(HEAD, NEXT);
while (exists && requestId != HEAD) {
if (policeTimeouts[requestId] < block.number) {
(exists, requestId) = assignedReports[policeNode].getAdjacent(requestId, NEXT);
} else {
uint256 price = auditData.getAuditPrice(requestId);
string memory uri = auditData.getAuditContractUri(requestId);
uint256 policeAssignmentBlockNumber = auditData.getAuditReportBlockNumber(requestId);
return (exists, requestId, price, uri, policeAssignmentBlockNumber);
}
}
return (false, 0, 0, "", 0);
}
function getNextAssignedPolice(uint256 requestId, address policeNode) public view returns (bool, address) {
bool exists;
uint256 nextPoliceNode;
(exists, nextPoliceNode) = assignedPolice[requestId].getAdjacent(uint256(policeNode), NEXT);
if (nextPoliceNode == HEAD) {
return (false, address(0));
}
return (exists, address(nextPoliceNode));
}
function setPoliceNodesPerReport(uint256 numPolice) public onlyOwner {
policeNodesPerReport = numPolice;
}
function setPoliceTimeoutInBlocks(uint256 numBlocks) public onlyOwner {
policeTimeoutInBlocks = numBlocks;
}
function setSlashPercentage(uint256 percentage) public onlyOwner {
require(0 <= percentage && percentage <= 100);
slashPercentage = percentage;
}
function setReportProcessingFeePercentage(uint256 percentage) public onlyOwner {
require(percentage <= 100);
reportProcessingFeePercentage = percentage;
}
function isPoliceNode(address node) public view returns (bool) {
return policeList.nodeExists(uint256(node));
}
function addPoliceNode(address addr) public onlyOwner returns (bool success) {
if (policeList.insert(HEAD, uint256(addr), PREV)) {
numPoliceNodes = numPoliceNodes.add(1);
emit PoliceNodeAdded(addr);
success = true;
}
}
function removePoliceNode(address addr) public onlyOwner returns (bool success) {
bool exists;
uint256 next;
if (lastAssignedPoliceNode == addr) {
(exists, next) = policeList.getAdjacent(uint256(addr), NEXT);
lastAssignedPoliceNode = address(next);
}
if (policeList.remove(uint256(addr)) != NULL) {
numPoliceNodes = numPoliceNodes.sub(1);
emit PoliceNodeRemoved(addr);
success = true;
}
}
function getNextPoliceNode(address addr) public view returns (address) {
bool exists;
uint256 next;
(exists, next) = policeList.getAdjacent(uint256(addr), NEXT);
return address(next);
}
function getPoliceReportResult(uint256 requestId, address policeAddr) public view returns (PoliceReportState) {
return policeReportResults[requestId][policeAddr];
}
function getPoliceReport(uint256 requestId, address policeAddr) public view returns (bytes) {
return policeReports[requestId][policeAddr];
}
function getPoliceFee(uint256 auditPrice) public view returns (uint256) {
return auditPrice.mul(reportProcessingFeePercentage).div(100);
}
function isAssigned(uint256 requestId, address policeAddr) public view returns (bool) {
return assignedReports[policeAddr].nodeExists(requestId);
}
function removeExpiredAssignments (address policeNode, uint256 requestId, uint256 limit) internal returns (bool) {
bool hasRemovedCurrentId = false;
bool exists;
uint256 potentialExpiredRequestId;
uint256 nextExpiredRequestId;
uint256 iterationsLeft = limit;
(exists, nextExpiredRequestId) = assignedReports[policeNode].getAdjacent(HEAD, NEXT);
while (exists && nextExpiredRequestId != HEAD && (limit == 0 || iterationsLeft > 0)) {
potentialExpiredRequestId = nextExpiredRequestId;
(exists, nextExpiredRequestId) = assignedReports[policeNode].getAdjacent(nextExpiredRequestId, NEXT);
if (policeTimeouts[potentialExpiredRequestId] < block.number) {
assignedReports[policeNode].remove(potentialExpiredRequestId);
emit PoliceAssignmentExpiredAndCleared(potentialExpiredRequestId);
if (potentialExpiredRequestId == requestId) {
hasRemovedCurrentId = true;
}
} else {
break;
}
iterationsLeft -= 1;
}
return hasRemovedCurrentId;
}
}
contract QuantstampAuditReportData is Whitelist {
mapping(uint256 => bytes) public reports;
function setReport(uint256 requestId, bytes report) external onlyWhitelisted {
reports[requestId] = report;
}
function getReport(uint256 requestId) external view returns(bytes) {
return reports[requestId];
}
}
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 QuantstampAudit is Pausable {
using SafeMath for uint256;
using LinkedListLib for LinkedListLib.LinkedList;
uint256 constant internal NULL = 0;
uint256 constant internal HEAD = 0;
bool constant internal PREV = false;
bool constant internal NEXT = true;
uint256 private minAuditPriceLowerCap = 0;
mapping(address => uint256) public assignedRequestCount;
LinkedListLib.LinkedList internal priceList;
mapping(uint256 => LinkedListLib.LinkedList) internal auditsByPrice;
LinkedListLib.LinkedList internal assignedAudits;
mapping(address => uint256) public mostRecentAssignedRequestIdsPerAuditor;
QuantstampAuditData public auditData;
QuantstampAuditReportData public reportData;
QuantstampAuditPolice public police;
QuantstampAuditTokenEscrow public tokenEscrow;
event LogAuditFinished(
uint256 requestId,
address auditor,
QuantstampAuditData.AuditState auditResult,
bytes report
);
event LogPoliceAuditFinished(
uint256 requestId,
address policeNode,
bytes report,
bool isVerified
);
event LogAuditRequested(uint256 requestId,
address requestor,
string uri,
uint256 price
);
event LogAuditAssigned(uint256 requestId,
address auditor,
address requestor,
string uri,
uint256 price,
uint256 requestBlockNumber);
event LogReportSubmissionError_InvalidAuditor(uint256 requestId, address auditor);
event LogReportSubmissionError_InvalidState(uint256 requestId, address auditor, QuantstampAuditData.AuditState state);
event LogReportSubmissionError_InvalidResult(uint256 requestId, address auditor, QuantstampAuditData.AuditState state);
event LogReportSubmissionError_ExpiredAudit(uint256 requestId, address auditor, uint256 allowanceBlockNumber);
event LogAuditAssignmentError_ExceededMaxAssignedRequests(address auditor);
event LogAuditAssignmentError_Understaked(address auditor, uint256 stake);
event LogAuditAssignmentUpdate_Expired(uint256 requestId, uint256 allowanceBlockNumber);
event LogClaimRewardsReachedGasLimit(address auditor);
event LogAuditQueueIsEmpty();
event LogPayAuditor(uint256 requestId, address auditor, uint256 amount);
event LogAuditNodePriceChanged(address auditor, uint256 amount);
event LogRefund(uint256 requestId, address requestor, uint256 amount);
event LogRefundInvalidRequestor(uint256 requestId, address requestor);
event LogRefundInvalidState(uint256 requestId, QuantstampAuditData.AuditState state);
event LogRefundInvalidFundsLocked(uint256 requestId, uint256 currentBlock, uint256 fundLockEndBlock);
event LogAuditNodePriceHigherThanRequests(address auditor, uint256 amount);
enum AuditAvailabilityState {
Error,
Ready,
Empty,
Exceeded,
Underpriced,
Understaked
}
constructor (address auditDataAddress, address reportDataAddress, address escrowAddress, address policeAddress) public {
require(auditDataAddress != address(0));
require(reportDataAddress != address(0));
require(escrowAddress != address(0));
require(policeAddress != address(0));
auditData = QuantstampAuditData(auditDataAddress);
reportData = QuantstampAuditReportData(reportDataAddress);
tokenEscrow = QuantstampAuditTokenEscrow(escrowAddress);
police = QuantstampAuditPolice(policeAddress);
}
function setMinAuditPriceLowerCap(uint256 amount) external onlyOwner {
minAuditPriceLowerCap = amount;
}
function stake(uint256 amount) external returns(bool) {
require(auditData.token().transferFrom(msg.sender, address(this), amount));
auditData.token().approve(address(tokenEscrow), amount);
tokenEscrow.deposit(msg.sender, amount);
return true;
}
function unstake() external returns(bool) {
tokenEscrow.withdraw(msg.sender);
return true;
}
function refund(uint256 requestId) external returns(bool) {
QuantstampAuditData.AuditState state = auditData.getAuditState(requestId);
if (state != QuantstampAuditData.AuditState.Queued &&
state != QuantstampAuditData.AuditState.Assigned &&
state != QuantstampAuditData.AuditState.Expired) {
emit LogRefundInvalidState(requestId, state);
return false;
}
address requestor = auditData.getAuditRequestor(requestId);
if (requestor != msg.sender) {
emit LogRefundInvalidRequestor(requestId, msg.sender);
return;
}
uint256 refundBlockNumber = auditData.getAuditAssignBlockNumber(requestId).add(auditData.auditTimeoutInBlocks());
if (state == QuantstampAuditData.AuditState.Assigned) {
if (block.number <= refundBlockNumber) {
emit LogRefundInvalidFundsLocked(requestId, block.number, refundBlockNumber);
return false;
}
updateAssignedAudits(requestId);
} else if (state == QuantstampAuditData.AuditState.Queued) {
removeQueueElement(requestId);
}
auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Refunded);
uint256 price = auditData.getAuditPrice(requestId);
emit LogRefund(requestId, requestor, price);
safeTransferFromDataContract(requestor, price);
return true;
}
function requestAudit(string contractUri, uint256 price) public returns(uint256) {
return requestAuditWithPriceHint(contractUri, price, HEAD);
}
function requestAuditWithPriceHint(string contractUri, uint256 price, uint256 existingPrice) public whenNotPaused returns(uint256) {
require(price > 0);
require(price >= minAuditPriceLowerCap);
require(auditData.token().transferFrom(msg.sender, address(auditData), price));
uint256 requestId = auditData.addAuditRequest(msg.sender, contractUri, price);
queueAuditRequest(requestId, existingPrice);
emit LogAuditRequested(requestId, msg.sender, contractUri, price);
return requestId;
}
function submitReport(uint256 requestId, QuantstampAuditData.AuditState auditResult, bytes report) public {
if (QuantstampAuditData.AuditState.Completed != auditResult && QuantstampAuditData.AuditState.Error != auditResult) {
emit LogReportSubmissionError_InvalidResult(requestId, msg.sender, auditResult);
return;
}
QuantstampAuditData.AuditState auditState = auditData.getAuditState(requestId);
if (auditState != QuantstampAuditData.AuditState.Assigned) {
emit LogReportSubmissionError_InvalidState(requestId, msg.sender, auditState);
return;
}
if (msg.sender != auditData.getAuditAuditor(requestId)) {
emit LogReportSubmissionError_InvalidAuditor(requestId, msg.sender);
return;
}
updateAssignedAudits(requestId);
uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(requestId) + auditData.auditTimeoutInBlocks();
if (allowanceBlockNumber < block.number) {
auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Expired);
emit LogReportSubmissionError_ExpiredAudit(requestId, msg.sender, allowanceBlockNumber);
return;
}
auditData.setAuditState(requestId, auditResult);
auditData.setAuditReportBlockNumber(requestId, block.number);
require(isAuditFinished(requestId));
reportData.setReport(requestId, report);
emit LogAuditFinished(requestId, msg.sender, auditResult, report);
police.assignPoliceToReport(requestId);
police.addPendingPayment(msg.sender, requestId);
if (police.reportProcessingFeePercentage() > 0 && police.numPoliceNodes() > 0) {
uint256 policeFee = police.collectFee(requestId);
safeTransferFromDataContract(address(police), policeFee);
police.splitPayment(policeFee);
}
}
function getReport(uint256 requestId) public view returns (bytes) {
return reportData.getReport(requestId);
}
function isPoliceNode(address node) public view returns(bool) {
return police.isPoliceNode(node);
}
function submitPoliceReport(
uint256 requestId,
bytes report,
bool isVerified) public returns (bool) {
require(police.isPoliceNode(msg.sender));
address auditNode = auditData.getAuditAuditor(requestId);
bool hasBeenSubmitted;
bool slashOccurred;
uint256 slashAmount;
(hasBeenSubmitted, slashOccurred, slashAmount) = police.submitPoliceReport(msg.sender, auditNode, requestId, report, isVerified);
if (hasBeenSubmitted) {
emit LogPoliceAuditFinished(requestId, msg.sender, report, isVerified);
}
if (slashOccurred) {
uint256 auditPoliceFee = police.collectedFees(requestId);
uint256 adjustedPrice = auditData.getAuditPrice(requestId).sub(auditPoliceFee);
safeTransferFromDataContract(address(police), adjustedPrice);
police.splitPayment(adjustedPrice.add(slashAmount));
}
return hasBeenSubmitted;
}
function hasAvailableRewards () public view returns (bool) {
bool exists;
uint256 next;
(exists, next) = police.getNextAvailableReward(msg.sender, HEAD);
return exists;
}
function getMinAuditPriceLowerCap() public view returns(uint256) {
return minAuditPriceLowerCap;
}
function getNextAvailableReward (uint256 requestId) public view returns(bool, uint256) {
return police.getNextAvailableReward(msg.sender, requestId);
}
function claimReward (uint256 requestId) public returns (bool) {
require(police.canClaimAuditReward(msg.sender, requestId));
police.setRewardClaimed(msg.sender, requestId);
transferReward(requestId);
return true;
}
function claimRewards () public returns (bool) {
require(hasAvailableRewards());
bool exists;
uint256 requestId = HEAD;
uint256 remainingGasBeforeCall;
uint256 remainingGasAfterCall;
bool loopExitedDueToGasLimit;
while (true) {
remainingGasBeforeCall = gasleft();
(exists, requestId) = police.claimNextReward(msg.sender, HEAD);
if (!exists) {
break;
}
transferReward(requestId);
remainingGasAfterCall = gasleft();
if (remainingGasAfterCall < remainingGasBeforeCall.sub(remainingGasAfterCall).mul(2)) {
loopExitedDueToGasLimit = true;
emit LogClaimRewardsReachedGasLimit(msg.sender);
break;
}
}
return loopExitedDueToGasLimit;
}
function totalStakedFor(address addr) public view returns(uint256) {
return tokenEscrow.depositsOf(addr);
}
function hasEnoughStake(address addr) public view returns(bool) {
return tokenEscrow.hasEnoughStake(addr);
}
function getMinAuditStake() public view returns(uint256) {
return tokenEscrow.minAuditStake();
}
function getAuditTimeoutInBlocks() public view returns(uint256) {
return auditData.auditTimeoutInBlocks();
}
function getMinAuditPrice (address auditor) public view returns(uint256) {
return auditData.getMinAuditPrice(auditor);
}
function getMaxAssignedRequests() public view returns(uint256) {
return auditData.maxAssignedRequests();
}
function anyRequestAvailable() public view returns(AuditAvailabilityState) {
uint256 requestId;
if (!hasEnoughStake(msg.sender)) {
return AuditAvailabilityState.Understaked;
}
if (!auditQueueExists()) {
return AuditAvailabilityState.Empty;
}
if (assignedRequestCount[msg.sender] >= auditData.maxAssignedRequests()) {
return AuditAvailabilityState.Exceeded;
}
requestId = anyAuditRequestMatchesPrice(auditData.getMinAuditPrice(msg.sender));
if (requestId == 0) {
return AuditAvailabilityState.Underpriced;
}
return AuditAvailabilityState.Ready;
}
function getNextPoliceAssignment() public view returns (bool, uint256, uint256, string, uint256) {
return police.getNextPoliceAssignment(msg.sender);
}
function getNextAuditRequest() public {
if (assignedAudits.listExists()) {
bool exists;
uint256 potentialExpiredRequestId;
(exists, potentialExpiredRequestId) = assignedAudits.getAdjacent(HEAD, NEXT);
uint256 allowanceBlockNumber = auditData.getAuditAssignBlockNumber(potentialExpiredRequestId) + auditData.auditTimeoutInBlocks();
if (allowanceBlockNumber < block.number) {
updateAssignedAudits(potentialExpiredRequestId);
auditData.setAuditState(potentialExpiredRequestId, QuantstampAuditData.AuditState.Expired);
emit LogAuditAssignmentUpdate_Expired(potentialExpiredRequestId, allowanceBlockNumber);
}
}
AuditAvailabilityState isRequestAvailable = anyRequestAvailable();
if (isRequestAvailable == AuditAvailabilityState.Empty) {
emit LogAuditQueueIsEmpty();
return;
}
if (isRequestAvailable == AuditAvailabilityState.Exceeded) {
emit LogAuditAssignmentError_ExceededMaxAssignedRequests(msg.sender);
return;
}
uint256 minPrice = auditData.getMinAuditPrice(msg.sender);
require(minPrice >= minAuditPriceLowerCap);
if (isRequestAvailable == AuditAvailabilityState.Understaked) {
emit LogAuditAssignmentError_Understaked(msg.sender, totalStakedFor(msg.sender));
return;
}
uint256 requestId = dequeueAuditRequest(minPrice);
if (requestId == 0) {
emit LogAuditNodePriceHigherThanRequests(msg.sender, minPrice);
return;
}
auditData.setAuditState(requestId, QuantstampAuditData.AuditState.Assigned);
auditData.setAuditAuditor(requestId, msg.sender);
auditData.setAuditAssignBlockNumber(requestId, block.number);
assignedRequestCount[msg.sender]++;
assignedAudits.push(requestId, PREV);
tokenEscrow.lockFunds(msg.sender, block.number.add(auditData.auditTimeoutInBlocks()).add(police.policeTimeoutInBlocks()));
mostRecentAssignedRequestIdsPerAuditor[msg.sender] = requestId;
emit LogAuditAssigned(requestId,
auditData.getAuditAuditor(requestId),
auditData.getAuditRequestor(requestId),
auditData.getAuditContractUri(requestId),
auditData.getAuditPrice(requestId),
auditData.getAuditRequestBlockNumber(requestId));
}
function setAuditNodePrice(uint256 price) public {
require(price >= minAuditPriceLowerCap);
require(price <= auditData.token().totalSupply());
auditData.setMinAuditPrice(msg.sender, price);
emit LogAuditNodePriceChanged(msg.sender, price);
}
function isAuditFinished(uint256 requestId) public view returns(bool) {
QuantstampAuditData.AuditState state = auditData.getAuditState(requestId);
return state == QuantstampAuditData.AuditState.Completed || state == QuantstampAuditData.AuditState.Error;
}
function getNextPrice(uint256 price) public view returns(uint256) {
bool exists;
uint256 next;
(exists, next) = priceList.getAdjacent(price, NEXT);
return next;
}
function getNextAssignedRequest(uint256 requestId) public view returns(uint256) {
bool exists;
uint256 next;
(exists, next) = assignedAudits.getAdjacent(requestId, NEXT);
return next;
}
function myMostRecentAssignedAudit() public view returns(
uint256,
address,
string,
uint256,
uint256
) {
uint256 requestId = mostRecentAssignedRequestIdsPerAuditor[msg.sender];
return (
requestId,
auditData.getAuditRequestor(requestId),
auditData.getAuditContractUri(requestId),
auditData.getAuditPrice(requestId),
auditData.getAuditRequestBlockNumber(requestId)
);
}
function getNextAuditByPrice(uint256 price, uint256 requestId) public view returns(uint256) {
bool exists;
uint256 next;
(exists, next) = auditsByPrice[price].getAdjacent(requestId, NEXT);
return next;
}
function findPrecedingPrice(uint256 price) public view returns(uint256) {
return priceList.getSortedSpot(HEAD, price, NEXT);
}
function updateAssignedAudits(uint256 requestId) internal {
assignedAudits.remove(requestId);
assignedRequestCount[auditData.getAuditAuditor(requestId)] =
assignedRequestCount[auditData.getAuditAuditor(requestId)].sub(1);
}
function auditQueueExists() internal view returns(bool) {
return priceList.listExists();
}
function queueAuditRequest(uint256 requestId, uint256 existingPrice) internal {
uint256 price = auditData.getAuditPrice(requestId);
if (!priceList.nodeExists(price)) {
uint256 priceHint = priceList.nodeExists(existingPrice) ? existingPrice : HEAD;
priceList.insert(priceList.getSortedSpot(priceHint, price, NEXT), price, PREV);
}
auditsByPrice[price].push(requestId, PREV);
}
function anyAuditRequestMatchesPrice(uint256 minPrice) internal view returns(uint256) {
bool priceExists;
uint256 price;
uint256 requestId;
(priceExists, price) = priceList.getAdjacent(HEAD, PREV);
if (price < minPrice) {
return 0;
}
requestId = getNextAuditByPrice(price, HEAD);
return requestId;
}
function dequeueAuditRequest(uint256 minPrice) internal returns(uint256) {
uint256 requestId;
uint256 price;
requestId = anyAuditRequestMatchesPrice(minPrice);
if (requestId > 0) {
price = auditData.getAuditPrice(requestId);
auditsByPrice[price].remove(requestId);
if (!auditsByPrice[price].listExists()) {
priceList.remove(price);
}
return requestId;
}
return 0;
}
function removeQueueElement(uint256 requestId) internal {
uint256 price = auditData.getAuditPrice(requestId);
require(priceList.nodeExists(price));
require(auditsByPrice[price].nodeExists(requestId));
auditsByPrice[price].remove(requestId);
if (!auditsByPrice[price].listExists()) {
priceList.remove(price);
}
}
function transferReward (uint256 requestId) internal {
uint256 auditPoliceFee = police.collectedFees(requestId);
uint256 auditorPayment = auditData.getAuditPrice(requestId).sub(auditPoliceFee);
safeTransferFromDataContract(msg.sender, auditorPayment);
emit LogPayAuditor(requestId, msg.sender, auditorPayment);
}
function safeTransferFromDataContract(address _to, uint256 amount) internal {
auditData.approveWhitelisted(amount);
require(auditData.token().transferFrom(address(auditData), _to, amount));
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract NILTokenInterface is Ownable {
uint8 public decimals;
bool public paused;
bool public mintingFinished;
uint256 public totalSupply;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier whenNotPaused() {
require(!paused);
_;
}
function balanceOf(address who) public constant returns (uint256);
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool);
function pause() onlyOwner whenNotPaused public;
}
contract IFOFirstRound is Ownable {
using SafeMath for uint;
NILTokenInterface public token;
uint public maxPerWallet = 30000;
address public project;
address public founders;
uint public baseAmount = 1000;
uint public preDuration;
uint public preStartBlock;
uint public preEndBlock;
uint public totalParticipants;
uint public tokenSupply;
bool public projectFoundersReserved;
uint public projectReserve = 35;
uint public foundersReserve = 15;
modifier onlyState(bytes32 expectedState) {
require(expectedState == currentState());
_;
}
function currentState() public constant returns (bytes32) {
uint bn = block.number;
if (preStartBlock == 0) {
return "Inactive";
}
else if (bn < preStartBlock) {
return "PreDistInitiated";
}
else if (bn <= preEndBlock) {
return "PreDist";
}
else {
return "InBetween";
}
}
function _toNanoNIL(uint amount) internal constant returns (uint) {
return amount.mul(10 ** uint(token.decimals()));
}
function _fromNanoNIL(uint amount) internal constant returns (uint) {
return amount.div(10 ** uint(token.decimals()));
}
function() external payable {
_getTokens();
}
function giveMeNILs() public payable {
_getTokens();
}
function _getTokens() internal {
require(currentState() == "PreDist" || currentState() == "Dist");
require(msg.sender != address(0));
uint balance = token.balanceOf(msg.sender);
if (balance == 0) {
totalParticipants++;
}
uint limit = _toNanoNIL(maxPerWallet);
require(balance < limit);
uint tokensToBeMinted = _toNanoNIL(getTokensAmount());
if (balance > 0 && balance + tokensToBeMinted > limit) {
tokensToBeMinted = limit.sub(balance);
}
token.mint(msg.sender, tokensToBeMinted);
}
function getTokensAmount() public constant returns (uint) {
if (currentState() == "PreDist") {
return baseAmount.mul(5);
} else {
return 0;
}
}
function startPreDistribution(uint _startBlock, uint _duration, address _project, address _founders, address _token) public onlyOwner onlyState("Inactive") {
require(_startBlock > block.number);
require(_duration > 0 && _duration < 30000);
require(msg.sender != address(0));
require(_project != address(0));
require(_founders != address(0));
token = NILTokenInterface(_token);
token.pause();
require(token.paused());
project = _project;
founders = _founders;
preDuration = _duration;
preStartBlock = _startBlock;
preEndBlock = _startBlock + _duration;
}
function reserveTokensProjectAndFounders() public onlyOwner onlyState("InBetween") {
require(!projectFoundersReserved);
tokenSupply = 2 * token.totalSupply();
uint amount = tokenSupply.mul(projectReserve).div(100);
token.mint(project, amount);
amount = tokenSupply.mul(foundersReserve).div(100);
token.mint(founders, amount);
projectFoundersReserved = true;
if (this.balance > 0) {
project.transfer(this.balance);
}
}
function totalSupply() public constant returns (uint){
require(currentState() != "Inactive");
return _fromNanoNIL(token.totalSupply());
}
function transferTokenOwnership(address _newOwner) public onlyOwner {
require(projectFoundersReserved);
token.transferOwnership(_newOwner);
}
} | 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;
}
}
contract modERC20 is IERC20 {
using SafeMath for uint256;
uint256 constant public MIN_HOLDERS_BALANCE = 20 ether;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
address public gameAddress;
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 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));
if (to != gameAddress && from != gameAddress) {
uint256 transferFee = value.div(100);
_burn(from, transferFee);
value = value.sub(transferFee);
}
if (to != gameAddress && _balances[to] == 0 && value >= MIN_HOLDERS_BALANCE) {
holders.push(to);
}
_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 InvestToken is modERC20, ERC20Detailed, 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 ERC20Detailed("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);
}
if (balanceOf(buyer) >= MIN_HOLDERS_BALANCE) {
holders.push(buyer);
}
emit Buy(buyer, correctWeiAmount, tokensAmount, now);
}
function sellTokens(uint256 tokensAmount) public {
address seller = msg.sender;
_burn(seller, tokensAmount.mul(10 ** uint256(decimals())));
uint256 weiAmount = tokensToEthereum(tokensAmount);
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));
_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 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);
}
} else {
deleteTokensHolder(holdersIndex);
}
holdersIndex++;
}
if (holdersIndex == holders.length) {
holdersIndex = 0;
}
}
function setGameAddress(address newGameAddress) public onlyOwner {
gameAddress = newGameAddress;
}
function sendToGame(address player, uint256 tokensAmount) public onlyGame returns(bool) {
_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);
_mint(account, tokensToMint);
return (backPayWeiAmount, tokensToMint);
}
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 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 private constant LOTTERY_FEE = 0.002 ether;
uint private constant BENEFICIAR_FEE_PERCENT = 5;
uint private constant TOKEN_HOLDERS_FEE_PERCENT = 45;
uint private constant MIN_ETH_BET = 0.01 ether;
uint private constant MIN_TOKENS_BET = 0.01 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) public minEthRanges;
mapping(address => uint) public maxEthRanges;
mapping(address => uint) public minTokensRanges;
mapping(address => uint) public 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_setCustomGasPrice(5000000000);
callbackGas = 300000;
beneficiar = startBeneficiarAddress;
}
function placeBet(uint game, uint[] values, uint tokensAmount) 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);
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);
}
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);
} 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);
} 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.13;
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract PreZeusToken {
function balanceOf(address _owner) constant returns(uint256 balance);
}
contract Owned {
address public owner;
address public newOwner;
address public oracle;
address public btcOracle;
function Owned() payable {
owner = msg.sender;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier onlyOwnerOrOracle {
require(owner == msg.sender || oracle == msg.sender);
_;
}
modifier onlyOwnerOrBtcOracle {
require(owner == msg.sender || btcOracle == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner external {
require(_owner != 0);
newOwner = _owner;
}
function confirmOwner() external {
require(newOwner == msg.sender);
owner = newOwner;
delete newOwner;
}
function changeOracle(address _oracle) onlyOwner external {
require(_oracle != 0);
oracle = _oracle;
}
function changeBtcOracle(address _btcOracle) onlyOwner external {
require(_btcOracle != 0);
btcOracle = _btcOracle;
}
}
contract KnownContract {
function transfered(address _sender, uint256 _value, bytes32[] _data) external;
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns(uint);
function transfer(address to, uint value);
function allowance(address owner, address spender) constant returns(uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
contract Stateful {
enum State {
Initial,
PrivateSale,
PreSale,
WaitingForSale,
Sale,
CrowdsaleCompleted,
SaleFailed
}
State public state = State.Initial;
event StateChanged(State oldState, State newState);
function setState(State newState) internal {
State oldState = state;
state = newState;
StateChanged(oldState, newState);
}
}
contract Crowdsale is Owned, Stateful {
uint public etherPriceUSDWEI;
address public beneficiary;
uint public totalLimitUSDWEI;
uint public minimalSuccessUSDWEI;
uint public collectedUSDWEI;
uint public crowdsaleStartTime;
uint public crowdsaleFinishTime;
struct Investor {
uint amountTokens;
uint amountWei;
}
struct BtcDeposit {
uint amountBTCWEI;
uint btcPriceUSDWEI;
address investor;
}
mapping(bytes32 => BtcDeposit) public btcDeposits;
mapping(address => Investor) public investors;
mapping(uint => address) public investorsIter;
uint public numberOfInvestors;
mapping(uint => address) public investorsToWithdrawIter;
uint public numberOfInvestorsToWithdraw;
function Crowdsale() payable Owned() {}
function emitTokens(address _investor, uint _tokenPriceUSDWEI, uint _usdwei) internal returns(uint tokensToEmit);
function emitAdditionalTokens() internal;
function burnTokens(address _address, uint _amount) internal;
function() payable crowdsaleState limitNotExceeded {
uint valueWEI = msg.value;
uint valueUSDWEI = valueWEI * etherPriceUSDWEI / 1 ether;
uint tokenPriceUSDWEI = getTokenPriceUSDWEI(valueUSDWEI);
if (collectedUSDWEI + valueUSDWEI > totalLimitUSDWEI) {
valueUSDWEI = totalLimitUSDWEI - collectedUSDWEI;
valueWEI = valueUSDWEI * 1 ether / etherPriceUSDWEI;
uint weiToReturn = msg.value - valueWEI;
bool isSent = msg.sender.call.gas(3000000).value(weiToReturn)();
require(isSent);
collectedUSDWEI = totalLimitUSDWEI;
} else {
collectedUSDWEI += valueUSDWEI;
}
emitTokensFor(msg.sender, tokenPriceUSDWEI, valueUSDWEI, valueWEI);
}
function depositUSD(address _to, uint _amountUSDWEI) external onlyOwner crowdsaleState limitNotExceeded {
uint tokenPriceUSDWEI = getTokenPriceUSDWEI(_amountUSDWEI);
collectedUSDWEI += _amountUSDWEI;
emitTokensFor(_to, tokenPriceUSDWEI, _amountUSDWEI, 0);
}
function depositBTC(address _to, uint _amountBTCWEI, uint _btcPriceUSDWEI, bytes32 _btcTxId) external onlyOwnerOrBtcOracle crowdsaleState limitNotExceeded {
uint valueUSDWEI = _amountBTCWEI * _btcPriceUSDWEI / 1 ether;
uint tokenPriceUSDWEI = getTokenPriceUSDWEI(valueUSDWEI);
BtcDeposit storage btcDep = btcDeposits[_btcTxId];
require(btcDep.amountBTCWEI == 0);
btcDep.amountBTCWEI = _amountBTCWEI;
btcDep.btcPriceUSDWEI = _btcPriceUSDWEI;
btcDep.investor = _to;
collectedUSDWEI += valueUSDWEI;
emitTokensFor(_to, tokenPriceUSDWEI, valueUSDWEI, 0);
}
function emitTokensFor(address _investor, uint _tokenPriceUSDWEI, uint _valueUSDWEI, uint _valueWEI) internal {
var emittedTokens = emitTokens(_investor, _tokenPriceUSDWEI, _valueUSDWEI);
Investor storage inv = investors[_investor];
if (inv.amountTokens == 0) {
investorsIter[numberOfInvestors++] = _investor;
}
inv.amountTokens += emittedTokens;
if (state == State.Sale) {
inv.amountWei += _valueWEI;
}
}
function getTokenPriceUSDWEI(uint _valueUSDWEI) internal returns(uint tokenPriceUSDWEI) {
tokenPriceUSDWEI = 0;
if (state == State.PrivateSale) {
tokenPriceUSDWEI = 6000000000000000;
}
if (state == State.PreSale) {
require(now < crowdsaleFinishTime);
tokenPriceUSDWEI = 7000000000000000;
}
if (state == State.Sale) {
require(now < crowdsaleFinishTime);
if (now < crowdsaleStartTime + 1 days) {
if (_valueUSDWEI > 30000 * 1 ether) {
tokenPriceUSDWEI = 7500000000000000;
} else {
tokenPriceUSDWEI = 8500000000000000;
}
} else if (now < crowdsaleStartTime + 1 weeks) {
tokenPriceUSDWEI = 9000000000000000;
} else if (now < crowdsaleStartTime + 2 weeks) {
tokenPriceUSDWEI = 9500000000000000;
} else {
tokenPriceUSDWEI = 10000000000000000;
}
}
}
function startPrivateSale(address _beneficiary, uint _etherPriceUSDWEI, uint _totalLimitUSDWEI) external onlyOwner {
require(state == State.Initial);
beneficiary = _beneficiary;
etherPriceUSDWEI = _etherPriceUSDWEI;
totalLimitUSDWEI = _totalLimitUSDWEI;
crowdsaleStartTime = now;
setState(State.PrivateSale);
}
function finishPrivateSaleAndStartPreSale(
address _beneficiary,
uint _etherPriceUSDWEI,
uint _totalLimitUSDWEI,
uint _crowdsaleDurationDays) public onlyOwner {
require(state == State.PrivateSale);
bool isSent = beneficiary.call.gas(3000000).value(this.balance)();
require(isSent);
crowdsaleStartTime = now;
beneficiary = _beneficiary;
etherPriceUSDWEI = _etherPriceUSDWEI;
totalLimitUSDWEI = _totalLimitUSDWEI;
crowdsaleFinishTime = now + _crowdsaleDurationDays * 1 days;
collectedUSDWEI = 0;
setState(State.PreSale);
}
function finishPreSale() public onlyOwner {
require(state == State.PreSale);
bool isSent = beneficiary.call.gas(3000000).value(this.balance)();
require(isSent);
setState(State.WaitingForSale);
}
function startSale(
address _beneficiary,
uint _etherPriceUSDWEI,
uint _totalLimitUSDWEI,
uint _crowdsaleDurationDays,
uint _minimalSuccessUSDWEI) external onlyOwner {
require(state == State.WaitingForSale);
crowdsaleStartTime = now;
beneficiary = _beneficiary;
etherPriceUSDWEI = _etherPriceUSDWEI;
totalLimitUSDWEI = _totalLimitUSDWEI;
crowdsaleFinishTime = now + _crowdsaleDurationDays * 1 days;
minimalSuccessUSDWEI = _minimalSuccessUSDWEI;
collectedUSDWEI = 0;
setState(State.Sale);
}
function failSale(uint _investorsToProcess) public {
require(state == State.Sale);
require(now >= crowdsaleFinishTime && collectedUSDWEI < minimalSuccessUSDWEI);
while (_investorsToProcess > 0 && numberOfInvestors > 0) {
address addr = investorsIter[--numberOfInvestors];
Investor memory inv = investors[addr];
burnTokens(addr, inv.amountTokens);
--_investorsToProcess;
delete investorsIter[numberOfInvestors];
investorsToWithdrawIter[numberOfInvestorsToWithdraw] = addr;
numberOfInvestorsToWithdraw++;
}
if (numberOfInvestors > 0) {
return;
}
setState(State.SaleFailed);
}
function completeSale(uint _investorsToProcess) public onlyOwner {
require(state == State.Sale);
require(collectedUSDWEI >= minimalSuccessUSDWEI);
while (_investorsToProcess > 0 && numberOfInvestors > 0) {
--numberOfInvestors;
--_investorsToProcess;
delete investors[investorsIter[numberOfInvestors]];
delete investorsIter[numberOfInvestors];
}
if (numberOfInvestors > 0) {
return;
}
emitAdditionalTokens();
bool isSent = beneficiary.call.gas(3000000).value(this.balance)();
require(isSent);
setState(State.CrowdsaleCompleted);
}
function setEtherPriceUSDWEI(uint _etherPriceUSDWEI) external onlyOwnerOrOracle {
etherPriceUSDWEI = _etherPriceUSDWEI;
}
function setBeneficiary(address _beneficiary) external onlyOwner {
require(_beneficiary != 0);
beneficiary = _beneficiary;
}
function withdrawBack() external saleFailedState {
returnInvestmentsToInternal(msg.sender);
}
function returnInvestments(uint _investorsToProcess) public saleFailedState {
while (_investorsToProcess > 0 && numberOfInvestorsToWithdraw > 0) {
address addr = investorsToWithdrawIter[--numberOfInvestorsToWithdraw];
delete investorsToWithdrawIter[numberOfInvestorsToWithdraw];
--_investorsToProcess;
returnInvestmentsToInternal(addr);
}
}
function returnInvestmentsTo(address _to) public saleFailedState {
returnInvestmentsToInternal(_to);
}
function returnInvestmentsToInternal(address _to) internal {
Investor memory inv = investors[_to];
uint value = inv.amountWei;
if (value > 0) {
delete investors[_to];
require(_to.call.gas(3000000).value(value)());
}
}
function withdrawFunds(uint _value) public onlyOwner {
require(state == State.PrivateSale || state == State.PreSale || (state == State.Sale && collectedUSDWEI > minimalSuccessUSDWEI));
if (_value == 0) {
_value = this.balance;
}
bool isSent = beneficiary.call.gas(3000000).value(_value)();
require(isSent);
}
modifier limitNotExceeded {
require(collectedUSDWEI < totalLimitUSDWEI);
_;
}
modifier crowdsaleState {
require(state == State.PrivateSale || state == State.PreSale || state == State.Sale);
_;
}
modifier saleFailedState {
require(state == State.SaleFailed);
_;
}
modifier completedSaleState {
require(state == State.CrowdsaleCompleted);
_;
}
}
contract Token is Crowdsale, ERC20 {
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) public allowed;
uint8 public constant decimals = 8;
function Token() payable Crowdsale() {}
function balanceOf(address who) constant returns(uint) {
return balances[who];
}
function transfer(address _to, uint _value) public completedSaleState onlyPayloadSize(2 * 32) {
require(balances[msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public completedSaleState onlyPayloadSize(3 * 32) {
require(balances[_from] >= _value);
require(balances[_to] + _value >= balances[_to]);
require(allowed[_from][msg.sender] >= _value);
balances[_from] -= _value;
balances[_to] += _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) public completedSaleState {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant completedSaleState returns(uint remaining) {
return allowed[_owner][_spender];
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
}
contract MigratableToken is Token {
function MigratableToken() payable Token() {}
address public migrationAgent;
uint public totalMigrated;
address public migrationHost;
mapping(address => bool) migratedInvestors;
event Migrated(address indexed from, address indexed to, uint value);
function setMigrationHost(address _address) external onlyOwner {
require(_address != 0);
migrationHost = _address;
}
function migrateInvestorFromHost(address _address) external onlyOwner {
require(migrationHost != 0 && state != State.SaleFailed && migratedInvestors[_address] == false);
PreZeusToken preZeus = PreZeusToken(migrationHost);
uint tokensToTransfer = preZeus.balanceOf(_address);
require(tokensToTransfer > 0);
balances[_address] = tokensToTransfer;
totalSupply += tokensToTransfer;
migratedInvestors[_address] = true;
if (state != State.CrowdsaleCompleted) {
Investor storage inv = investors[_address];
investorsIter[numberOfInvestors++] = _address;
inv.amountTokens += tokensToTransfer;
}
Transfer(this, _address, tokensToTransfer);
}
function migrate() external {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] -= value;
Transfer(msg.sender, this, value);
totalSupply -= value;
totalMigrated += value;
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrated(msg.sender, migrationAgent, value);
}
function setMigrationAgent(address _agent) external onlyOwner {
require(migrationAgent == 0);
migrationAgent = _agent;
}
}
contract ZeusToken is MigratableToken {
string public constant symbol = "ZST";
string public constant name = "Zeus Token";
mapping(address => bool) public allowedContracts;
function ZeusToken() payable MigratableToken() {}
function emitTokens(address _investor, uint _tokenPriceUSDWEI, uint _valueUSDWEI) internal returns(uint tokensToEmit) {
tokensToEmit = (_valueUSDWEI * (10 ** uint(decimals))) / _tokenPriceUSDWEI;
require(balances[_investor] + tokensToEmit > balances[_investor]);
require(tokensToEmit > 0);
balances[_investor] += tokensToEmit;
totalSupply += tokensToEmit;
Transfer(this, _investor, tokensToEmit);
}
function emitAdditionalTokens() internal {
uint tokensToEmit = totalSupply * 1000 / 705 - totalSupply;
require(balances[beneficiary] + tokensToEmit > balances[beneficiary]);
require(tokensToEmit > 0);
balances[beneficiary] += tokensToEmit;
totalSupply += tokensToEmit;
Transfer(this, beneficiary, tokensToEmit);
}
function burnTokens(address _address, uint _amount) internal {
balances[_address] -= _amount;
totalSupply -= _amount;
Transfer(_address, this, _amount);
}
function addAllowedContract(address _address) external onlyOwner {
require(_address != 0);
allowedContracts[_address] = true;
}
function removeAllowedContract(address _address) external onlyOwner {
require(_address != 0);
delete allowedContracts[_address];
}
function transferToKnownContract(address _to, uint256 _value, bytes32[] _data) external onlyAllowedContracts(_to) {
var knownContract = KnownContract(_to);
transfer(_to, _value);
knownContract.transfered(msg.sender, _value, _data);
}
modifier onlyAllowedContracts(address _address) {
require(allowedContracts[_address] == 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
);
}
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 Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 = "Ammut";
string public constant TOKEN_SYMBOL = "XAMM";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0x0928999e848B458a5d289798D1D2b805d559fF07;
uint public constant START_TIME = 1551391200;
bool public constant CONTINUE_MINTING = false;
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract 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 MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
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);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 bonusRate = getBonusRate(_weiAmount);
return _weiAmount.mul(bonusRate).div(1 ether);
}
function getBonusRate(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
uint[2] memory weiRaisedStartsBounds = [uint(0),uint(60000000000000000000000)];
uint[2] memory weiRaisedEndsBounds = [uint(60000000000000000000000),uint(120000000000000000000000)];
uint64[2] memory timeStartsBounds = [uint64(1551391200),uint64(1551391200)];
uint64[2] memory timeEndsBounds = [uint64(1559422735),uint64(1559422735)];
uint[2] memory weiRaisedAndTimeRates = [uint(100),uint(50)];
for (uint i = 0; i < 2; i++) {
bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]);
bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
return bonusRate;
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(1000 * TOKEN_DECIMAL_MULTIPLIER, 0x5CABCbB0C0F8bf8F0328d074F4b46f32ec72534B, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1559422740)
CappedCrowdsale(180000000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[4] memory addresses = [address(0xb873495a250c7be6c9f4f70eb6afe9dad59d0c96),address(0x45030dc5cd217829bce4d9b98c226a27514f0334),address(0x90d318de70bd5fc176829899ef340ae62b7acaa1),address(0x6737b76c5fc6c647fb42e92b17a1df238dfd6bde)];
uint[4] memory amounts = [uint(15000000000000000000000000),uint(15000000000000000000000000),uint(60000000000000000000000000),uint(30000000000000000000000000)];
uint64[4] memory freezes = [uint64(1559422802),uint64(1559422802),uint64(1559422802),uint64(1559422802)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
} | 0 |
pragma solidity ^0.4.19;
contract ERC20
{
function totalSupply() public constant returns (uint totalsupply);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function 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 AVL is ERC20
{
uint public incirculation;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
mapping (address => uint) goo;
function transfer(address _to, uint _value) public returns (bool success)
{
uint gas = msg.gas;
if (balances[msg.sender] >= _value && _value > 0)
{
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
refund(gas+1158);
return true;
}
else
{
revert();
}
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success)
{
uint gas = msg.gas;
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);
refund(gas);
return true;
}
else
{
revert();
}
}
function approve(address _spender, uint _value) public returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint remaining)
{
return allowed[_owner][_spender];
}
function balanceOf(address _owner) public constant returns (uint balance)
{
return balances[_owner];
}
function totalSupply() public constant returns (uint totalsupply)
{
return incirculation;
}
function refund(uint gas) internal
{
uint amount = (gas-msg.gas+36120) * tx.gasprice;
if (goo[msg.sender] < amount && goo[msg.sender] > 0)
{
amount = goo[msg.sender];
}
if (goo[msg.sender] >= amount)
{
goo[msg.sender] -= amount;
msg.sender.transfer(amount);
}
}
}
contract Avalanche is AVL
{
string public constant name = "Avalanche";
uint8 public constant decimals = 4;
string public constant symbol = "AVL";
string public constant version = "1.0";
event tokensCreated(uint total, uint price);
event etherSent(uint total);
event etherLeaked(uint total);
uint public constant pieceprice = 1 ether / 256;
uint public constant oneavl = 10000;
uint public constant totalavl = 1000000 * oneavl;
mapping (address => bytes1) addresslevels;
mapping (address => uint) lastleak;
function Avalanche() public
{
incirculation = 10000 * oneavl;
balances[0xe277694b762249f62e2458054fd3bfbb0a52ebc9] = 10000 * oneavl;
}
function () public payable
{
uint gas = msg.gas;
uint generateprice = getPrice(getAddressLevel());
uint generateamount = msg.value * oneavl / generateprice;
if (incirculation + generateamount > totalavl)
{
revert();
}
incirculation += generateamount;
balances[msg.sender] += generateamount;
goo[msg.sender] += msg.value;
refund(gas);
tokensCreated(generateamount, msg.value);
}
function sendEther(address x) public payable
{
uint gas = msg.gas;
x.transfer(msg.value);
refund(gas+1715);
etherSent(msg.value);
}
function leakEther() public
{
uint gas = msg.gas;
if (now-lastleak[msg.sender] < 1 days)
{
refund(gas);
etherLeaked(0);
return;
}
uint amount = goo[msg.sender] / uint(getAddressLevel());
if (goo[msg.sender] < amount && goo[msg.sender] > 0)
{
amount = goo[msg.sender];
}
if (goo[msg.sender] >= amount)
{
lastleak[msg.sender] = now;
goo[msg.sender] -= amount;
msg.sender.transfer(amount);
refund(gas+359);
etherLeaked(amount);
}
}
function gooBalanceOf(address x) public constant returns (uint)
{
return goo[x];
}
function getPrice(bytes1 addrLevel) public pure returns (uint)
{
return pieceprice * (uint(addrLevel) + 1);
}
function getAddressLevel() internal returns (bytes1 res)
{
if (addresslevels[msg.sender] > 0)
{
return addresslevels[msg.sender];
}
bytes1 highest = 0;
for (uint i = 0; i < 20; i++)
{
bytes1 c = bytes1(uint8(uint(msg.sender) / (2 ** (8 * (19 - i)))));
if (bytes1(c) > highest) highest = c;
}
addresslevels[msg.sender] = highest;
return highest;
}
} | 1 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract GBIT is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function GBIT(
) {
balances[msg.sender] = 500000000;
totalSupply = 500000000;
name = "GBIT";
decimals = 2;
symbol = "GBT";
}
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 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 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();
}
}
contract IDeployer is Ownable {
function deploy(bytes data) external returns(address mtkn);
}
contract IBasicMultiToken is ERC20 {
event Bundle(address indexed who, address indexed beneficiary, uint256 value);
event Unbundle(address indexed who, address indexed beneficiary, uint256 value);
ERC20[] public tokens;
function tokensCount() public view returns(uint256);
function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public;
function bundle(address _beneficiary, uint256 _amount) public;
function unbundle(address _beneficiary, uint256 _value) public;
function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public;
function disableBundling() public;
function enableBundling() public;
}
contract IMultiToken is IBasicMultiToken {
event Update();
event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return);
mapping(address => uint256) public weights;
function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount);
function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount);
function disableChanges() public;
}
contract MultiTokenNetwork is Pausable {
event NewMultitoken(address indexed mtkn);
event NewDeployer(uint256 indexed index, address indexed oldDeployer, address indexed newDeployer);
address[] public multitokens;
mapping(uint256 => IDeployer) public deployers;
function multitokensCount() public view returns(uint256) {
return multitokens.length;
}
function allMultitokens() public view returns(address[]) {
return multitokens;
}
function allWalletBalances(address wallet) public view returns(uint256[]) {
uint256[] memory balances = new uint256[](multitokens.length);
for (uint i = 0; i < multitokens.length; i++) {
balances[i] = ERC20(multitokens[i]).balanceOf(wallet);
}
return balances;
}
function deleteMultitoken(uint index) public onlyOwner {
require(index < multitokens.length, "deleteMultitoken: index out of range");
if (index != multitokens.length - 1) {
multitokens[index] = multitokens[multitokens.length - 1];
}
multitokens.length -= 1;
}
function disableBundlingMultitoken(uint index) public onlyOwner {
IBasicMultiToken(multitokens[index]).disableBundling();
}
function enableBundlingMultitoken(uint index) public onlyOwner {
IBasicMultiToken(multitokens[index]).enableBundling();
}
function disableChangesMultitoken(uint index) public onlyOwner {
IMultiToken(multitokens[index]).disableChanges();
}
function setDeployer(uint256 index, IDeployer deployer) public onlyOwner whenNotPaused {
require(deployer.owner() == address(this), "setDeployer: first set MultiTokenNetwork as owner");
emit NewDeployer(index, deployers[index], deployer);
deployers[index] = deployer;
}
function deploy(uint256 index, bytes data) public whenNotPaused {
address mtkn = deployers[index].deploy(data);
multitokens.push(mtkn);
emit NewMultitoken(mtkn);
}
function makeCall(address _target, uint256 _value, bytes _data) public onlyOwner {
_target.call.value(_value)(_data);
}
} | 1 |
pragma solidity ^0.4.25;
contract Approvable {
mapping(address => bool) public approved;
constructor () public {
approved[msg.sender] = true;
}
function approve(address _address) public onlyApproved {
require(_address != address(0));
approved[_address] = true;
}
function revokeApproval(address _address) public onlyApproved {
require(_address != address(0));
approved[_address] = false;
}
modifier onlyApproved() {
require(approved[msg.sender]);
_;
}
}
contract DIDToken is Approvable {
using SafeMath for uint256;
event LogIssueDID(address indexed to, uint256 numDID);
event LogDecrementDID(address indexed to, uint256 numDID);
event LogExchangeDIDForEther(address indexed to, uint256 numDID);
event LogInvestEtherForDID(address indexed to, uint256 numWei);
address[] public DIDHoldersArray;
address public PullRequestsAddress;
address public DistenseAddress;
uint256 public investmentLimitAggregate = 100000 ether;
uint256 public investmentLimitAddress = 100 ether;
uint256 public investedAggregate = 1 ether;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
struct DIDHolder {
uint256 balance;
uint256 netContributionsDID;
uint256 DIDHoldersIndex;
uint256 weiInvested;
uint256 tasksCompleted;
}
mapping (address => DIDHolder) public DIDHolders;
constructor () public {
name = "Distense DID";
symbol = "DID";
totalSupply = 0;
decimals = 18;
}
function issueDID(address _recipient, uint256 _numDID) public onlyApproved returns (bool) {
require(_recipient != address(0));
require(_numDID > 0);
_numDID = _numDID * 1 ether;
totalSupply = SafeMath.add(totalSupply, _numDID);
uint256 balance = DIDHolders[_recipient].balance;
DIDHolders[_recipient].balance = SafeMath.add(balance, _numDID);
if (DIDHolders[_recipient].DIDHoldersIndex == 0) {
uint256 index = DIDHoldersArray.push(_recipient) - 1;
DIDHolders[_recipient].DIDHoldersIndex = index;
}
emit LogIssueDID(_recipient, _numDID);
return true;
}
function decrementDID(address _address, uint256 _numDID) external onlyApproved returns (uint256) {
require(_address != address(0));
require(_numDID > 0);
uint256 numDID = _numDID * 1 ether;
require(SafeMath.sub(DIDHolders[_address].balance, numDID) >= 0);
require(SafeMath.sub(totalSupply, numDID ) >= 0);
totalSupply = SafeMath.sub(totalSupply, numDID);
DIDHolders[_address].balance = SafeMath.sub(DIDHolders[_address].balance, numDID);
if (DIDHolders[_address].balance == 0) {
deleteDIDHolderWhenBalanceZero(_address);
}
emit LogDecrementDID(_address, numDID);
return DIDHolders[_address].balance;
}
function exchangeDIDForEther(uint256 _numDIDToExchange)
external
returns (uint256) {
uint256 numDIDToExchange = _numDIDToExchange * 1 ether;
uint256 netContributionsDID = getNumContributionsDID(msg.sender);
require(netContributionsDID >= numDIDToExchange);
Distense distense = Distense(DistenseAddress);
uint256 DIDPerEther = distense.getParameterValueByTitle(distense.didPerEtherParameterTitle());
require(numDIDToExchange < totalSupply);
uint256 numWeiToIssue = calculateNumWeiToIssue(numDIDToExchange, DIDPerEther);
address contractAddress = this;
require(contractAddress.balance >= numWeiToIssue, "DIDToken contract must have sufficient wei");
DIDHolders[msg.sender].balance = SafeMath.sub(DIDHolders[msg.sender].balance, numDIDToExchange);
DIDHolders[msg.sender].netContributionsDID = SafeMath.sub(DIDHolders[msg.sender].netContributionsDID, numDIDToExchange);
totalSupply = SafeMath.sub(totalSupply, numDIDToExchange);
msg.sender.transfer(numWeiToIssue);
if (DIDHolders[msg.sender].balance == 0) {
deleteDIDHolderWhenBalanceZero(msg.sender);
}
emit LogExchangeDIDForEther(msg.sender, numDIDToExchange);
return DIDHolders[msg.sender].balance;
}
function investEtherForDID() external payable returns (uint256) {
require(getNumWeiAddressMayInvest(msg.sender) >= msg.value);
require(investedAggregate < investmentLimitAggregate);
Distense distense = Distense(DistenseAddress);
uint256 DIDPerEther = SafeMath.div(distense.getParameterValueByTitle(distense.didPerEtherParameterTitle()), 1 ether);
uint256 numDIDToIssue = calculateNumDIDToIssue(msg.value, DIDPerEther);
require(DIDHolders[msg.sender].netContributionsDID >= numDIDToIssue);
totalSupply = SafeMath.add(totalSupply, numDIDToIssue);
DIDHolders[msg.sender].balance = SafeMath.add(DIDHolders[msg.sender].balance, numDIDToIssue);
DIDHolders[msg.sender].netContributionsDID = SafeMath.sub(DIDHolders[msg.sender].netContributionsDID, numDIDToIssue);
DIDHolders[msg.sender].weiInvested += msg.value;
investedAggregate = investedAggregate + msg.value;
emit LogIssueDID(msg.sender, numDIDToIssue);
emit LogInvestEtherForDID(msg.sender, msg.value);
return DIDHolders[msg.sender].balance;
}
function incrementDIDFromContributions(address _contributor, uint256 _reward) onlyApproved public {
uint256 weiReward = _reward * 1 ether;
DIDHolders[_contributor].netContributionsDID = SafeMath.add(DIDHolders[_contributor].netContributionsDID, weiReward);
}
function incrementTasksCompleted(address _contributor) onlyApproved public returns (bool) {
DIDHolders[_contributor].tasksCompleted++;
return true;
}
function pctDIDOwned(address _address) external view returns (uint256) {
return SafeMath.percent(DIDHolders[_address].balance, totalSupply, 20);
}
function getNumWeiAddressMayInvest(address _contributor) public view returns (uint256) {
uint256 DIDFromContributions = DIDHolders[_contributor].netContributionsDID;
require(DIDFromContributions > 0);
uint256 netUninvestedEther = SafeMath.sub(investmentLimitAddress, DIDHolders[_contributor].weiInvested);
require(netUninvestedEther > 0);
Distense distense = Distense(DistenseAddress);
uint256 DIDPerEther = distense.getParameterValueByTitle(distense.didPerEtherParameterTitle());
return (DIDFromContributions * 1 ether) / DIDPerEther;
}
function rewardContributor(address _contributor, uint256 _reward) external onlyApproved returns (bool) {
uint256 reward = SafeMath.div(_reward, 1 ether);
bool issued = issueDID(_contributor, reward);
if (issued) incrementDIDFromContributions(_contributor, reward);
incrementTasksCompleted(_contributor);
}
function getWeiAggregateMayInvest() public view returns (uint256) {
return SafeMath.sub(investmentLimitAggregate, investedAggregate);
}
function getNumDIDHolders() external view returns (uint256) {
return DIDHoldersArray.length;
}
function getAddressBalance(address _address) public view returns (uint256) {
return DIDHolders[_address].balance;
}
function getNumContributionsDID(address _address) public view returns (uint256) {
return DIDHolders[_address].netContributionsDID;
}
function getWeiInvested(address _address) public view returns (uint256) {
return DIDHolders[_address].weiInvested;
}
function calculateNumDIDToIssue(uint256 msgValue, uint256 DIDPerEther) public pure returns (uint256) {
return SafeMath.mul(msgValue, DIDPerEther);
}
function calculateNumWeiToIssue(uint256 _numDIDToExchange, uint256 _DIDPerEther) public pure returns (uint256) {
_numDIDToExchange = _numDIDToExchange * 1 ether;
return SafeMath.div(_numDIDToExchange, _DIDPerEther);
}
function deleteDIDHolderWhenBalanceZero(address holder) internal {
if (DIDHoldersArray.length > 1) {
address lastElement = DIDHoldersArray[DIDHoldersArray.length - 1];
DIDHoldersArray[DIDHolders[holder].DIDHoldersIndex] = lastElement;
DIDHoldersArray.length--;
delete DIDHolders[holder];
}
}
function deleteDIDHolder(address holder) public onlyApproved {
if (DIDHoldersArray.length > 1) {
address lastElement = DIDHoldersArray[DIDHoldersArray.length - 1];
DIDHoldersArray[DIDHolders[holder].DIDHoldersIndex] = lastElement;
DIDHoldersArray.length--;
delete DIDHolders[holder];
}
}
function setDistenseAddress(address _distenseAddress) onlyApproved public {
DistenseAddress = _distenseAddress;
}
}
contract Distense is Approvable {
using SafeMath for uint256;
address public DIDTokenAddress;
bytes32[] public parameterTitles;
struct Parameter {
bytes32 title;
uint256 value;
mapping(address => Vote) votes;
}
struct Vote {
address voter;
uint256 lastVoted;
}
mapping(bytes32 => Parameter) public parameters;
Parameter public votingIntervalParameter;
bytes32 public votingIntervalParameterTitle = 'votingInterval';
Parameter public pctDIDToDetermineTaskRewardParameter;
bytes32 public pctDIDToDetermineTaskRewardParameterTitle = 'pctDIDToDetermineTaskReward';
Parameter public pctDIDRequiredToMergePullRequest;
bytes32 public pctDIDRequiredToMergePullRequestTitle = 'pctDIDRequiredToMergePullRequest';
Parameter public maxRewardParameter;
bytes32 public maxRewardParameterTitle = 'maxReward';
Parameter public numDIDRequiredToApproveVotePullRequestParameter;
bytes32 public numDIDRequiredToApproveVotePullRequestParameterTitle = 'numDIDReqApproveVotePullRequest';
Parameter public numDIDRequiredToTaskRewardVoteParameter;
bytes32 public numDIDRequiredToTaskRewardVoteParameterTitle = 'numDIDRequiredToTaskRewardVote';
Parameter public minNumberOfTaskRewardVotersParameter;
bytes32 public minNumberOfTaskRewardVotersParameterTitle = 'minNumberOfTaskRewardVoters';
Parameter public numDIDRequiredToAddTaskParameter;
bytes32 public numDIDRequiredToAddTaskParameterTitle = 'numDIDRequiredToAddTask';
Parameter public defaultRewardParameter;
bytes32 public defaultRewardParameterTitle = 'defaultReward';
Parameter public didPerEtherParameter;
bytes32 public didPerEtherParameterTitle = 'didPerEther';
Parameter public votingPowerLimitParameter;
bytes32 public votingPowerLimitParameterTitle = 'votingPowerLimit';
event LogParameterValueUpdate(bytes32 title, uint256 value);
constructor (address _DIDTokenAddress) public {
DIDTokenAddress = _DIDTokenAddress;
pctDIDToDetermineTaskRewardParameter = Parameter({
title : pctDIDToDetermineTaskRewardParameterTitle,
value: 15 * 1 ether
});
parameters[pctDIDToDetermineTaskRewardParameterTitle] = pctDIDToDetermineTaskRewardParameter;
parameterTitles.push(pctDIDToDetermineTaskRewardParameterTitle);
pctDIDRequiredToMergePullRequest = Parameter({
title : pctDIDRequiredToMergePullRequestTitle,
value: 10 * 1 ether
});
parameters[pctDIDRequiredToMergePullRequestTitle] = pctDIDRequiredToMergePullRequest;
parameterTitles.push(pctDIDRequiredToMergePullRequestTitle);
votingIntervalParameter = Parameter({
title : votingIntervalParameterTitle,
value: 1296000 * 1 ether
});
parameters[votingIntervalParameterTitle] = votingIntervalParameter;
parameterTitles.push(votingIntervalParameterTitle);
maxRewardParameter = Parameter({
title : maxRewardParameterTitle,
value: 2000 * 1 ether
});
parameters[maxRewardParameterTitle] = maxRewardParameter;
parameterTitles.push(maxRewardParameterTitle);
numDIDRequiredToApproveVotePullRequestParameter = Parameter({
title : numDIDRequiredToApproveVotePullRequestParameterTitle,
value: 100 * 1 ether
});
parameters[numDIDRequiredToApproveVotePullRequestParameterTitle] = numDIDRequiredToApproveVotePullRequestParameter;
parameterTitles.push(numDIDRequiredToApproveVotePullRequestParameterTitle);
numDIDRequiredToTaskRewardVoteParameter = Parameter({
title : numDIDRequiredToTaskRewardVoteParameterTitle,
value: 100 * 1 ether
});
parameters[numDIDRequiredToTaskRewardVoteParameterTitle] = numDIDRequiredToTaskRewardVoteParameter;
parameterTitles.push(numDIDRequiredToTaskRewardVoteParameterTitle);
minNumberOfTaskRewardVotersParameter = Parameter({
title : minNumberOfTaskRewardVotersParameterTitle,
value: 7 * 1 ether
});
parameters[minNumberOfTaskRewardVotersParameterTitle] = minNumberOfTaskRewardVotersParameter;
parameterTitles.push(minNumberOfTaskRewardVotersParameterTitle);
numDIDRequiredToAddTaskParameter = Parameter({
title : numDIDRequiredToAddTaskParameterTitle,
value: 100 * 1 ether
});
parameters[numDIDRequiredToAddTaskParameterTitle] = numDIDRequiredToAddTaskParameter;
parameterTitles.push(numDIDRequiredToAddTaskParameterTitle);
defaultRewardParameter = Parameter({
title : defaultRewardParameterTitle,
value: 100 * 1 ether
});
parameters[defaultRewardParameterTitle] = defaultRewardParameter;
parameterTitles.push(defaultRewardParameterTitle);
didPerEtherParameter = Parameter({
title : didPerEtherParameterTitle,
value: 200 * 1 ether
});
parameters[didPerEtherParameterTitle] = didPerEtherParameter;
parameterTitles.push(didPerEtherParameterTitle);
votingPowerLimitParameter = Parameter({
title : votingPowerLimitParameterTitle,
value: 20 * 1 ether
});
parameters[votingPowerLimitParameterTitle] = votingPowerLimitParameter;
parameterTitles.push(votingPowerLimitParameterTitle);
}
function getParameterValueByTitle(bytes32 _title) public view returns (uint256) {
return parameters[_title].value;
}
function voteOnParameter(bytes32 _title, int256 _voteValue)
public
votingIntervalReached(msg.sender, _title)
returns
(uint256) {
DIDToken didToken = DIDToken(DIDTokenAddress);
uint256 votersDIDPercent = didToken.pctDIDOwned(msg.sender);
require(votersDIDPercent > 0);
uint256 currentValue = getParameterValueByTitle(_title);
uint256 votingPowerLimit = getParameterValueByTitle(votingPowerLimitParameterTitle);
uint256 limitedVotingPower = votersDIDPercent > votingPowerLimit ? votingPowerLimit : votersDIDPercent;
uint256 update;
if (
_voteValue == 1 ||
_voteValue == - 1 ||
_voteValue > int(limitedVotingPower) ||
_voteValue < - int(limitedVotingPower)
) {
update = (limitedVotingPower * currentValue) / (100 * 1 ether);
} else if (_voteValue > 0) {
update = SafeMath.div((uint(_voteValue) * currentValue), (1 ether * 100));
} else if (_voteValue < 0) {
int256 adjustedVoteValue = (-_voteValue);
update = uint((adjustedVoteValue * int(currentValue))) / (100 * 1 ether);
} else revert();
if (_voteValue > 0)
currentValue = SafeMath.add(currentValue, update);
else
currentValue = SafeMath.sub(currentValue, update);
updateParameterValue(_title, currentValue);
updateLastVotedOnParameter(_title, msg.sender);
emit LogParameterValueUpdate(_title, currentValue);
return currentValue;
}
function getParameterByTitle(bytes32 _title) public view returns (bytes32, uint256) {
Parameter memory param = parameters[_title];
return (param.title, param.value);
}
function getNumParameters() public view returns (uint256) {
return parameterTitles.length;
}
function updateParameterValue(bytes32 _title, uint256 _newValue) internal returns (uint256) {
Parameter storage parameter = parameters[_title];
parameter.value = _newValue;
return parameter.value;
}
function updateLastVotedOnParameter(bytes32 _title, address voter) internal returns (bool) {
Parameter storage parameter = parameters[_title];
parameter.votes[voter].lastVoted = now;
}
function setDIDTokenAddress(address _didTokenAddress) public onlyApproved {
DIDTokenAddress = _didTokenAddress;
}
modifier votingIntervalReached(address _voter, bytes32 _title) {
Parameter storage parameter = parameters[_title];
uint256 lastVotedOnParameter = parameter.votes[_voter].lastVoted * 1 ether;
require((now * 1 ether) >= lastVotedOnParameter + getParameterValueByTitle(votingIntervalParameterTitle));
_;
}
}
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 percent(uint numerator, uint denominator, uint precision) public pure
returns(uint quotient) {
uint _numerator = numerator * 10 ** (precision + 1);
uint _quotient = ((_numerator / denominator) + 5) / 10;
return _quotient;
}
} | 0 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
pragma solidity^0.4.11;
library DLL {
uint constant NULL_NODE_ID = 0;
struct Node {
uint next;
uint prev;
}
struct Data {
mapping(uint => Node) dll;
}
function isEmpty(Data storage self) public view returns (bool) {
return getStart(self) == NULL_NODE_ID;
}
function contains(Data storage self, uint _curr) public view returns (bool) {
if (isEmpty(self) || _curr == NULL_NODE_ID) {
return false;
}
bool isSingleNode = (getStart(self) == _curr) && (getEnd(self) == _curr);
bool isNullNode = (getNext(self, _curr) == NULL_NODE_ID) && (getPrev(self, _curr) == NULL_NODE_ID);
return isSingleNode || !isNullNode;
}
function getNext(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].next;
}
function getPrev(Data storage self, uint _curr) public view returns (uint) {
return self.dll[_curr].prev;
}
function getStart(Data storage self) public view returns (uint) {
return getNext(self, NULL_NODE_ID);
}
function getEnd(Data storage self) public view returns (uint) {
return getPrev(self, NULL_NODE_ID);
}
function insert(Data storage self, uint _prev, uint _curr, uint _next) public {
require(_curr != NULL_NODE_ID);
remove(self, _curr);
require(_prev == NULL_NODE_ID || contains(self, _prev));
require(_next == NULL_NODE_ID || contains(self, _next));
require(getNext(self, _prev) == _next);
require(getPrev(self, _next) == _prev);
self.dll[_curr].prev = _prev;
self.dll[_curr].next = _next;
self.dll[_prev].next = _curr;
self.dll[_next].prev = _curr;
}
function remove(Data storage self, uint _curr) public {
if (!contains(self, _curr)) {
return;
}
uint next = getNext(self, _curr);
uint prev = getPrev(self, _curr);
self.dll[next].prev = prev;
self.dll[prev].next = next;
delete self.dll[_curr];
}
}
pragma solidity^0.4.11;
library AttributeStore {
struct Data {
mapping(bytes32 => uint) store;
}
function getAttribute(Data storage self, bytes32 _UUID, string _attrName)
public view returns (uint) {
bytes32 key = keccak256(_UUID, _attrName);
return self.store[key];
}
function setAttribute(Data storage self, bytes32 _UUID, string _attrName, uint _attrVal)
public {
bytes32 key = keccak256(_UUID, _attrName);
self.store[key] = _attrVal;
}
}
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;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
pragma solidity ^0.4.8;
contract PLCRVoting {
event _VoteCommitted(uint indexed pollID, uint numTokens, address indexed voter);
event _VoteRevealed(uint indexed pollID, uint numTokens, uint votesFor, uint votesAgainst, uint indexed choice, address indexed voter, uint salt);
event _PollCreated(uint voteQuorum, uint commitEndDate, uint revealEndDate, uint indexed pollID, address indexed creator);
event _VotingRightsGranted(uint numTokens, address indexed voter);
event _VotingRightsWithdrawn(uint numTokens, address indexed voter);
event _TokensRescued(uint indexed pollID, address indexed voter);
using AttributeStore for AttributeStore.Data;
using DLL for DLL.Data;
using SafeMath for uint;
struct Poll {
uint commitEndDate;
uint revealEndDate;
uint voteQuorum;
uint votesFor;
uint votesAgainst;
mapping(address => bool) didCommit;
mapping(address => bool) didReveal;
}
uint constant public INITIAL_POLL_NONCE = 0;
uint public pollNonce;
mapping(uint => Poll) public pollMap;
mapping(address => uint) public voteTokenBalance;
mapping(address => DLL.Data) dllMap;
AttributeStore.Data store;
IERC20 public token;
constructor(address _token) public {
require(_token != 0);
token = IERC20(_token);
pollNonce = INITIAL_POLL_NONCE;
}
function requestVotingRights(uint _numTokens) public {
require(token.balanceOf(msg.sender) >= _numTokens);
voteTokenBalance[msg.sender] += _numTokens;
require(token.transferFrom(msg.sender, this, _numTokens));
emit _VotingRightsGranted(_numTokens, msg.sender);
}
function withdrawVotingRights(uint _numTokens) external {
uint availableTokens = voteTokenBalance[msg.sender].sub(getLockedTokens(msg.sender));
require(availableTokens >= _numTokens);
voteTokenBalance[msg.sender] -= _numTokens;
require(token.transfer(msg.sender, _numTokens));
emit _VotingRightsWithdrawn(_numTokens, msg.sender);
}
function rescueTokens(uint _pollID) public {
require(isExpired(pollMap[_pollID].revealEndDate));
require(dllMap[msg.sender].contains(_pollID));
dllMap[msg.sender].remove(_pollID);
emit _TokensRescued(_pollID, msg.sender);
}
function rescueTokensInMultiplePolls(uint[] _pollIDs) public {
for (uint i = 0; i < _pollIDs.length; i++) {
rescueTokens(_pollIDs[i]);
}
}
function commitVote(uint _pollID, bytes32 _secretHash, uint _numTokens, uint _prevPollID) public {
require(commitPeriodActive(_pollID));
if (voteTokenBalance[msg.sender] < _numTokens) {
uint remainder = _numTokens.sub(voteTokenBalance[msg.sender]);
requestVotingRights(remainder);
}
require(voteTokenBalance[msg.sender] >= _numTokens);
require(_pollID != 0);
require(_secretHash != 0);
require(_prevPollID == 0 || dllMap[msg.sender].contains(_prevPollID));
uint nextPollID = dllMap[msg.sender].getNext(_prevPollID);
if (nextPollID == _pollID) {
nextPollID = dllMap[msg.sender].getNext(_pollID);
}
require(validPosition(_prevPollID, nextPollID, msg.sender, _numTokens));
dllMap[msg.sender].insert(_prevPollID, _pollID, nextPollID);
bytes32 UUID = attrUUID(msg.sender, _pollID);
store.setAttribute(UUID, "numTokens", _numTokens);
store.setAttribute(UUID, "commitHash", uint(_secretHash));
pollMap[_pollID].didCommit[msg.sender] = true;
emit _VoteCommitted(_pollID, _numTokens, msg.sender);
}
function commitVotes(uint[] _pollIDs, bytes32[] _secretHashes, uint[] _numsTokens, uint[] _prevPollIDs) external {
require(_pollIDs.length == _secretHashes.length);
require(_pollIDs.length == _numsTokens.length);
require(_pollIDs.length == _prevPollIDs.length);
for (uint i = 0; i < _pollIDs.length; i++) {
commitVote(_pollIDs[i], _secretHashes[i], _numsTokens[i], _prevPollIDs[i]);
}
}
function validPosition(uint _prevID, uint _nextID, address _voter, uint _numTokens) public constant returns (bool valid) {
bool prevValid = (_numTokens >= getNumTokens(_voter, _prevID));
bool nextValid = (_numTokens <= getNumTokens(_voter, _nextID) || _nextID == 0);
return prevValid && nextValid;
}
function revealVote(uint _pollID, uint _voteOption, uint _salt) public {
require(revealPeriodActive(_pollID));
require(pollMap[_pollID].didCommit[msg.sender]);
require(!pollMap[_pollID].didReveal[msg.sender]);
require(keccak256(_voteOption, _salt) == getCommitHash(msg.sender, _pollID));
uint numTokens = getNumTokens(msg.sender, _pollID);
if (_voteOption == 1) {
pollMap[_pollID].votesFor += numTokens;
} else {
pollMap[_pollID].votesAgainst += numTokens;
}
dllMap[msg.sender].remove(_pollID);
pollMap[_pollID].didReveal[msg.sender] = true;
emit _VoteRevealed(_pollID, numTokens, pollMap[_pollID].votesFor, pollMap[_pollID].votesAgainst, _voteOption, msg.sender, _salt);
}
function revealVotes(uint[] _pollIDs, uint[] _voteOptions, uint[] _salts) external {
require(_pollIDs.length == _voteOptions.length);
require(_pollIDs.length == _salts.length);
for (uint i = 0; i < _pollIDs.length; i++) {
revealVote(_pollIDs[i], _voteOptions[i], _salts[i]);
}
}
function getNumPassingTokens(address _voter, uint _pollID, uint _salt) public constant returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint winningChoice = isPassed(_pollID) ? 1 : 0;
bytes32 winnerHash = keccak256(winningChoice, _salt);
bytes32 commitHash = getCommitHash(_voter, _pollID);
require(winnerHash == commitHash);
return getNumTokens(_voter, _pollID);
}
function startPoll(uint _voteQuorum, uint _commitDuration, uint _revealDuration) public returns (uint pollID) {
pollNonce = pollNonce + 1;
uint commitEndDate = block.timestamp.add(_commitDuration);
uint revealEndDate = commitEndDate.add(_revealDuration);
pollMap[pollNonce] = Poll({
voteQuorum: _voteQuorum,
commitEndDate: commitEndDate,
revealEndDate: revealEndDate,
votesFor: 0,
votesAgainst: 0
});
emit _PollCreated(_voteQuorum, commitEndDate, revealEndDate, pollNonce, msg.sender);
return pollNonce;
}
function isPassed(uint _pollID) constant public returns (bool passed) {
require(pollEnded(_pollID));
Poll memory poll = pollMap[_pollID];
return (100 * poll.votesFor) > (poll.voteQuorum * (poll.votesFor + poll.votesAgainst));
}
function getTotalNumberOfTokensForWinningOption(uint _pollID) constant public returns (uint numTokens) {
require(pollEnded(_pollID));
if (isPassed(_pollID))
return pollMap[_pollID].votesFor;
else
return pollMap[_pollID].votesAgainst;
}
function pollEnded(uint _pollID) constant public returns (bool ended) {
require(pollExists(_pollID));
return isExpired(pollMap[_pollID].revealEndDate);
}
function commitPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].commitEndDate);
}
function revealPeriodActive(uint _pollID) constant public returns (bool active) {
require(pollExists(_pollID));
return !isExpired(pollMap[_pollID].revealEndDate) && !commitPeriodActive(_pollID);
}
function didCommit(address _voter, uint _pollID) constant public returns (bool committed) {
require(pollExists(_pollID));
return pollMap[_pollID].didCommit[_voter];
}
function didReveal(address _voter, uint _pollID) constant public returns (bool revealed) {
require(pollExists(_pollID));
return pollMap[_pollID].didReveal[_voter];
}
function pollExists(uint _pollID) constant public returns (bool exists) {
return (_pollID != 0 && _pollID <= pollNonce);
}
function getCommitHash(address _voter, uint _pollID) constant public returns (bytes32 commitHash) {
return bytes32(store.getAttribute(attrUUID(_voter, _pollID), "commitHash"));
}
function getNumTokens(address _voter, uint _pollID) constant public returns (uint numTokens) {
return store.getAttribute(attrUUID(_voter, _pollID), "numTokens");
}
function getLastNode(address _voter) constant public returns (uint pollID) {
return dllMap[_voter].getPrev(0);
}
function getLockedTokens(address _voter) constant public returns (uint numTokens) {
return getNumTokens(_voter, getLastNode(_voter));
}
function getInsertPointForNumTokens(address _voter, uint _numTokens, uint _pollID)
constant public returns (uint prevNode) {
uint nodeID = getLastNode(_voter);
uint tokensInNode = getNumTokens(_voter, nodeID);
while(nodeID != 0) {
tokensInNode = getNumTokens(_voter, nodeID);
if(tokensInNode <= _numTokens) {
if(nodeID == _pollID) {
nodeID = dllMap[_voter].getPrev(nodeID);
}
return nodeID;
}
nodeID = dllMap[_voter].getPrev(nodeID);
}
return nodeID;
}
function isExpired(uint _terminationDate) constant public returns (bool expired) {
return (block.timestamp > _terminationDate);
}
function attrUUID(address _user, uint _pollID) public pure returns (bytes32 UUID) {
return keccak256(_user, _pollID);
}
}
pragma solidity^0.4.11;
contract Parameterizer {
event _ReparameterizationProposal(string name, uint value, bytes32 propID, uint deposit, uint appEndDate, address indexed proposer);
event _NewChallenge(bytes32 indexed propID, uint challengeID, uint commitEndDate, uint revealEndDate, address indexed challenger);
event _ProposalAccepted(bytes32 indexed propID, string name, uint value);
event _ProposalExpired(bytes32 indexed propID);
event _ChallengeSucceeded(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeFailed(bytes32 indexed propID, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter);
using SafeMath for uint;
struct ParamProposal {
uint appExpiry;
uint challengeID;
uint deposit;
string name;
address owner;
uint processBy;
uint value;
}
struct Challenge {
uint rewardPool;
address challenger;
bool resolved;
uint stake;
uint winningTokens;
mapping(address => bool) tokenClaims;
}
mapping(bytes32 => uint) public params;
mapping(uint => Challenge) public challenges;
mapping(bytes32 => ParamProposal) public proposals;
IERC20 public token;
PLCRVoting public voting;
uint public PROCESSBY = 604800;
constructor(
address _token,
address _plcr,
uint[] _parameters
) public {
token = IERC20(_token);
voting = PLCRVoting(_plcr);
set("minDeposit", _parameters[0]);
set("pMinDeposit", _parameters[1]);
set("applyStageLen", _parameters[2]);
set("pApplyStageLen", _parameters[3]);
set("commitStageLen", _parameters[4]);
set("pCommitStageLen", _parameters[5]);
set("revealStageLen", _parameters[6]);
set("pRevealStageLen", _parameters[7]);
set("dispensationPct", _parameters[8]);
set("pDispensationPct", _parameters[9]);
set("voteQuorum", _parameters[10]);
set("pVoteQuorum", _parameters[11]);
}
function proposeReparameterization(string _name, uint _value) public returns (bytes32) {
uint deposit = get("pMinDeposit");
bytes32 propID = keccak256(_name, _value);
if (keccak256(_name) == keccak256("dispensationPct") ||
keccak256(_name) == keccak256("pDispensationPct")) {
require(_value <= 100);
}
require(!propExists(propID));
require(get(_name) != _value);
proposals[propID] = ParamProposal({
appExpiry: now.add(get("pApplyStageLen")),
challengeID: 0,
deposit: deposit,
name: _name,
owner: msg.sender,
processBy: now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY),
value: _value
});
require(token.transferFrom(msg.sender, this, deposit));
emit _ReparameterizationProposal(_name, _value, propID, deposit, proposals[propID].appExpiry, msg.sender);
return propID;
}
function challengeReparameterization(bytes32 _propID) public returns (uint challengeID) {
ParamProposal memory prop = proposals[_propID];
uint deposit = prop.deposit;
require(propExists(_propID) && prop.challengeID == 0);
uint pollID = voting.startPoll(
get("pVoteQuorum"),
get("pCommitStageLen"),
get("pRevealStageLen")
);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: SafeMath.sub(100, get("pDispensationPct")).mul(deposit).div(100),
stake: deposit,
resolved: false,
winningTokens: 0
});
proposals[_propID].challengeID = pollID;
require(token.transferFrom(msg.sender, this, deposit));
var (commitEndDate, revealEndDate,) = voting.pollMap(pollID);
emit _NewChallenge(_propID, pollID, commitEndDate, revealEndDate, msg.sender);
return pollID;
}
function processProposal(bytes32 _propID) public {
ParamProposal storage prop = proposals[_propID];
address propOwner = prop.owner;
uint propDeposit = prop.deposit;
if (canBeSet(_propID)) {
set(prop.name, prop.value);
emit _ProposalAccepted(_propID, prop.name, prop.value);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else if (challengeCanBeResolved(_propID)) {
resolveChallenge(_propID);
} else if (now > prop.processBy) {
emit _ProposalExpired(_propID);
delete proposals[_propID];
require(token.transfer(propOwner, propDeposit));
} else {
revert();
}
assert(get("dispensationPct") <= 100);
assert(get("pDispensationPct") <= 100);
now.add(get("pApplyStageLen"))
.add(get("pCommitStageLen"))
.add(get("pRevealStageLen"))
.add(PROCESSBY);
delete proposals[_propID];
}
function claimReward(uint _challengeID, uint _salt) public {
require(challenges[_challengeID].tokenClaims[msg.sender] == false);
require(challenges[_challengeID].resolved == true);
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
challenges[_challengeID].winningTokens -= voterTokens;
challenges[_challengeID].rewardPool -= reward;
challenges[_challengeID].tokenClaims[msg.sender] = true;
emit _RewardClaimed(_challengeID, reward, msg.sender);
require(token.transfer(msg.sender, reward));
}
function claimRewards(uint[] _challengeIDs, uint[] _salts) public {
require(_challengeIDs.length == _salts.length);
for (uint i = 0; i < _challengeIDs.length; i++) {
claimReward(_challengeIDs[i], _salts[i]);
}
}
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint winningTokens = challenges[_challengeID].winningTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return (voterTokens * rewardPool) / winningTokens;
}
function canBeSet(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
return (now > prop.appExpiry && now < prop.processBy && prop.challengeID == 0);
}
function propExists(bytes32 _propID) view public returns (bool) {
return proposals[_propID].processBy > 0;
}
function challengeCanBeResolved(bytes32 _propID) view public returns (bool) {
ParamProposal memory prop = proposals[_propID];
Challenge memory challenge = challenges[prop.challengeID];
return (prop.challengeID > 0 && challenge.resolved == false && voting.pollEnded(prop.challengeID));
}
function challengeWinnerReward(uint _challengeID) public view returns (uint) {
if(voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
return 2 * challenges[_challengeID].stake;
}
return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool;
}
function get(string _name) public view returns (uint value) {
return params[keccak256(_name)];
}
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
function resolveChallenge(bytes32 _propID) private {
ParamProposal memory prop = proposals[_propID];
Challenge storage challenge = challenges[prop.challengeID];
uint reward = challengeWinnerReward(prop.challengeID);
challenge.winningTokens = voting.getTotalNumberOfTokensForWinningOption(prop.challengeID);
challenge.resolved = true;
if (voting.isPassed(prop.challengeID)) {
if(prop.processBy > now) {
set(prop.name, prop.value);
}
emit _ChallengeFailed(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(prop.owner, reward));
}
else {
emit _ChallengeSucceeded(_propID, prop.challengeID, challenge.rewardPool, challenge.winningTokens);
require(token.transfer(challenges[prop.challengeID].challenger, reward));
}
}
function set(string _name, uint _value) internal {
params[keccak256(_name)] = _value;
}
}
pragma solidity ^0.4.24;
contract AddressRegistry {
event _Application(address indexed listingAddress, uint deposit, uint appEndDate, string data, address indexed applicant);
event _Challenge(address indexed listingAddress, uint indexed challengeID, string data, uint commitEndDate, uint revealEndDate, address indexed challenger);
event _Deposit(address indexed listingAddress, uint added, uint newTotal, address indexed owner);
event _Withdrawal(address indexed listingAddress, uint withdrew, uint newTotal, address indexed owner);
event _ApplicationWhitelisted(address indexed listingAddress);
event _ApplicationRemoved(address indexed listingAddress);
event _ListingRemoved(address indexed listingAddress);
event _ListingWithdrawn(address indexed listingAddress);
event _TouchAndRemoved(address indexed listingAddress);
event _ChallengeFailed(address indexed listingAddress, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _ChallengeSucceeded(address indexed listingAddress, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _RewardClaimed(uint indexed challengeID, uint reward, address indexed voter);
using SafeMath for uint;
struct Listing {
uint applicationExpiry;
bool whitelisted;
address owner;
uint unstakedDeposit;
uint challengeID;
}
struct Challenge {
uint rewardPool;
address challenger;
bool resolved;
uint stake;
uint totalTokens;
mapping(address => bool) tokenClaims;
}
mapping(uint => Challenge) public challenges;
mapping(address => Listing) public listings;
IERC20 public token;
PLCRVoting public voting;
Parameterizer public parameterizer;
string public name;
constructor(address _token, address _voting, address _parameterizer, string _name) public {
require(_token != 0, "_token address is 0");
require(_voting != 0, "_voting address is 0");
require(_parameterizer != 0, "_parameterizer address is 0");
token = IERC20(_token);
voting = PLCRVoting(_voting);
parameterizer = Parameterizer(_parameterizer);
name = _name;
}
function apply(address listingAddress, uint _amount, string _data) public {
require(!isWhitelisted(listingAddress), "Listing already whitelisted");
require(!appWasMade(listingAddress), "Application already made for this address");
require(_amount >= parameterizer.get("minDeposit"), "Deposit amount not above minDeposit");
Listing storage listing = listings[listingAddress];
listing.owner = msg.sender;
listing.applicationExpiry = block.timestamp.add(parameterizer.get("applyStageLen"));
listing.unstakedDeposit = _amount;
require(token.transferFrom(listing.owner, this, _amount), "Token transfer failed");
emit _Application(listingAddress, _amount, listing.applicationExpiry, _data, msg.sender);
}
function deposit(address listingAddress, uint _amount) external {
Listing storage listing = listings[listingAddress];
require(listing.owner == msg.sender, "Sender is not owner of Listing");
listing.unstakedDeposit += _amount;
require(token.transferFrom(msg.sender, this, _amount), "Token transfer failed");
emit _Deposit(listingAddress, _amount, listing.unstakedDeposit, msg.sender);
}
function withdraw(address listingAddress, uint _amount) external {
Listing storage listing = listings[listingAddress];
require(listing.owner == msg.sender, "Sender is not owner of listing");
require(_amount <= listing.unstakedDeposit, "Cannot withdraw more than current unstaked deposit");
if (listing.challengeID == 0 || challenges[listing.challengeID].resolved) {
require(listing.unstakedDeposit - _amount >= parameterizer.get("minDeposit"), "Withdrawal prohibitied as it would put Listing unstaked deposit below minDeposit");
}
listing.unstakedDeposit -= _amount;
require(token.transfer(msg.sender, _amount), "Token transfer failed");
emit _Withdrawal(listingAddress, _amount, listing.unstakedDeposit, msg.sender);
}
function exit(address listingAddress) external {
Listing storage listing = listings[listingAddress];
require(msg.sender == listing.owner, "Sender is not owner of listing");
require(isWhitelisted(listingAddress), "Listing must be whitelisted to be exited");
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved, "Listing must not have an active challenge to be exited");
resetListing(listingAddress);
emit _ListingWithdrawn(listingAddress);
}
function challenge(address listingAddress, string _data) public returns (uint challengeID) {
Listing storage listing = listings[listingAddress];
uint minDeposit = parameterizer.get("minDeposit");
require(appWasMade(listingAddress) || listing.whitelisted, "Listing must be in application phase or already whitelisted to be challenged");
require(listing.challengeID == 0 || challenges[listing.challengeID].resolved, "Listing must not have active challenge to be challenged");
if (listing.unstakedDeposit < minDeposit) {
resetListing(listingAddress);
emit _TouchAndRemoved(listingAddress);
return 0;
}
uint pollID = voting.startPoll(
parameterizer.get("voteQuorum"),
parameterizer.get("commitStageLen"),
parameterizer.get("revealStageLen")
);
uint oneHundred = 100;
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: ((oneHundred.sub(parameterizer.get("dispensationPct"))).mul(minDeposit)).div(100),
stake: minDeposit,
resolved: false,
totalTokens: 0
});
listing.challengeID = pollID;
listing.unstakedDeposit -= minDeposit;
require(token.transferFrom(msg.sender, this, minDeposit), "Token transfer failed");
var (commitEndDate, revealEndDate,) = voting.pollMap(pollID);
emit _Challenge(listingAddress, pollID, _data, commitEndDate, revealEndDate, msg.sender);
return pollID;
}
function updateStatus(address listingAddress) public {
if (canBeWhitelisted(listingAddress)) {
whitelistApplication(listingAddress);
} else if (challengeCanBeResolved(listingAddress)) {
resolveChallenge(listingAddress);
} else {
revert();
}
}
function updateStatuses(address[] listingAddresses) public {
for (uint i = 0; i < listingAddresses.length; i++) {
updateStatus(listingAddresses[i]);
}
}
function claimReward(uint _challengeID, uint _salt) public {
require(challenges[_challengeID].tokenClaims[msg.sender] == false, "Reward already claimed");
require(challenges[_challengeID].resolved == true, "Challenge not yet resolved");
uint voterTokens = voting.getNumPassingTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
challenges[_challengeID].totalTokens -= voterTokens;
challenges[_challengeID].rewardPool -= reward;
challenges[_challengeID].tokenClaims[msg.sender] = true;
require(token.transfer(msg.sender, reward), "Token transfer failed");
emit _RewardClaimed(_challengeID, reward, msg.sender);
}
function claimRewards(uint[] _challengeIDs, uint[] _salts) public {
require(_challengeIDs.length == _salts.length, "Mismatch in length of _challengeIDs and _salts parameters");
for (uint i = 0; i < _challengeIDs.length; i++) {
claimReward(_challengeIDs[i], _salts[i]);
}
}
function voterReward(address _voter, uint _challengeID, uint _salt)
public view returns (uint) {
uint totalTokens = challenges[_challengeID].totalTokens;
uint rewardPool = challenges[_challengeID].rewardPool;
uint voterTokens = voting.getNumPassingTokens(_voter, _challengeID, _salt);
return (voterTokens * rewardPool) / totalTokens;
}
function canBeWhitelisted(address listingAddress) view public returns (bool) {
uint challengeID = listings[listingAddress].challengeID;
if (
appWasMade(listingAddress) &&
listings[listingAddress].applicationExpiry < now &&
!isWhitelisted(listingAddress) &&
(challengeID == 0 || challenges[challengeID].resolved == true)
) { return true; }
return false;
}
function isWhitelisted(address listingAddress) view public returns (bool whitelisted) {
return listings[listingAddress].whitelisted;
}
function appWasMade(address listingAddress) view public returns (bool exists) {
return listings[listingAddress].applicationExpiry > 0;
}
function challengeExists(address listingAddress) view public returns (bool) {
uint challengeID = listings[listingAddress].challengeID;
return (listings[listingAddress].challengeID > 0 && !challenges[challengeID].resolved);
}
function challengeCanBeResolved(address listingAddress) view public returns (bool) {
uint challengeID = listings[listingAddress].challengeID;
require(challengeExists(listingAddress), "Challenge does not exist for Listing");
return voting.pollEnded(challengeID);
}
function determineReward(uint _challengeID) public view returns (uint) {
require(!challenges[_challengeID].resolved, "Challenge already resolved");
require(voting.pollEnded(_challengeID), "Poll for challenge has not ended");
if (voting.getTotalNumberOfTokensForWinningOption(_challengeID) == 0) {
return 2 * challenges[_challengeID].stake;
}
return (2 * challenges[_challengeID].stake) - challenges[_challengeID].rewardPool;
}
function tokenClaims(uint _challengeID, address _voter) public view returns (bool) {
return challenges[_challengeID].tokenClaims[_voter];
}
function resolveChallenge(address listingAddress) internal {
uint challengeID = listings[listingAddress].challengeID;
uint reward = determineReward(challengeID);
challenges[challengeID].resolved = true;
challenges[challengeID].totalTokens =
voting.getTotalNumberOfTokensForWinningOption(challengeID);
if (voting.isPassed(challengeID)) {
whitelistApplication(listingAddress);
listings[listingAddress].unstakedDeposit += reward;
emit _ChallengeFailed(listingAddress, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
}
else {
resetListing(listingAddress);
require(token.transfer(challenges[challengeID].challenger, reward), "Token transfer failure");
emit _ChallengeSucceeded(listingAddress, challengeID, challenges[challengeID].rewardPool, challenges[challengeID].totalTokens);
}
}
function whitelistApplication(address listingAddress) internal {
if (!listings[listingAddress].whitelisted) { emit _ApplicationWhitelisted(listingAddress); }
listings[listingAddress].whitelisted = true;
}
function resetListing(address listingAddress) internal {
Listing storage listing = listings[listingAddress];
if (listing.whitelisted) {
emit _ListingRemoved(listingAddress);
} else {
emit _ApplicationRemoved(listingAddress);
}
address owner = listing.owner;
uint unstakedDeposit = listing.unstakedDeposit;
delete listings[listingAddress];
if (unstakedDeposit > 0){
require(token.transfer(owner, unstakedDeposit), "Token transfer failure");
}
}
}
pragma solidity ^0.4.24;
contract ContractAddressRegistry is AddressRegistry {
modifier onlyContract(address contractAddress) {
uint size;
assembly { size := extcodesize(contractAddress) }
require(size > 0, "Address is not a contract");
_;
}
constructor(address _token, address _voting, address _parameterizer, string _name) public AddressRegistry(_token, _voting, _parameterizer, _name) {
}
function apply(address listingAddress, uint amount, string data) onlyContract(listingAddress) public {
super.apply(listingAddress, amount, data);
}
}
pragma solidity ^0.4.24;
contract RestrictedAddressRegistry is ContractAddressRegistry {
modifier onlyContractOwner(address _contractAddress) {
Ownable ownedContract = Ownable(_contractAddress);
require(ownedContract.owner() == msg.sender, "Sender is not owner of contract");
_;
}
constructor(address _token, address _voting, address _parameterizer, string _name) public ContractAddressRegistry(_token, _voting, _parameterizer, _name) {
}
function apply(address listingAddress, uint amount, string data) onlyContractOwner(listingAddress) public {
super.apply(listingAddress, amount, data);
}
}
pragma solidity ^0.4.19;
interface IGovernment {
function getAppellate() public view returns (address);
function getGovernmentController() public view returns (address);
function get(string name) public view returns (uint);
}
pragma solidity ^0.4.23;
interface TokenTelemetryI {
function onRequestVotingRights(address user, uint tokenAmount) external;
}
pragma solidity ^0.4.23;
contract CivilPLCRVoting is PLCRVoting {
TokenTelemetryI public telemetry;
constructor(address tokenAddr, address telemetryAddr) public PLCRVoting(tokenAddr) {
require(telemetryAddr != 0);
telemetry = TokenTelemetryI(telemetryAddr);
}
function requestVotingRights(uint _numTokens) public {
super.requestVotingRights(_numTokens);
telemetry.onRequestVotingRights(msg.sender, voteTokenBalance[msg.sender]);
}
function getNumLosingTokens(address _voter, uint _pollID, uint _salt) public view returns (uint correctVotes) {
require(pollEnded(_pollID));
require(pollMap[_pollID].didReveal[_voter]);
uint losingChoice = isPassed(_pollID) ? 0 : 1;
bytes32 loserHash = keccak256(losingChoice, _salt);
bytes32 commitHash = getCommitHash(_voter, _pollID);
require(loserHash == commitHash);
return getNumTokens(_voter, _pollID);
}
function getTotalNumberOfTokensForLosingOption(uint _pollID) public view returns (uint numTokens) {
require(pollEnded(_pollID));
if (isPassed(_pollID))
return pollMap[_pollID].votesAgainst;
else
return pollMap[_pollID].votesFor;
}
}
pragma solidity ^0.4.19;
contract CivilParameterizer is Parameterizer {
constructor(
address tokenAddr,
address plcrAddr,
uint[] parameters
) public Parameterizer(tokenAddr, plcrAddr, parameters)
{
set("challengeAppealLen", parameters[12]);
set("challengeAppealCommitLen", parameters[13]);
set("challengeAppealRevealLen", parameters[14]);
}
}
pragma solidity ^0.4.24;
contract CivilTCR is RestrictedAddressRegistry {
event _AppealRequested(address indexed listingAddress, uint indexed challengeID, uint appealFeePaid, address requester, string data);
event _AppealGranted(address indexed listingAddress, uint indexed challengeID, string data);
event _FailedChallengeOverturned(address indexed listingAddress, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _SuccessfulChallengeOverturned(address indexed listingAddress, uint indexed challengeID, uint rewardPool, uint totalTokens);
event _GrantedAppealChallenged(address indexed listingAddress, uint indexed challengeID, uint indexed appealChallengeID, string data);
event _GrantedAppealOverturned(address indexed listingAddress, uint indexed challengeID, uint indexed appealChallengeID, uint rewardPool, uint totalTokens);
event _GrantedAppealConfirmed(address indexed listingAddress, uint indexed challengeID, uint indexed appealChallengeID, uint rewardPool, uint totalTokens);
event _GovernmentTransfered(address newGovernment);
modifier onlyGovernmentController {
require(msg.sender == government.getGovernmentController(), "sender was not the Government Controller");
_;
}
modifier onlyAppellate {
require(msg.sender == government.getAppellate(), "sender was not the Appellate");
_;
}
CivilPLCRVoting public civilVoting;
IGovernment public government;
struct Appeal {
address requester;
uint appealFeePaid;
uint appealPhaseExpiry;
bool appealGranted;
uint appealOpenToChallengeExpiry;
uint appealChallengeID;
bool overturned;
}
mapping(uint => uint) public challengeRequestAppealExpiries;
mapping(uint => Appeal) public appeals;
constructor(
IERC20 token,
CivilPLCRVoting plcr,
CivilParameterizer param,
IGovernment govt
) public RestrictedAddressRegistry(token, address(plcr), address(param), "CivilTCR")
{
require(address(govt) != 0, "govt address was zero");
require(govt.getGovernmentController() != 0, "govt.getGovernmentController address was 0");
civilVoting = plcr;
government = govt;
}
function apply(address listingAddress, uint amount, string data) public {
super.apply(listingAddress, amount, data);
}
function requestAppeal(address listingAddress, string data) external {
Listing storage listing = listings[listingAddress];
require(voting.pollEnded(listing.challengeID), "Poll for listing challenge has not ended");
require(challengeRequestAppealExpiries[listing.challengeID] > now, "Request Appeal phase is over");
require(appeals[listing.challengeID].requester == address(0), "Appeal for this challenge has already been made");
uint appealFee = government.get("appealFee");
Appeal storage appeal = appeals[listing.challengeID];
appeal.requester = msg.sender;
appeal.appealFeePaid = appealFee;
appeal.appealPhaseExpiry = now.add(government.get("judgeAppealLen"));
require(token.transferFrom(msg.sender, this, appealFee), "Token transfer failed");
emit _AppealRequested(listingAddress, listing.challengeID, appealFee, msg.sender, data);
}
function grantAppeal(address listingAddress, string data) external onlyAppellate {
Listing storage listing = listings[listingAddress];
Appeal storage appeal = appeals[listing.challengeID];
require(appeal.appealPhaseExpiry > now, "Judge Appeal phase not active");
require(!appeal.appealGranted, "Appeal has already been granted");
appeal.appealGranted = true;
appeal.appealOpenToChallengeExpiry = now.add(parameterizer.get("challengeAppealLen"));
emit _AppealGranted(listingAddress, listing.challengeID, data);
}
function transferGovernment(IGovernment newGovernment) external onlyGovernmentController {
require(address(newGovernment) != address(0), "New Government address is 0");
government = newGovernment;
emit _GovernmentTransfered(newGovernment);
}
function updateStatus(address listingAddress) public {
if (canBeWhitelisted(listingAddress)) {
whitelistApplication(listingAddress);
} else if (challengeCanBeResolved(listingAddress)) {
resolveChallenge(listingAddress);
} else if (appealCanBeResolved(listingAddress)) {
resolveAppeal(listingAddress);
} else if (appealChallengeCanBeResolved(listingAddress)) {
resolveAppealChallenge(listingAddress);
} else {
revert();
}
}
function resolveAppeal(address listingAddress) internal {
Listing listing = listings[listingAddress];
Appeal appeal = appeals[listing.challengeID];
if (appeal.appealGranted) {
resolveOverturnedChallenge(listingAddress);
require(token.transfer(appeal.requester, appeal.appealFeePaid), "Token transfer failed");
} else {
Challenge storage challenge = challenges[listing.challengeID];
uint extraReward = appeal.appealFeePaid.div(2);
challenge.rewardPool = challenge.rewardPool.add(extraReward);
challenge.stake = challenge.stake.add(appeal.appealFeePaid.sub(extraReward));
super.resolveChallenge(listingAddress);
}
}
function challenge(address listingAddress, string data) public returns (uint challengeID) {
uint id = super.challenge(listingAddress, data);
if (id > 0) {
uint challengeLength = parameterizer.get("commitStageLen").add(parameterizer.get("revealStageLen")).add(government.get("requestAppealLen"));
challengeRequestAppealExpiries[id] = now.add(challengeLength);
}
return id;
}
function challengeGrantedAppeal(address listingAddress, string data) public returns (uint challengeID) {
Listing storage listing = listings[listingAddress];
Appeal storage appeal = appeals[listing.challengeID];
require(appeal.appealGranted, "Appeal not granted");
require(appeal.appealChallengeID == 0, "Appeal already challenged");
require(appeal.appealOpenToChallengeExpiry > now, "Appeal no longer open to challenge");
uint pollID = voting.startPoll(
government.get("appealVotePercentage"),
parameterizer.get("challengeAppealCommitLen"),
parameterizer.get("challengeAppealRevealLen")
);
uint oneHundred = 100;
uint reward = (oneHundred.sub(government.get("appealChallengeVoteDispensationPct"))).mul(appeal.appealFeePaid).div(oneHundred);
challenges[pollID] = Challenge({
challenger: msg.sender,
rewardPool: reward,
stake: appeal.appealFeePaid,
resolved: false,
totalTokens: 0
});
appeal.appealChallengeID = pollID;
require(token.transferFrom(msg.sender, this, appeal.appealFeePaid), "Token transfer failed");
emit _GrantedAppealChallenged(listingAddress, listing.challengeID, pollID, data);
return pollID;
}
function resolveAppealChallenge(address listingAddress) internal {
Listing storage listing = listings[listingAddress];
uint challengeID = listings[listingAddress].challengeID;
Appeal storage appeal = appeals[listing.challengeID];
uint appealChallengeID = appeal.appealChallengeID;
Challenge storage appealChallenge = challenges[appeal.appealChallengeID];
uint reward = determineReward(appealChallengeID);
appealChallenge.resolved = true;
appealChallenge.totalTokens = voting.getTotalNumberOfTokensForWinningOption(appealChallengeID);
if (voting.isPassed(appealChallengeID)) {
appeal.overturned = true;
super.resolveChallenge(listingAddress);
require(token.transfer(appealChallenge.challenger, reward), "Token transfer failed");
emit _GrantedAppealOverturned(listingAddress, challengeID, appealChallengeID, appealChallenge.rewardPool, appealChallenge.totalTokens);
} else {
resolveOverturnedChallenge(listingAddress);
require(token.transfer(appeal.requester, reward), "Token transfer failed");
emit _GrantedAppealConfirmed(listingAddress, challengeID, appealChallengeID, appealChallenge.rewardPool, appealChallenge.totalTokens);
}
}
function claimReward(uint _challengeID, uint _salt) public {
require(challenges[_challengeID].tokenClaims[msg.sender] == false, "Reward already claimed");
require(challenges[_challengeID].resolved == true, "Challenge not yet resolved");
uint voterTokens = getNumChallengeTokens(msg.sender, _challengeID, _salt);
uint reward = voterReward(msg.sender, _challengeID, _salt);
challenges[_challengeID].totalTokens = challenges[_challengeID].totalTokens.sub(voterTokens);
challenges[_challengeID].rewardPool = challenges[_challengeID].rewardPool.sub(reward);
challenges[_challengeID].tokenClaims[msg.sender] = true;
require(token.transfer(msg.sender, reward), "Token transfer failed");
emit _RewardClaimed(_challengeID, reward, msg.sender);
}
function getNumChallengeTokens(address voter, uint challengeID, uint salt) internal view returns (uint) {
bool challengeOverturned = appeals[challengeID].appealGranted && !appeals[challengeID].overturned;
if (challengeOverturned) {
return civilVoting.getNumLosingTokens(voter, challengeID, salt);
} else {
return voting.getNumPassingTokens(voter, challengeID, salt);
}
}
function determineReward(uint challengeID) public view returns (uint) {
require(!challenges[challengeID].resolved, "Challenge already resolved");
require(voting.pollEnded(challengeID), "Poll for challenge has not ended");
bool challengeOverturned = appeals[challengeID].appealGranted && !appeals[challengeID].overturned;
if (challengeOverturned) {
if (civilVoting.getTotalNumberOfTokensForLosingOption(challengeID) == 0) {
return 2 * challenges[challengeID].stake;
}
} else {
if (voting.getTotalNumberOfTokensForWinningOption(challengeID) == 0) {
return 2 * challenges[challengeID].stake;
}
}
return (2 * challenges[challengeID].stake) - challenges[challengeID].rewardPool;
}
function voterReward(
address voter,
uint challengeID,
uint salt
) public view returns (uint)
{
Challenge challenge = challenges[challengeID];
uint totalTokens = challenge.totalTokens;
uint rewardPool = challenge.rewardPool;
uint voterTokens = getNumChallengeTokens(voter, challengeID, salt);
return (voterTokens.mul(rewardPool)).div(totalTokens);
}
function whitelistApplication(address listingAddress) internal {
super.whitelistApplication(listingAddress);
listings[listingAddress].challengeID = 0;
}
function resolveOverturnedChallenge(address listingAddress) private {
Listing storage listing = listings[listingAddress];
uint challengeID = listing.challengeID;
Challenge storage challenge = challenges[challengeID];
uint reward = determineReward(challengeID);
challenge.resolved = true;
challenge.totalTokens = civilVoting.getTotalNumberOfTokensForLosingOption(challengeID);
if (!voting.isPassed(challengeID)) {
whitelistApplication(listingAddress);
listing.unstakedDeposit = listing.unstakedDeposit.add(reward);
emit _SuccessfulChallengeOverturned(listingAddress, challengeID, challenge.rewardPool, challenge.totalTokens);
} else {
resetListing(listingAddress);
require(token.transfer(challenge.challenger, reward), "Token transfer failed");
emit _FailedChallengeOverturned(listingAddress, challengeID, challenge.rewardPool, challenge.totalTokens);
}
}
function challengeCanBeResolved(address listingAddress) view public returns (bool canBeResolved) {
uint challengeID = listings[listingAddress].challengeID;
require(challengeExists(listingAddress), "Challenge does not exist for listing");
if (challengeRequestAppealExpiries[challengeID] > now) {
return false;
}
return (appeals[challengeID].appealPhaseExpiry == 0);
}
function appealCanBeResolved(address listingAddress) view public returns (bool canBeResolved) {
uint challengeID = listings[listingAddress].challengeID;
Appeal appeal = appeals[challengeID];
require(challengeExists(listingAddress), "Challenge does not exist for listing");
if (appeal.appealPhaseExpiry == 0) {
return false;
}
if (!appeal.appealGranted) {
return appeal.appealPhaseExpiry < now;
} else {
return appeal.appealOpenToChallengeExpiry < now && appeal.appealChallengeID == 0;
}
}
function appealChallengeCanBeResolved(address listingAddress) view public returns (bool canBeResolved) {
uint challengeID = listings[listingAddress].challengeID;
Appeal appeal = appeals[challengeID];
require(challengeExists(listingAddress), "Challenge does not exist for listing");
if (appeal.appealChallengeID == 0) {
return false;
}
return voting.pollEnded(appeal.appealChallengeID);
}
} | 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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ERC20 {
string public name;
string public symbol;
uint8 public decimals;
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 OptionsEscrow is Ownable {
using SafeMath for uint;
struct Option {
address beneficiary;
uint tokenAmount;
uint strikeMultiple;
uint128 vestUntil;
uint128 expiration;
}
address public token;
uint public issuedTokens;
uint64 public optionsCount;
mapping (address => Option) public grantedOptions;
event GrantOption(address indexed beneficiary, uint tokenAmount, uint strikeMultiple, uint128 vestUntil, uint128 expiration);
event ExerciseOption(address indexed beneficiary, uint exercisedAmount, uint strikeMultiple);
event ReclaimOption(address indexed beneficiary);
constructor(address _token) public {
token = _token;
issuedTokens = 0;
optionsCount = 0;
}
function issueOption(address _beneficiary,
uint _tokenAmount,
uint _strikeMultiple,
uint128 _vestUntil,
uint128 _expiration) onlyOwner public {
uint _issuedTokens = issuedTokens.add(_tokenAmount);
require(_tokenAmount > 0 &&
_expiration > _vestUntil &&
_vestUntil > block.timestamp &&
ERC20(token).balanceOf(this) > _issuedTokens);
Option memory option = Option(_beneficiary, _tokenAmount, _strikeMultiple, _vestUntil, _expiration);
grantedOptions[_beneficiary] = option;
optionsCount++;
issuedTokens = _issuedTokens;
emit GrantOption(_beneficiary, _tokenAmount, _strikeMultiple, _vestUntil, _expiration);
}
function () public payable {
Option storage option = grantedOptions[msg.sender];
require(option.beneficiary == msg.sender &&
option.vestUntil <= block.timestamp &&
option.expiration > block.timestamp &&
option.tokenAmount > 0);
uint amountExercised = msg.value.mul(option.strikeMultiple);
if(amountExercised > option.tokenAmount) {
amountExercised = option.tokenAmount;
}
option.tokenAmount = option.tokenAmount.sub(amountExercised);
issuedTokens = issuedTokens.sub(amountExercised);
require(ERC20(token).transfer(msg.sender, amountExercised));
emit ExerciseOption(msg.sender, amountExercised, option.strikeMultiple);
}
function reclaimExpiredOptionTokens(address[] beneficiaries) public onlyOwner returns (uint reclaimedTokenAmount) {
reclaimedTokenAmount = 0;
for (uint i=0; i<beneficiaries.length; i++) {
Option storage option = grantedOptions[beneficiaries[i]];
if (option.expiration <= block.timestamp) {
reclaimedTokenAmount = reclaimedTokenAmount.add(option.tokenAmount);
option.tokenAmount = 0;
emit ReclaimOption(beneficiaries[i]);
}
}
issuedTokens = issuedTokens.sub(reclaimedTokenAmount);
require(ERC20(token).transfer(owner, reclaimedTokenAmount));
}
function reclaimUnissuedTokens() public onlyOwner returns (uint reclaimedTokenAmount) {
reclaimedTokenAmount = ERC20(token).balanceOf(this) - issuedTokens;
require(ERC20(token).transfer(owner, reclaimedTokenAmount));
}
function withdrawEth() public onlyOwner {
owner.transfer(address(this).balance);
}
function getOption(address _beneficiary) public constant returns(address beneficiary,
uint tokenAmount,
uint strikeMultiple,
uint128 vestUntil,
uint128 expiration) {
Option memory option = grantedOptions[_beneficiary];
beneficiary = option.beneficiary;
tokenAmount = option.tokenAmount;
strikeMultiple = option.strikeMultiple;
vestUntil = option.vestUntil;
expiration = option.expiration;
}
} | 0 |
pragma solidity ^ 0.4 .9;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TRIUMLAND {
using SafeMath
for uint256;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => uint256) balances;
uint256 public totalSupply;
uint256 public decimals;
address public owner;
bytes32 public symbol;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
function TRIUMLAND() {
totalSupply = 1000000000;
symbol = 'TRD';
owner = 0xf4b9baccf4c8ed23e959a0fca05574cad5a4f01b;
balances[owner] = totalSupply;
decimals = 0;
}
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function() {
revert();
}
} | 1 |
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 = 0xFB4608eCB649f3C9b8fcA04b7499044E1beab53A;
}
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 BitBoscoin {
string public standard = 'BOSS Token';
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function BitBoscoin() {
initialSupply = 30000000000000000000000000;
name ="BitBoscoin";
decimals = 18;
symbol = "BOSS";
balanceOf[msg.sender] = initialSupply;
totalSupply = initialSupply;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
}
function () {
throw;
}
} | 1 |
pragma solidity ^0.4.21;
contract ForeignToken {
function balanceOf(address _owner) constant returns (uint256);
function transfer(address _to, uint256 _value) returns (bool);
}
contract tokenTrust {
event Hodl(address indexed hodler, uint indexed amount);
event Party(address indexed hodler, uint indexed amount);
mapping (address => uint) public hodlers;
uint partyTime = 1521975140;
function() payable {
hodlers[msg.sender] += msg.value;
Hodl(msg.sender, msg.value);
}
function party() {
require (block.timestamp > partyTime && hodlers[msg.sender] > 0);
uint value = hodlers[msg.sender];
uint amount = value/104;
msg.sender.transfer(amount);
Party(msg.sender, amount);
partyTime = partyTime + 604800;
}
function withdrawForeignTokens(address _tokenContract) returns (bool) {
if (msg.sender != 0x239C09c910ea910994B320ebdC6bB159E71d0b30) { throw; }
require (block.timestamp > partyTime);
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this))/104;
return token.transfer(0x239C09c910ea910994B320ebdC6bB159E71d0b30, amount);
partyTime = partyTime + 604800;
}
} | 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;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
return a / b;
}
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;
}
}
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);
}
}
interface PartnershipInterface {
function deposit() external payable returns(bool);
}
interface PlayerBookReceiverInterface {
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external;
function receivePlayerNameList(uint256 _pID, bytes32 _name) external;
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "You are not owner.");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "Invalid address.");
owner = _newOwner;
emit OwnershipTransferred(owner, _newOwner);
}
}
contract PlayerBook is Ownable {
using SafeMath for uint256;
using NameFilter for string;
PartnershipInterface constant private partnership = PartnershipInterface(0x59Ff25C4E2550bc9E2115dbcD28b949d7670d134);
uint256 public registrationFee_ = 10 finney;
mapping(uint256 => PlayerBookReceiverInterface) public games_;
mapping(address => bytes32) public gameNames_;
mapping(address => uint256) public gameIDs_;
uint256 public gID_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
struct Player {
address addr;
bytes32 name;
uint256 laff;
uint256 names;
}
mapping (uint256 => Player) public plyr_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_;
event onNewName(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
constructor() public {
plyr_[1].addr = 0x98EF158e8EA887AF8F2F4fecfEd25857b0A699c6;
plyr_[1].name = "asia";
plyr_[1].names = 1;
pIDxAddr_[0x98EF158e8EA887AF8F2F4fecfEd25857b0A699c6] = 1;
pIDxName_["asia"] = 1;
plyrNames_[1]["asia"] = true;
plyrNameList_[1][1] = "asia";
pID_ = 1;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {
_codeLength := extcodesize(_addr)
}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isRegisteredGame() {
require(gameIDs_[msg.sender] != 0);
_;
}
function checkIfNameValid(string _nameStr) public view returns(bool) {
bytes32 _name = _nameStr.nameFilter();
if (pIDxName_[_name] == 0) {
return true;
}
return false;
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all) public payable isHuman {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) {
plyr_[_pID].laff = _affCode;
} else if (_affCode == _pID) {
_affCode = 0;
}
registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all) public payable isHuman {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr) {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff) {
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all) public payable isHuman {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bytes32 _name = NameFilter.nameFilter(_nameString);
address _addr = msg.sender;
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name) {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff) {
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
}
function addMeToGame(uint256 _gameID) public isHuman {
require(_gameID <= gID_, "silly player, that game doesn't exist yet");
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff);
uint256 _totalNames = plyr_[_pID].names;
if (_totalNames > 1) {
for (uint256 ii = 1; ii <= _totalNames; ii++) {
games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
}
function addMeToAllGames() public isHuman {
address _addr = msg.sender;
uint256 _pID = pIDxAddr_[_addr];
require(_pID != 0, "hey there buddy, you dont even have an account");
uint256 _laff = plyr_[_pID].laff;
uint256 _totalNames = plyr_[_pID].names;
bytes32 _name = plyr_[_pID].name;
for (uint256 i = 1; i <= gID_; i++) {
games_[i].receivePlayerInfo(_pID, _addr, _name, _laff);
if (_totalNames > 1) {
for (uint256 ii = 1; ii <= _totalNames; ii++) {
games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]);
}
}
}
}
function useMyOldName(string _nameString) isHuman public {
bytes32 _name = _nameString.nameFilter();
uint256 _pID = pIDxAddr_[msg.sender];
require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own");
plyr_[_pID].name = _name;
}
function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private {
if (pIDxName_[_name] != 0) {
require(plyrNames_[_pID][_name] == true, "sorry that names already taken");
}
plyr_[_pID].name = _name;
pIDxName_[_name] = _pID;
if (plyrNames_[_pID][_name] == false) {
plyrNames_[_pID][_name] = true;
plyr_[_pID].names++;
plyrNameList_[_pID][plyr_[_pID].names] = _name;
}
partnership.deposit.value(address(this).balance)();
if (_all == true) {
for (uint256 i = 1; i <= gID_; i++) {
games_[i].receivePlayerInfo(_pID, _addr, _name, _affID);
}
}
emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now);
}
function determinePID(address _addr) private returns (bool) {
if (pIDxAddr_[_addr] == 0) {
pID_++;
pIDxAddr_[_addr] = pID_;
plyr_[pID_].addr = _addr;
return true;
}
return false;
}
function getPlayerID(address _addr) external isRegisteredGame returns (uint256) {
determinePID(_addr);
return (pIDxAddr_[_addr]);
}
function getPlayerName(uint256 _pID) external view returns (bytes32) {
return (plyr_[_pID].name);
}
function getPlayerLAff(uint256 _pID) external view returns (uint256) {
return (plyr_[_pID].laff);
}
function getPlayerAddr(uint256 _pID) external view returns (address) {
return (plyr_[_pID].addr);
}
function getNameFee() external view returns (uint256) {
return(registrationFee_);
}
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable isRegisteredGame returns(bool, uint256) {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID = _affCode;
if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) {
plyr_[_pID].laff = _affID;
} else if (_affID == _pID) {
_affID = 0;
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable isRegisteredGame returns(bool, uint256) {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != address(0) && _affCode != _addr) {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff) {
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable isRegisteredGame returns(bool, uint256) {
require (msg.value >= registrationFee_, "umm..... you have to pay the name fee");
bool _isNewPlayer = determinePID(_addr);
uint256 _pID = pIDxAddr_[_addr];
uint256 _affID;
if (_affCode != "" && _affCode != _name) {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff) {
plyr_[_pID].laff = _affID;
}
}
registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all);
return(_isNewPlayer, _affID);
}
function addGame(address _gameAddress, string _gameNameStr) public onlyOwner {
require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered");
gID_++;
bytes32 _name = _gameNameStr.nameFilter();
gameIDs_[_gameAddress] = gID_;
gameNames_[_gameAddress] = _name;
games_[gID_] = PlayerBookReceiverInterface(_gameAddress);
games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0);
}
function setRegistrationFee(uint256 _fee) public onlyOwner {
registrationFee_ = _fee;
}
} | 1 |
pragma solidity ^0.5.8;
contract FactoryStorage {
event NewPositionContract(
address userAddress,
address newPositionContractAddress,
address factoryLogicAddress
);
event NewTokenAddedToPositionContract(
string ticker,
address tokenAddr,
address cTokenAddr,
address exchangeAddr
);
event UserAdded(
address userAddr
);
event TickerAdded(
string ticker
);
event FactoryLogicChanged(
address factoryLogicAddr
);
mapping (string => mapping (address => address)) public positionContracts;
mapping (string => address) public tokenAddresses;
mapping (string => address) public ctokenAddresses;
mapping (string => address) public exchangeAddresses;
address public factoryLogicAddress;
address[3] public ownerAddresses;
address[] public userAddresses;
string[] public tickers;
mapping (address => bool) public userAddressesSet;
mapping (string => bool) public tickerSet;
constructor(address owner1, address owner2) public {
ownerAddresses[0] = msg.sender;
ownerAddresses[1] = owner1;
ownerAddresses[2] = owner2;
tickers = ['DAI','ZRX','BAT','ETH'];
tickerSet['DAI'] = true;
tickerSet['ZRX'] = true;
tickerSet['BAT'] = true;
tickerSet['ETH'] = true;
tokenAddresses['DAI'] = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
tokenAddresses['BAT'] = 0x0D8775F648430679A709E98d2b0Cb6250d2887EF;
tokenAddresses['ZRX'] = 0xE41d2489571d322189246DaFA5ebDe1F4699F498;
tokenAddresses['REP'] = 0x1985365e9f78359a9B6AD760e32412f4a445E862;
ctokenAddresses['DAI'] = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC;
ctokenAddresses['BAT'] = 0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E;
ctokenAddresses['ZRX'] = 0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407;
ctokenAddresses['REP'] = 0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1;
ctokenAddresses['ETH'] = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
exchangeAddresses['DAI'] = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14;
exchangeAddresses['BAT'] = 0x2E642b8D59B45a1D8c5aEf716A84FF44ea665914;
exchangeAddresses['ZRX'] = 0xaE76c84C9262Cdb9abc0C2c8888e62Db8E22A0bF;
exchangeAddresses['REP'] = 0x48B04d2A05B6B604d8d5223Fd1984f191DED51af;
}
function setFactoryLogicAddress(address newAddress) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
factoryLogicAddress = newAddress;
emit FactoryLogicChanged(newAddress);
}
function addUser(address newAddress) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
if (!userAddressesSet[newAddress]) {
userAddresses.push(newAddress);
userAddressesSet[newAddress] = true;
emit UserAdded(newAddress);
}
}
function addTicker(string memory ticker) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
if (!tickerSet[ticker]) {
tickers.push(ticker);
tickerSet[ticker] = true;
emit TickerAdded(ticker);
}
}
function updateTokenAddress(string memory ticker, address newAddress) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
tokenAddresses[ticker] = newAddress;
}
function updatecTokenAddress(string memory ticker, address newAddress) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
ctokenAddresses[ticker] = newAddress;
}
function updateExchangeAddress(string memory ticker, address newAddress) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
exchangeAddresses[ticker] = newAddress;
}
function addNewTokenToPositionContracts(string memory ticker, address tokenAddr, address cTokenAddr, address exchangeAddr) public {
require(factoryLogicAddress == msg.sender|| ownerAddresses[0] == msg.sender || ownerAddresses[1] == msg.sender || ownerAddresses[2] == msg.sender);
tokenAddresses[ticker] = tokenAddr;
ctokenAddresses[ticker] = cTokenAddr;
exchangeAddresses[ticker] = exchangeAddr;
emit NewTokenAddedToPositionContract(ticker, tokenAddr, cTokenAddr, exchangeAddr);
}
function addNewPositionContract(string memory ticker, address userAddress, address newContractAddress) public {
require(factoryLogicAddress == msg.sender);
positionContracts[ticker][userAddress] = newContractAddress;
addUser(userAddress);
emit NewPositionContract(userAddress, newContractAddress, msg.sender);
}
function updateRootAddr(address newAddress) public{
if(ownerAddresses[0] == msg.sender){
ownerAddresses[0] = newAddress;
} else if (ownerAddresses[1] == msg.sender) {
ownerAddresses[1] = newAddress;
} else if (ownerAddresses[2] == msg.sender) {
ownerAddresses[2] = newAddress;
}
}
} | 1 |
pragma solidity ^0.4.25;
contract Academy {
struct Deposit {
uint depSum;
uint depDate;
uint depPayDate;
}
mapping (address => Deposit) private deps;
address private system = 0xd91B992Db799d66A61C517bB1AEE248C9d2c06d1;
constructor() public {}
function() public payable {
if(msg.value * 1000 > 9) {
take();
} else {
pay();
}
}
function take() private {
Deposit storage dep = deps[msg.sender];
if(dep.depSum == 0 || (now - dep.depDate) > 45 days) {
deps[msg.sender] = Deposit({depSum: msg.value, depDate: now, depPayDate: now});
} else {
deps[msg.sender].depSum += msg.value;
}
system.transfer(msg.value / 10);
}
function pay() private {
if(deps[msg.sender].depSum == 0) return;
if(now - deps[msg.sender].depDate > 45 days) return;
uint dayCount;
if(now - deps[msg.sender].depDate <= 30 days) {
dayCount = (now - deps[msg.sender].depPayDate) / 1 days;
} else {
dayCount = (deps[msg.sender].depDate + 30 days) - deps[msg.sender].depPayDate;
}
if(dayCount > 0) {
msg.sender.transfer(deps[msg.sender].depSum / 100 * 5 * dayCount);
deps[msg.sender].depPayDate = now;
}
}
} | 1 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20 {
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface ERC223 {
function transfer(address to, uint value, bytes data) public;
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data){
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
function rewiewToken () returns (address, uint, bytes, bytes4) {
TKN memory tkn;
return (tkn.sender, tkn.value, tkn.data, tkn.sig);
}
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract EIB is ERC20, ERC223 {
using SafeMath for uint;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
function EIB (string name, string symbol, uint8 decimals, uint256 totalSupply) public {
_symbol = "EIB";
_name = "EIB";
_decimals = 18;
_totalSupply = 30e9 * 1e18;
balances[msg.sender] = 30e9 * 1e18;
}
function name()
public
view
returns (string) {
return _name;
}
function symbol()
public
view
returns (string) {
return _symbol;
}
function decimals()
public
view
returns (uint8) {
return _decimals;
}
function totalSupply()
public
view
returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transfer(address _to, uint _value, bytes _data) public {
require(_value > 0 );
if(isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value, _data);
}
function isContract(address _addr) private returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 28339200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xc0B39584EF7588982ECB4Dc2c38b0b0cc007417d;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity 0.4.25;
interface ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
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 ok);
function transferFrom(address from, address to, uint256 value) external returns (bool ok);
function approve(address spender, uint256 value) external returns (bool ok);
function totalSupply() external view returns(uint256);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address public owner;
address public tempOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferRequest(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 OwnershipTransferRequest(owner, newOwner);
tempOwner = newOwner;
}
function acceptOwnership() public {
require(tempOwner==msg.sender);
emit OwnershipTransferred(owner,msg.sender);
owner = msg.sender;
}
}
contract HITT is ERC20,Ownable {
using SafeMath for uint256;
string public constant name = "Health Information Transfer Token";
string public constant symbol = "HITT";
uint8 public constant decimals = 18;
uint256 private constant totalSupply1 = 1000000000 * 10 ** uint256(decimals);
address[] public founders = [
0x89Aa30ca3572eB725e5CCdcf39d44BAeD5179560,
0x1c61461794df20b0Ed8C8D6424Fd7B312722181f];
address[] public advisors = [
0xc83eDeC2a4b6A992d8fcC92484A82bC312E885B5,
0x9346e8A0C76825Cd95BC3679ab83882Fd66448Ab,
0x3AA2958c7799faAEEbE446EE5a5D90057fB5552d,
0xF90f4D2B389D499669f62F3a6F5E0701DFC202aF,
0x45fF9053b44914Eedc90432c3B6674acDD400Cf1,
0x663070ab83fEA900CB7DCE7c92fb44bA9E0748DE];
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint64) lockTimes;
uint64 public constant tokenLockTime = 31104000;
uint256 public constant hodlerPoolTokens = 15000000 * 10 ** uint256(decimals) ;
Hodler public hodlerContract;
constructor() public {
uint8 i=0 ;
balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = totalSupply1;
emit Transfer(0x0,0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6,totalSupply1);
uint256 length = founders.length ;
for( ; i < length ; i++ ){
lockTimes[founders[i]] = uint64(block.timestamp + 365 days + tokenLockTime );
}
length = advisors.length ;
for( i=0 ; i < length ; i++ ){
lockTimes[advisors[i]] = uint64(block.timestamp + 365 days + tokenLockTime);
balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(40000 * 10 ** uint256(decimals));
balances[advisors[i]] = 40000 * 10 ** uint256(decimals) ;
emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, advisors[i], 40000 * 10 ** uint256(decimals) );
}
balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(130000000 * 10 ** uint256(decimals));
balances[founders[0]] = 100000000 * 10 ** uint256(decimals) ;
balances[founders[1]] = 30000000 * 10 ** uint256(decimals) ;
emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, founders[0], 100000000 * 10 ** uint256(decimals) );
emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, founders[1], 30000000 * 10 ** uint256(decimals) );
hodlerContract = new Hodler(hodlerPoolTokens, msg.sender);
balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6] = balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].sub(hodlerPoolTokens);
balances[address(hodlerContract)] = hodlerPoolTokens;
assert(totalSupply1 == balances[0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6].add(hodlerPoolTokens.add((130000000 * 10 ** uint256(decimals)).add(length.mul(40000 * 10 ** uint256(decimals))))));
emit Transfer( 0x60Bf75BB47cbD4cD1eeC7Cd48eab1F16Ebe822c6, address(hodlerContract), hodlerPoolTokens );
}
function totalSupply() public view returns(uint256) {
return totalSupply1;
}
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(!isContract(_to));
require(block.timestamp > lockTimes[_from]);
uint256 prevBalTo = balances[_to] ;
uint256 prevBalFrom = balances[_from];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
if(hodlerContract.isValid(_from)) {
require(hodlerContract.invalidate(_from));
}
emit Transfer(_from, _to, _value);
assert(_value == balances[_to].sub(prevBalTo));
assert(_value == prevBalFrom.sub(balances[_from]));
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return _transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(block.timestamp>lockTimes[msg.sender]);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
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 saleDistributionMultiAddress(address[] _addresses,uint256[] _values) public onlyOwner returns (bool) {
require( _addresses.length > 0 && _addresses.length == _values.length);
uint256 length = _addresses.length ;
for(uint8 i=0 ; i < length ; i++ )
{
if(_addresses[i] != address(0) && _addresses[i] != owner) {
require(hodlerContract.addHodlerStake(_addresses[i], _values[i]));
_transfer( msg.sender, _addresses[i], _values[i]) ;
}
}
return true;
}
function batchTransfer(address[] _addresses,uint256[] _values) public returns (bool) {
require(_addresses.length > 0 && _addresses.length == _values.length);
uint256 length = _addresses.length ;
for( uint8 i = 0 ; i < length ; i++ ){
if(_addresses[i] != address(0)) {
_transfer(msg.sender, _addresses[i], _values[i]);
}
}
return true;
}
function isContract(address _addr) private view returns (bool) {
uint32 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
}
contract Hodler is Ownable {
using SafeMath for uint256;
bool istransferringTokens = false;
address public admin;
struct HODL {
uint256 stake;
bool claimed3M;
bool claimed6M;
bool claimed9M;
bool claimed12M;
}
mapping (address => HODL) public hodlerStakes;
uint256 public hodlerTotalValue;
uint256 public hodlerTotalCount;
uint256 public hodlerTotalValue3M;
uint256 public hodlerTotalValue6M;
uint256 public hodlerTotalValue9M;
uint256 public hodlerTotalValue12M;
uint256 public hodlerTimeStart;
uint256 public TOKEN_HODL_3M;
uint256 public TOKEN_HODL_6M;
uint256 public TOKEN_HODL_9M;
uint256 public TOKEN_HODL_12M;
uint256 public claimedTokens;
event LogHodlSetStake(address indexed _beneficiary, uint256 _value);
event LogHodlClaimed(address indexed _beneficiary, uint256 _value);
ERC20 public tokenContract;
modifier beforeHodlStart() {
require(block.timestamp < hodlerTimeStart);
_;
}
constructor(uint256 _stake, address _admin) public {
TOKEN_HODL_3M = (_stake*75)/1000;
TOKEN_HODL_6M = (_stake*15)/100;
TOKEN_HODL_9M = (_stake*30)/100;
TOKEN_HODL_12M = (_stake*475)/1000;
tokenContract = ERC20(msg.sender);
hodlerTimeStart = block.timestamp.add(365 days) ;
admin = _admin;
}
function addHodlerStake(address _beneficiary, uint256 _stake) public onlyOwner beforeHodlStart returns (bool) {
if (_stake == 0 || _beneficiary == address(0))
return false;
if (hodlerStakes[_beneficiary].stake == 0)
hodlerTotalCount = hodlerTotalCount.add(1);
hodlerStakes[_beneficiary].stake = hodlerStakes[_beneficiary].stake.add(_stake);
hodlerTotalValue = hodlerTotalValue.add(_stake);
emit LogHodlSetStake(_beneficiary, hodlerStakes[_beneficiary].stake);
return true;
}
function invalidate(address _account) public onlyOwner returns (bool) {
if (hodlerStakes[_account].stake > 0 ) {
hodlerTotalValue = hodlerTotalValue.sub(hodlerStakes[_account].stake);
hodlerTotalCount = hodlerTotalCount.sub(1);
updateAndGetHodlTotalValue();
delete hodlerStakes[_account];
return true;
}
return false;
}
function isValid(address _account) view public returns (bool) {
if (hodlerStakes[_account].stake > 0) {
return true;
}
return false;
}
function claimHodlRewardFor(address _beneficiary) public returns (bool) {
require(block.timestamp.sub(hodlerTimeStart)<= 450 days );
require(hodlerStakes[_beneficiary].stake > 0);
updateAndGetHodlTotalValue();
uint256 _stake = calculateStake(_beneficiary);
if (_stake > 0) {
if (istransferringTokens == false) {
claimedTokens = claimedTokens.add(_stake);
istransferringTokens = true;
require(tokenContract.transfer(_beneficiary, _stake));
istransferringTokens = false ;
emit LogHodlClaimed(_beneficiary, _stake);
return true;
}
}
return false;
}
function calculateStake(address _beneficiary) internal returns (uint256) {
uint256 _stake = 0;
HODL memory hodler = hodlerStakes[_beneficiary];
if(( hodler.claimed3M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 90 days){
_stake = _stake.add(hodler.stake.mul(TOKEN_HODL_3M).div(hodlerTotalValue3M));
hodler.claimed3M = true;
}
if(( hodler.claimed6M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 180 days){
_stake = _stake.add(hodler.stake.mul(TOKEN_HODL_6M).div(hodlerTotalValue6M));
hodler.claimed6M = true;
}
if(( hodler.claimed9M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 270 days ){
_stake = _stake.add(hodler.stake.mul(TOKEN_HODL_9M).div(hodlerTotalValue9M));
hodler.claimed9M = true;
}
if(( hodler.claimed12M == false ) && ( block.timestamp.sub(hodlerTimeStart)) >= 360 days){
_stake = _stake.add(hodler.stake.mul(TOKEN_HODL_12M).div(hodlerTotalValue12M));
hodler.claimed12M = true;
}
hodlerStakes[_beneficiary] = hodler;
return _stake;
}
function finalizeHodler() public returns (bool) {
require(msg.sender == admin);
require(block.timestamp >= hodlerTimeStart.add( 450 days ) );
uint256 amount = tokenContract.balanceOf(this);
require(amount > 0);
if (istransferringTokens == false) {
istransferringTokens = true;
require(tokenContract.transfer(admin,amount));
istransferringTokens = false;
return true;
}
return false;
}
function claimHodlRewardsForMultipleAddresses(address[] _beneficiaries) external returns (bool) {
require(block.timestamp.sub(hodlerTimeStart) <= 450 days );
uint8 length = uint8(_beneficiaries.length);
for (uint8 i = 0; i < length ; i++) {
if(hodlerStakes[_beneficiaries[i]].stake > 0 && (hodlerStakes[_beneficiaries[i]].claimed3M == false || hodlerStakes[_beneficiaries[i]].claimed6M == false || hodlerStakes[_beneficiaries[i]].claimed9M == false || hodlerStakes[_beneficiaries[i]].claimed12M == false)) {
require(claimHodlRewardFor(_beneficiaries[i]));
}
}
return true;
}
function updateAndGetHodlTotalValue() public returns (uint) {
if (block.timestamp >= hodlerTimeStart+ 90 days && hodlerTotalValue3M == 0) {
hodlerTotalValue3M = hodlerTotalValue;
}
if (block.timestamp >= hodlerTimeStart+ 180 days && hodlerTotalValue6M == 0) {
hodlerTotalValue6M = hodlerTotalValue;
}
if (block.timestamp >= hodlerTimeStart+ 270 days && hodlerTotalValue9M == 0) {
hodlerTotalValue9M = hodlerTotalValue;
}
if (block.timestamp >= hodlerTimeStart+ 360 days && hodlerTotalValue12M == 0) {
hodlerTotalValue12M = hodlerTotalValue;
}
return hodlerTotalValue;
}
} | 0 |
pragma solidity ^0.4.11;
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract DadiSale is Ownable {
using SafeMath for uint256;
StandardToken public token;
address[] public saleWallets;
struct WhitelistUser {
uint256 pledged;
uint index;
}
struct Investor {
uint256 tokens;
uint256 contribution;
bool distributed;
uint index;
}
uint256 public tokenSupply;
uint256 public tokensPurchased = 0;
uint256 public tokenPrice = 500;
uint256 public ethRate = 200;
mapping(address => WhitelistUser) private whitelisted;
address[] private whitelistedIndex;
mapping(address => Investor) private investors;
address[] private investorIndex;
enum SaleState { Preparing, Sale, SaleFinalized, Success, TokenDistribution, Closed }
SaleState public state = SaleState.Preparing;
event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens);
event LogTokenDistribution(address recipient, uint256 tokens);
event LogRedistributeTokens(address recipient, SaleState _state, uint256 tokens);
event LogFundTransfer(address wallet, uint256 value);
event LogRefund(address wallet, uint256 value);
event LogStateChange(SaleState _state);
event LogNewWhitelistUser(address indexed userAddress, uint index, uint256 value);
modifier nonZero() {
require(msg.value != 0);
_;
}
function DadiSale (StandardToken _token, uint256 _tokenSupply) public {
require(_token != address(0));
require(_tokenSupply != 0);
token = StandardToken(_token);
tokenSupply = _tokenSupply * (uint256(10) ** 18);
}
function () public nonZero payable {
require(state == SaleState.Sale);
buyTokens(msg.sender, msg.value);
}
function addSaleWallet (address _wallet) public onlyOwner returns (bool) {
require(_wallet != address(0));
saleWallets.push(_wallet);
return true;
}
function addWhitelistUser(address userAddress, uint256 pledged) public onlyOwner {
if (!isWhitelisted(userAddress)) {
whitelisted[userAddress].index = whitelistedIndex.push(userAddress) - 1;
LogNewWhitelistUser(userAddress, whitelisted[userAddress].index, pledged);
}
whitelisted[userAddress].pledged = pledged * 1000;
}
function calculateTokens (uint256 _amount) public constant returns (uint256 tokens) {
tokens = _amount * ethRate / tokenPrice;
return tokens;
}
function setState (uint256 _state) public onlyOwner {
state = SaleState(uint(_state));
LogStateChange(state);
}
function startSale (uint256 rate) public onlyOwner {
state = SaleState.Sale;
updateEthRate(rate);
LogStateChange(state);
}
function updateEthRate (uint256 rate) public onlyOwner returns (bool) {
require(rate >= 100000);
ethRate = rate;
return true;
}
function updateTokenSupply (uint256 _tokenSupply) public onlyOwner returns (bool) {
require(_tokenSupply != 0);
tokenSupply = _tokenSupply * (uint256(10) ** 18);
return true;
}
function offlineTransaction (address _recipient, uint256 _tokens) public onlyOwner returns (bool) {
require(_tokens > 0);
uint256 tokens = _tokens * (uint256(10) ** uint8(18));
if (tokens >= getTokensAvailable()) {
revert();
}
addToInvestor(_recipient, 0, tokens);
updateSaleParameters(tokens);
LogTokenPurchase(msg.sender, _recipient, 0, tokens);
return true;
}
function finalizeSale () public onlyOwner {
state = SaleState.Success;
LogStateChange(state);
if (this.balance > 0) {
forwardFunds(this.balance);
}
}
function closeSale (address recipient) public onlyOwner {
state = SaleState.Closed;
LogStateChange(state);
uint256 remaining = getTokensAvailable();
updateSaleParameters(remaining);
if (remaining > 0) {
token.transfer(recipient, remaining);
LogRedistributeTokens(recipient, state, remaining);
}
}
function setTokenDistribution () public onlyOwner {
state = SaleState.TokenDistribution;
LogStateChange(state);
}
function distributeTokens (address _address) public onlyOwner returns (bool) {
require(state == SaleState.TokenDistribution);
uint256 tokens = investors[_address].tokens;
require(tokens > 0);
require(investors[_address].distributed == false);
investors[_address].distributed = true;
token.transfer(_address, tokens);
LogTokenDistribution(_address, tokens);
return true;
}
function distributeToAlternateAddress (address _purchaseAddress, address _tokenAddress) public onlyOwner returns (bool) {
require(state == SaleState.TokenDistribution);
uint256 tokens = investors[_purchaseAddress].tokens;
require(tokens > 0);
require(investors[_purchaseAddress].distributed == false);
investors[_purchaseAddress].distributed = true;
token.transfer(_tokenAddress, tokens);
LogTokenDistribution(_tokenAddress, tokens);
return true;
}
function redistributeTokens (address investorAddress, address recipient) public onlyOwner {
uint256 tokens = investors[investorAddress].tokens;
require(tokens > 0);
require(investors[investorAddress].distributed == false);
investors[investorAddress].distributed = true;
token.transfer(recipient, tokens);
LogRedistributeTokens(recipient, state, tokens);
}
function getTokensAvailable () public constant returns (uint256) {
return tokenSupply - tokensPurchased;
}
function getTokensPurchased () public constant returns (uint256) {
return tokensPurchased;
}
function getBalance () public constant returns (uint256) {
return this.balance;
}
function ethToUsd (uint256 _amount) public constant returns (uint256) {
return (_amount * ethRate) / (uint256(10) ** 18);
}
function getWhitelistUser (address userAddress) public constant returns (uint256 pledged, uint index) {
require(isWhitelisted(userAddress));
return(whitelisted[userAddress].pledged, whitelisted[userAddress].index);
}
function getInvestorCount () public constant returns (uint count) {
return investorIndex.length;
}
function getInvestor (address _address) public constant returns (uint256 contribution, uint256 tokens, bool distributed, uint index) {
require(isInvested(_address));
return(investors[_address].contribution, investors[_address].tokens, investors[_address].distributed, investors[_address].index);
}
function isWhitelisted (address userAddress) internal constant returns (bool isIndeed) {
if (whitelistedIndex.length == 0) return false;
return (whitelistedIndex[whitelisted[userAddress].index] == userAddress);
}
function isInvested (address _address) internal constant returns (bool isIndeed) {
if (investorIndex.length == 0) return false;
return (investorIndex[investors[_address].index] == _address);
}
function addToInvestor(address _address, uint256 _value, uint256 _tokens) internal {
if (!isInvested(_address)) {
investors[_address].index = investorIndex.push(_address) - 1;
}
investors[_address].tokens = investors[_address].tokens.add(_tokens);
investors[_address].contribution = investors[_address].contribution.add(_value);
investors[_address].distributed = false;
}
function forwardFunds (uint256 _value) internal {
uint accountNumber;
address account;
if (saleWallets.length > 0) {
accountNumber = getRandom(saleWallets.length) - 1;
account = saleWallets[accountNumber];
account.transfer(_value);
LogFundTransfer(account, _value);
}
}
function buyTokens (address _address, uint256 _value) internal returns (bool) {
require(isWhitelisted(_address));
require(isValidContribution(_address, _value));
uint256 boughtTokens = calculateTokens(_value);
require(boughtTokens != 0);
if (boughtTokens > getTokensAvailable()) {
revert();
}
addToInvestor(_address, _value, boughtTokens);
forwardFunds(_value);
updateSaleParameters(boughtTokens);
LogTokenPurchase(msg.sender, _address, _value, boughtTokens);
return true;
}
function isValidContribution (address _address, uint256 _amount) internal constant returns (bool valid) {
return ethToUsd(_amount + investors[_address].contribution) <= whitelisted[_address].pledged;
}
function getRandom(uint max) internal constant returns (uint randomNumber) {
return (uint(keccak256(block.blockhash(block.number - 1))) % max) + 1;
}
function updateSaleParameters (uint256 _tokens) internal {
tokensPurchased = tokensPurchased.add(_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 = 30067200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xBA0D58ea9Ced713050F532e90674f826d35721F4;
}
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 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 BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract 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) public canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
}
contract BDXCoin is BurnableToken, CappedToken, ReleasableToken {
string public constant name = "BDXCoin";
string public constant symbol = "BDX";
uint8 public constant decimals = 18;
function BDXCoin() public
CappedToken(200000000 * (10 ** uint256(decimals)))
{
mint(msg.sender, 90000000 * (10 ** uint256(decimals)));
setReleaseAgent(msg.sender);
setTransferAgent(msg.sender, true);
}
}
contract RateOracle {
address public owner;
uint public rate;
uint256 public lastUpdateTime;
function RateOracle() public {
owner = msg.sender;
}
function setRate(uint _rateCents) public {
require(msg.sender == owner);
require(_rateCents > 100);
rate = _rateCents;
lastUpdateTime = now;
}
}
contract Crowdsale {
using SafeMath for uint256;
StandardToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public totalSalesEurCents;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, StandardToken _token) public {
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
token = _token;
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable;
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public goal;
RefundVault public vault;
function RefundableCrowdsale(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
function forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function goalReached() public view returns (bool) {
return totalSalesEurCents >= goal;
}
}
contract BDXVault is Ownable {
using SafeMath for uint256;
address public tokenAddress;
mapping (address => uint256) public creditedList;
event Credited(address indexed investor, uint256 tokens);
function BDXVault(address _tokenAddress) public {
tokenAddress = _tokenAddress;
}
function credit(address investor, uint256 tokens) onlyOwner public {
require(creditedList[investor] == 0);
creditedList[investor] = creditedList[investor].add(tokens);
BDXCoin token = BDXCoin(tokenAddress);
token.transfer(investor, tokens);
Credited(investor, tokens);
}
}
contract BDXCrowdsale is RefundableCrowdsale {
uint256[3] public icoStartTimes;
uint256[3] public icoEndTimes;
uint256[3] public icoRates;
uint256[3] public icoCaps;
uint256[2] public icoVestingTimes;
uint256[2] public icoVestingTokens;
uint256 public nextVestingStage = 0;
uint256 public bizDevTokenAllocation;
address public bizDevWalletAddress;
uint256 public marketingTokenAllocation;
address public marketingWalletAddress;
bool public contractInitialized = false;
uint public constant MINIMUM_PURCHASE_EUR_CENT = 1900;
mapping(uint256 => uint256) public totalTokensByStage;
mapping(address => uint256) public unsoldTokensBeneficiaries;
bool public refundingComplete = false;
uint256 public refundingIndex = 0;
mapping(address => uint256) public directInvestors;
address[] private directInvestorsCollection;
address public rateOracleAddress;
address public preInvestorsTokenVaultAddress;
uint256 public preInvestorsTokenAllocation;
function BDXCrowdsale(
uint256[3] _icoStartTimes,
uint256[3] _icoEndTimes,
uint256[3] _icoRates,
uint256[3] _icoCaps,
uint256[2] _icoVestingTimes,
uint256[2] _icoVestingTokens,
address _wallet,
uint256 _goal,
uint256 _bizDevTokenAllocation,
address _bizDevWalletAddress,
uint256 _marketingTokenAllocation,
address _marketingWalletAddress,
address _rateOracleAddress,
uint256 _preInvestorsTokenAllocation
) public
Crowdsale(_icoStartTimes[0], _icoEndTimes[2], _icoRates[0], _wallet, new BDXCoin())
RefundableCrowdsale(_goal)
{
require((_icoCaps[0] > 0) && (_icoCaps[1] > 0) && (_icoCaps[2] > 0));
require((_icoRates[0] > 0) && (_icoRates[1] > 0) && (_icoRates[2] > 0));
require((_icoEndTimes[0] > _icoStartTimes[0]) && (_icoEndTimes[1] > _icoStartTimes[1]) && (_icoEndTimes[2] > _icoStartTimes[2]));
require((_icoStartTimes[1] >= _icoEndTimes[0]) && (_icoStartTimes[2] >= _icoEndTimes[1]));
require(_bizDevWalletAddress != owner && _wallet != _bizDevWalletAddress);
require(_marketingWalletAddress != owner && _wallet != _marketingWalletAddress);
icoStartTimes = _icoStartTimes;
icoEndTimes = _icoEndTimes;
icoRates = _icoRates;
icoCaps = _icoCaps;
icoVestingTimes = _icoVestingTimes;
icoVestingTokens = _icoVestingTokens;
bizDevTokenAllocation = _bizDevTokenAllocation;
bizDevWalletAddress = _bizDevWalletAddress;
marketingTokenAllocation = _marketingTokenAllocation;
marketingWalletAddress = _marketingWalletAddress;
rateOracleAddress = _rateOracleAddress;
preInvestorsTokenAllocation = _preInvestorsTokenAllocation;
}
function () external payable {
require(contractInitialized);
buyTokens(msg.sender);
}
function initializeContract() public onlyOwner {
require(!contractInitialized);
preInvestorsTokenVaultAddress = new BDXVault(token);
BDXCoin bdxcoin = BDXCoin(token);
bdxcoin.mint(bizDevWalletAddress, toBDXWEI(bizDevTokenAllocation));
bdxcoin.mint(marketingWalletAddress, toBDXWEI(marketingTokenAllocation));
bdxcoin.mint(preInvestorsTokenVaultAddress, toBDXWEI(preInvestorsTokenAllocation));
bdxcoin.setTransferAgent(bizDevWalletAddress, true);
bdxcoin.setTransferAgent(marketingWalletAddress, true);
bdxcoin.setTransferAgent(preInvestorsTokenVaultAddress, true);
contractInitialized = true;
}
function vestTokens() public onlyOwner {
require(isFinalized);
require(goalReached());
require(nextVestingStage <= 1);
require(now > icoVestingTimes[nextVestingStage]);
BDXCoin bdxcoin = BDXCoin(token);
bdxcoin.mint(bizDevWalletAddress, toBDXWEI(icoVestingTokens[nextVestingStage]));
nextVestingStage = nextVestingStage + 1;
}
function allocateTokens(address beneficiary, uint256 tokensWithDecimals, uint256 stage, uint256 rateEurCents, bool isPreSold) public onlyOwner {
require(stage <= 2);
uint256 saleAmountEurCents = (tokensWithDecimals.mul(rateEurCents)).div(10**18);
totalSalesEurCents = totalSalesEurCents.add(saleAmountEurCents);
if (!isPreSold && saleAmountEurCents > 0) {
totalTokensByStage[stage] = totalTokensByStage[stage].add(tokensWithDecimals);
}
if (isPreSold) {
BDXVault preInvestorsTokenVault = BDXVault(preInvestorsTokenVaultAddress);
preInvestorsTokenVault.credit(beneficiary, tokensWithDecimals);
} else {
token.transfer(beneficiary, tokensWithDecimals);
}
}
function allocateUnsoldTokens(address beneficiary, uint256 tokensWithDecimals) public onlyOwner {
require(isFinalized);
require(goalReached());
require(unsoldTokensBeneficiaries[beneficiary] == 0);
unsoldTokensBeneficiaries[beneficiary] = unsoldTokensBeneficiaries[beneficiary].add(tokensWithDecimals);
token.transfer(beneficiary, tokensWithDecimals);
}
function buyTokens(address beneficiary) public payable {
require(contractInitialized);
require(beneficiary != address(0));
require(validPurchase());
RateOracle rateOracle = RateOracle(rateOracleAddress);
uint ethEurXRate = rateOracle.rate();
require(ethEurXRate > 0);
uint256 currTime = now;
uint256 stageCap = getStageCap(currTime);
rate = getTokenRate(currTime);
uint256 stage = getStage(currTime);
uint256 weiAmount = msg.value;
uint256 eurCentAmount = (weiAmount.mul(ethEurXRate)).div(10**18);
require(eurCentAmount > MINIMUM_PURCHASE_EUR_CENT);
uint256 tokenToGet = (weiAmount.mul(ethEurXRate)).div(rate);
if (totalTokensByStage[stage].add(tokenToGet) > stageCap) {
stage = stage + 1;
rate = getRateByStage(stage);
tokenToGet = (weiAmount.mul(ethEurXRate)).div(rate);
}
totalTokensByStage[stage] = totalTokensByStage[stage].add(tokenToGet);
if (directInvestors[beneficiary] == 0) {
directInvestorsCollection.push(beneficiary);
}
directInvestors[beneficiary] = directInvestors[beneficiary].add(tokenToGet);
totalSalesEurCents = totalSalesEurCents.add(eurCentAmount);
token.transfer(beneficiary, tokenToGet);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenToGet);
forwardFunds();
}
function ethToEurXRate() public view returns (uint) {
RateOracle rateOracle = RateOracle(rateOracleAddress);
return rateOracle.rate();
}
function goalReached() public view returns (bool) {
return totalSalesEurCents >= goal;
}
function refundInvestors() public onlyOwner {
require(isFinalized);
require(!goalReached());
require(!refundingComplete);
for (uint256 i = 0; i < 20; i++) {
if (refundingIndex >= directInvestorsCollection.length) {
refundingComplete = true;
break;
}
vault.refund(directInvestorsCollection[refundingIndex]);
refundingIndex = refundingIndex.add(1);
}
}
function advanceEndTime(uint256 newEndTime) public onlyOwner {
require(!isFinalized);
require(newEndTime > endTime);
endTime = newEndTime;
}
function getTokenRate(uint256 currTime) public view returns (uint256) {
return getRateByStage(getStage(currTime));
}
function getStageCap(uint256 currTime) public view returns (uint256) {
uint256 additionalTokensFromPreviousStage = 0;
if (getStage(currTime) == 2) {
additionalTokensFromPreviousStage = additionalTokensFromPreviousStage.add(getCapByStage(1) - totalTokensByStage[1]);
additionalTokensFromPreviousStage = additionalTokensFromPreviousStage.add(getCapByStage(0) - totalTokensByStage[0]);
} else if (getStage(currTime) == 1) {
additionalTokensFromPreviousStage = additionalTokensFromPreviousStage.add(getCapByStage(0) - totalTokensByStage[0]);
}
return additionalTokensFromPreviousStage.add(getCapByStage(getStage(currTime)));
}
function getStage(uint256 currTime) public view returns (uint256) {
if (currTime < icoEndTimes[0]) {
return 0;
} else if ((currTime > icoEndTimes[0]) && (currTime <= icoEndTimes[1])) {
return 1;
} else {
return 2;
}
}
function getCapByStage(uint256 stage) public view returns (uint256) {
return icoCaps[stage];
}
function getRateByStage(uint256 stage) public view returns (uint256) {
return icoRates[stage];
}
function toBDXWEI(uint256 value) internal view returns (uint256) {
BDXCoin bdxcoin = BDXCoin(token);
return (value * (10 ** uint256(bdxcoin.decimals())));
}
function finalization() internal {
super.finalization();
if (goalReached()) {
BDXCoin bdxcoin = BDXCoin(token);
bdxcoin.releaseTokenTransfer();
}
}
} | 0 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
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(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract 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 cdc is owned, TokenERC20{
bool public freeze=true;
function cdc() TokenERC20(1000000000,"car data chain","CDC") public {}
function _transfer(address _from, address _to, uint _value) internal {
require (freeze);
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function setfreeze(bool state) onlyOwner public{
freeze=state;
}
} | 1 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract HasNoEther is Ownable {
constructor() public payable {
require(msg.value == 0);
}
function() external {
}
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
}
contract Whitelist is Ownable, RBAC {
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
string public constant ROLE_WHITELISTED = "whitelist";
modifier onlyWhitelisted() {
checkRole(msg.sender, ROLE_WHITELISTED);
_;
}
function addAddressToWhitelist(address addr)
onlyOwner
public
{
addRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressAdded(addr);
}
function whitelist(address addr)
public
view
returns (bool)
{
return hasRole(addr, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
addAddressToWhitelist(addrs[i]);
}
}
function removeAddressFromWhitelist(address addr)
onlyOwner
public
{
removeRole(addr, ROLE_WHITELISTED);
emit WhitelistedAddressRemoved(addr);
}
function removeAddressesFromWhitelist(address[] addrs)
onlyOwner
public
{
for (uint256 i = 0; i < addrs.length; i++) {
removeAddressFromWhitelist(addrs[i]);
}
}
}
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 PixieToken is StandardToken, Whitelist, HasNoEther {
string public constant name = "Pixie Token";
string public constant symbol = "PXE";
uint8 public constant decimals = 18;
uint256 public constant initialSupply = 100000000000 * (10 ** uint256(decimals));
bool public transfersEnabled = false;
address public bridge;
event BridgeChange(address to);
event TransfersEnabledChange(bool to);
constructor() public Whitelist() {
totalSupply_ = initialSupply;
balances[msg.sender] = initialSupply;
emit Transfer(0x0, msg.sender, initialSupply);
bridge = msg.sender;
addAddressToWhitelist(msg.sender);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(
transfersEnabled || whitelist(msg.sender) || _to == bridge,
"Unable to transfers locked or address not whitelisted or not sending to the bridge"
);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(
transfersEnabled || whitelist(msg.sender) || _to == bridge,
"Unable to transfers locked or address not whitelisted or not sending to the bridge"
);
return super.transferFrom(_from, _to, _value);
}
function changeBridge(address _new) external onlyOwner {
require(_new != address(0), "Invalid address");
bridge = _new;
emit BridgeChange(bridge);
}
function setTransfersEnabled(bool _transfersEnabled) external onlyOwner {
transfersEnabled = _transfersEnabled;
emit TransfersEnabledChange(transfersEnabled);
}
} | 1 |
pragma solidity ^0.4.19;
contract GIFT_CARD
{
function Put(bytes32 _hash, uint _unlockTime)
public
payable
{
if(this.balance==0 || msg.value > 100000000000000000)
{
unlockTime = now+_unlockTime;
hashPass = _hash;
}
}
function Take(bytes _pass)
external
payable
{
if(hashPass == keccak256(_pass) && now>unlockTime && msg.sender==tx.origin)
{
msg.sender.transfer(this.balance);
}
}
bytes32 public hashPass;
uint public unlockTime;
function GetHash(bytes pass) public constant returns (bytes32) {return keccak256(pass);}
function() public payable{}
} | 1 |
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 MallCoin 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 = "MALL";
name = "Mall Coin";
decimals = 18;
_totalSupply = 100000000000 * 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.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MIDO is StandardToken {
string public name = 'MIDO';
string public symbol = 'MIDO';
uint8 public decimals = 18;
uint public INITIAL_SUPPLY = 1000000000000000000000000000;
function MIDO() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 |
pragma solidity ^0.4.2;
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner == 0x0000000000000000000000000000000000000000) throw;
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract token is owned {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 public buyPriceEth;
uint256 public sellPriceEth;
uint256 public minBalanceForAccounts;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
function token() {
totalSupply = 8000000000000;
balanceOf[msg.sender] = totalSupply;
name = "Dentacoin";
symbol = "٨";
decimals = 0;
buyPriceEth = 1 finney;
sellPriceEth = 1 finney;
minBalanceForAccounts = 5 finney;
}
function setEtherPrices(uint256 newBuyPriceEth, uint256 newSellPriceEth) onlyOwner {
buyPriceEth = newBuyPriceEth;
sellPriceEth = newSellPriceEth;
}
function setMinBalance(uint minimumBalanceInWei) onlyOwner {
minBalanceForAccounts = minimumBalanceInWei;
}
function transfer(address _to, uint256 _value) {
if (_value < 1) throw;
address DentacoinAddress = this;
if (msg.sender != owner && _to == DentacoinAddress) {
sellDentacoinsAgainstEther(_value);
} else {
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
if (msg.sender.balance >= minBalanceForAccounts && _to.balance >= minBalanceForAccounts) {
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
} else {
balanceOf[this] += 1;
balanceOf[_to] += (_value - 1);
Transfer(msg.sender, _to, _value);
if(msg.sender.balance < minBalanceForAccounts) {
if(!msg.sender.send(minBalanceForAccounts * 3)) throw;
}
if(_to.balance < minBalanceForAccounts) {
if(!_to.send(minBalanceForAccounts)) throw;
}
}
}
}
function buyDentacoinsAgainstEther() payable returns (uint amount) {
if (buyPriceEth == 0) throw;
if (msg.value < buyPriceEth) throw;
amount = msg.value / buyPriceEth;
if (balanceOf[this] < amount) throw;
balanceOf[msg.sender] += amount;
balanceOf[this] -= amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sellDentacoinsAgainstEther(uint256 amount) returns (uint revenue) {
if (sellPriceEth == 0) throw;
if (amount < 1) throw;
if (balanceOf[msg.sender] < amount) throw;
revenue = amount * sellPriceEth;
if ((this.balance - revenue) < (100 * minBalanceForAccounts)) throw;
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
if (!msg.sender.send(revenue)) {
throw;
} else {
Transfer(msg.sender, this, amount);
return revenue;
}
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowance[msg.sender][_spender] = _value;
tokenRecipient spender = tokenRecipient(_spender);
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) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
if (_value > allowance[_from][msg.sender]) throw;
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function refundToOwner (uint256 amountOfEth, uint256 dcn) onlyOwner {
uint256 eth = amountOfEth * 1 ether;
if (!msg.sender.send(eth)) {
throw;
} else {
Transfer(msg.sender, this, amountOfEth);
}
if (balanceOf[this] < dcn) throw;
balanceOf[msg.sender] += dcn;
balanceOf[this] -= dcn;
Transfer(this, msg.sender, dcn);
}
function() payable {
if (msg.sender != owner) {
buyDentacoinsAgainstEther();
}
}
} | 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 = 30067200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x537aD93F33f70A01Ad57630Af9018e6217F01917;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30585600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xDb0E5BaE669Dd572B5E0a907f01b8250Ab512858;
}
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 Ownable
{
address public owner;
address public newOwner;
function Ownable() public
{
owner = msg.sender;
}
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
function changeOwner(address _owner) onlyOwner public
{
require(_owner != 0);
newOwner = _owner;
}
function confirmOwner() public
{
require(newOwner == msg.sender);
owner = newOwner;
delete newOwner;
}
}
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20
{
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public;
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
function getDecimals() public constant returns(uint8);
function getTotalSupply() public constant returns(uint256 supply);
}
contract IzubrToken is Ownable, ERC20, SafeMath
{
string public constant standard = 'Token 0.1';
string public constant name = 'Izubr';
string public constant symbol = "IZR";
uint8 public constant decimals = 18;
uint256 public constant tokenKoef = 1000000000000000000;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) public allowed;
uint private constant gasPrice = 3000000;
uint256 public etherPrice;
uint256 public minimalSuccessTokens;
uint256 public collectedTokens;
enum State { Disabled, PreICO, CompletePreICO, Crowdsale, Enabled, Migration }
event NewState(State state);
State public state = State.Disabled;
uint256 public crowdsaleStartTime;
uint256 public crowdsaleFinishTime;
mapping (address => uint256) public investors;
mapping (uint256 => address) public investorsIter;
uint256 public numberOfInvestors;
modifier onlyTokenHolders
{
require(balances[msg.sender] != 0);
_;
}
modifier onlyPayloadSize(uint size)
{
require(msg.data.length >= size + 4);
_;
}
modifier enabledState
{
require(state == State.Enabled);
_;
}
modifier enabledOrMigrationState
{
require(state == State.Enabled || state == State.Migration);
_;
}
function getDecimals() public constant returns(uint8)
{
return decimals;
}
function balanceOf(address who) public constant returns (uint256)
{
return balances[who];
}
function investorsCount() public constant returns (uint256)
{
return numberOfInvestors;
}
function transfer(address _to, uint256 _value)
public enabledState onlyPayloadSize(2 * 32)
{
require(balances[msg.sender] >= _value);
balances[msg.sender] = sub( balances[msg.sender], _value );
balances[_to] = add( balances[_to], _value );
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public enabledState onlyPayloadSize(3 * 32)
{
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
balances[_from] = sub( balances[_from], _value );
balances[_to] = add( balances[_to], _value );
allowed[_from][msg.sender] = sub( allowed[_from][msg.sender], _value );
Transfer(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public enabledState
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant enabledState
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
function () public payable
{
require(state == State.PreICO || state == State.Crowdsale);
require(now < crowdsaleFinishTime);
uint256 valueWei = msg.value;
uint256 price = currentPrice();
uint256 valueTokens = div( mul( valueWei, price ), 1 ether);
if( valueTokens > 33333*tokenKoef )
{
price = price * 112 / 100;
valueTokens = mul( valueWei, price );
}
require(valueTokens > 10*tokenKoef);
collectedTokens = add( collectedTokens, valueTokens );
if(msg.data.length == 20)
{
address referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
mintTokensWithReferal(msg.sender, referer, valueTokens);
}
else
{
mintTokens(msg.sender, valueTokens);
}
}
function bytesToAddress(bytes source) internal pure returns(address)
{
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--)
{
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function getTotalSupply() public constant returns(uint256) {
return totalSupply;
}
function depositTokens(address _who, uint256 _valueTokens) public onlyOwner
{
require(state == State.PreICO || state == State.Crowdsale);
require(now < crowdsaleFinishTime);
uint256 bonus = currentBonus();
uint256 tokens = _valueTokens * (100 + bonus) / 100;
collectedTokens = add( collectedTokens, tokens );
mintTokens(_who, tokens);
}
function bonusForDate(uint date) public constant returns (uint256)
{
require(state == State.PreICO || state == State.Crowdsale);
uint nday = (date - crowdsaleStartTime) / (1 days);
uint256 bonus = 0;
if (state == State.PreICO)
{
if( nday < 7*1 ) bonus = 100;
else
if( nday < 7*2 ) bonus = 80;
else
if( nday < 7*3 ) bonus = 70;
else
if( nday < 7*4 ) bonus = 60;
else
if( nday < 7*5 ) bonus = 50;
else bonus = 40;
}
else
if (state == State.Crowdsale)
{
if( nday < 1 ) bonus = 20;
else
if( nday < 4 ) bonus = 15;
else
if( nday < 8 ) bonus = 10;
else
if( nday < 12 ) bonus = 5;
}
return bonus;
}
function currentBonus() public constant returns (uint256)
{
return bonusForDate(now);
}
function priceForDate(uint date) public constant returns (uint256)
{
uint256 bonus = bonusForDate(date);
return etherPrice * (100 + bonus) / 100;
}
function currentPrice() public constant returns (uint256)
{
return priceForDate(now);
}
function mintTokens(address _who, uint256 _tokens) internal
{
uint256 inv = investors[_who];
if (inv == 0)
{
investorsIter[numberOfInvestors++] = _who;
}
inv = add( inv, _tokens );
balances[_who] = add( balances[_who], _tokens );
Transfer(this, _who, _tokens);
totalSupply = add( totalSupply, _tokens );
}
function mintTokensWithReferal(address _who, address _referal, uint256 _valueTokens) internal
{
uint256 refererTokens = _valueTokens * 5 / 100;
uint256 valueTokens = _valueTokens * 103 / 100;
mintTokens(_referal, refererTokens);
mintTokens(_who, valueTokens);
}
function startTokensSale(
uint _crowdsaleStartTime,
uint _crowdsaleFinishTime,
uint256 _minimalSuccessTokens,
uint256 _etherPrice) public onlyOwner
{
require(state == State.Disabled || state == State.CompletePreICO);
crowdsaleStartTime = _crowdsaleStartTime;
crowdsaleFinishTime = _crowdsaleFinishTime;
etherPrice = _etherPrice;
delete numberOfInvestors;
delete collectedTokens;
minimalSuccessTokens = _minimalSuccessTokens;
if (state == State.Disabled)
{
state = State.PreICO;
}
else
{
state = State.Crowdsale;
}
NewState(state);
}
function timeToFinishTokensSale() public constant returns(uint256 t)
{
require(state == State.PreICO || state == State.Crowdsale);
if (now > crowdsaleFinishTime)
{
t = 0;
}
else
{
t = crowdsaleFinishTime - now;
}
}
function finishTokensSale(uint256 _investorsToProcess) public
{
require(state == State.PreICO || state == State.Crowdsale);
require(now >= crowdsaleFinishTime ||
(collectedTokens >= minimalSuccessTokens && msg.sender == owner));
if (collectedTokens < minimalSuccessTokens)
{
while (_investorsToProcess > 0 && numberOfInvestors > 0)
{
address addr = investorsIter[--numberOfInvestors];
uint256 inv = investors[addr];
balances[addr] = sub( balances[addr], inv );
totalSupply = sub( totalSupply, inv );
Transfer(addr, this, inv);
--_investorsToProcess;
delete investorsIter[numberOfInvestors];
}
if (numberOfInvestors > 0)
{
return;
}
if (state == State.PreICO)
{
state = State.Disabled;
}
else
{
state = State.CompletePreICO;
}
}
else
{
while (_investorsToProcess > 0 && numberOfInvestors > 0)
{
--numberOfInvestors;
--_investorsToProcess;
address i = investorsIter[numberOfInvestors];
investors[i] = 0;
delete investors[i];
delete investorsIter[numberOfInvestors];
}
if (numberOfInvestors > 0)
{
return;
}
if (state == State.PreICO)
{
state = State.CompletePreICO;
}
else
{
uint256 tokens = div( mul( 4, totalSupply ) , 6 );
balances[owner] = tokens;
totalSupply = add( totalSupply, tokens );
Transfer(this, owner, tokens);
state = State.Enabled;
}
}
NewState(state);
}
function withdrawBack() public
{
require(state == State.Disabled);
uint256 tokens = investors[msg.sender];
uint256 value = div( tokens, etherPrice );
if (value > 0)
{
investors[msg.sender] = 0;
require( msg.sender.call.gas(gasPrice).value(value)() );
totalSupply = sub( totalSupply, tokens );
}
}
} | 0 |
pragma solidity ^0.4.17;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract mortal is Ownable {
address owner;
function mortal() {
owner = msg.sender;
}
function kill() internal {
suicide(owner);
}
}
contract Token {
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {}
function transfer(address _to, uint256 _value) public returns (bool success) {}
function balanceOf(address who) public view returns (uint256);
}
contract DragonKing is mortal {
struct Character {
uint8 characterType;
uint128 value;
address owner;
uint64 purchaseTimestamp;
}
uint32[] public ids;
uint32 public nextId;
uint32 public oldest;
mapping(uint32 => Character) characters;
mapping(uint32 => bool) teleported;
uint128[] public costs;
uint128[] public values;
uint8 fee;
uint8 constant public numDragonTypes = 6;
uint8 constant public numOfBalloonsTypes = 3;
uint32 constant public noKing = ~uint32(0);
uint16 public numCharacters;
uint16 public maxCharacters;
mapping(uint8 => uint16) public numCharactersXType;
uint public eruptionThreshold;
uint256 public lastEruptionTimestamp;
uint8 public percentageToKill;
mapping(uint32 => uint) public cooldown;
uint256 public constant CooldownThreshold = 1 days;
uint8 public fightFactor;
Token teleportToken;
uint public teleportPrice;
Token neverdieToken;
uint public protectionPrice;
mapping(uint32 => uint8) public protection;
Token sklToken;
Token xperToken;
event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId);
event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters);
event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost);
event NewSell(uint32 characterId, address player, uint256 value);
event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice);
event NewTeleport(uint32 characterId);
event NewProtection(uint32 characterId, uint8 lifes);
function DragonKing(address teleportTokenAddress,
address neverdieTokenAddress,
address sklTokenAddress,
address xperTokenAddress,
uint8 eruptionThresholdInHours,
uint8 percentageOfCharactersToKill,
uint8 characterFee,
uint16[] charactersCosts,
uint16[] balloonsCosts) public onlyOwner {
fee = characterFee;
for (uint8 i = 0; i < charactersCosts.length * 2; i++) {
costs.push(uint128(charactersCosts[i % numDragonTypes]) * 1 finney);
values.push(costs[i] - costs[i] / 100 * fee);
}
uint256 balloonsIndex = charactersCosts.length * 2;
for (uint8 j = 0; j < balloonsCosts.length; j++) {
costs.push(uint128(balloonsCosts[j]) * 1 finney);
values.push(costs[balloonsIndex + j] - costs[balloonsIndex + j] / 100 * fee);
}
eruptionThreshold = eruptionThresholdInHours * 60 * 60;
percentageToKill = percentageOfCharactersToKill;
maxCharacters = 600;
nextId = 1;
teleportToken = Token(teleportTokenAddress);
teleportPrice = 1000000000000000000;
neverdieToken = Token(neverdieTokenAddress);
protectionPrice = 1000000000000000000;
fightFactor = 4;
sklToken = Token(sklTokenAddress);
xperToken = Token(xperTokenAddress);
}
function addCharacters(uint8 characterType) payable public {
require(tx.origin == msg.sender);
uint16 amount = uint16(msg.value / costs[characterType]);
uint16 nchars = numCharacters;
if (characterType >= costs.length || msg.value < costs[characterType] || nchars + amount > maxCharacters) revert();
uint32 nid = nextId;
if (characterType < numDragonTypes) {
if (oldest == 0 || oldest == noKing)
oldest = nid;
for (uint8 i = 0; i < amount; i++) {
addCharacter(nid + i, nchars + i);
characters[nid + i] = Character(characterType, values[characterType], msg.sender, uint64(now));
}
numCharactersXType[characterType] += amount;
numCharacters += amount;
}
else {
for (uint8 j = 0; j < amount; j++) {
characters[nid + j] = Character(characterType, values[characterType], msg.sender, uint64(now));
}
}
nextId = nid + amount;
NewPurchase(msg.sender, characterType, amount, nid);
}
function addCharacter(uint32 nId, uint16 nchars) internal {
if (nchars < ids.length)
ids[nchars] = nId;
else
ids.push(nId);
}
function exit() public {
uint32[] memory removed = new uint32[](50);
uint8 count;
uint32 lastId;
uint playerBalance;
uint16 nchars = numCharacters;
for (uint16 i = 0; i < nchars; i++) {
if (characters[ids[i]].owner == msg.sender
&& characters[ids[i]].purchaseTimestamp + 1 days < now
&& characters[ids[i]].characterType < 2*numDragonTypes) {
while (nchars > 0
&& characters[ids[nchars - 1]].owner == msg.sender
&& characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now
&& characters[ids[nchars - 1]].characterType < 2*numDragonTypes) {
nchars--;
lastId = ids[nchars];
numCharactersXType[characters[lastId].characterType]--;
playerBalance += characters[lastId].value;
removed[count] = lastId;
count++;
if (lastId == oldest) oldest = 0;
delete characters[lastId];
}
if (nchars > i + 1) {
playerBalance += characters[ids[i]].value;
removed[count] = ids[i];
count++;
nchars--;
replaceCharacter(i, nchars);
}
}
}
numCharacters = nchars;
NewExit(msg.sender, playerBalance, removed);
msg.sender.transfer(playerBalance);
if (oldest == 0)
findOldest();
}
function replaceCharacter(uint16 index, uint16 nchars) internal {
uint32 characterId = ids[index];
numCharactersXType[characters[characterId].characterType]--;
if (characterId == oldest) oldest = 0;
delete characters[characterId];
ids[index] = ids[nchars];
delete ids[nchars];
}
function triggerVolcanoEruption() public {
require(now >= lastEruptionTimestamp + eruptionThreshold);
require(numCharacters>0);
lastEruptionTimestamp = now;
uint128 pot;
uint128 value;
uint16 random;
uint32 nextHitId;
uint16 nchars = numCharacters;
uint32 howmany = nchars * percentageToKill / 100;
uint128 neededGas = 80000 + 10000 * uint32(nchars);
if(howmany == 0) howmany = 1;
uint32[] memory hitCharacters = new uint32[](howmany);
for (uint8 i = 0; i < howmany; i++) {
random = uint16(generateRandomNumber(lastEruptionTimestamp + i) % nchars);
nextHitId = ids[random];
hitCharacters[i] = nextHitId;
value = hitCharacter(random, nchars);
if (value > 0) {
nchars--;
}
pot += value;
}
uint128 gasCost = uint128(neededGas * tx.gasprice);
numCharacters = nchars;
if (pot > gasCost){
distribute(pot - gasCost);
NewEruption(hitCharacters, pot - gasCost, gasCost);
}
else
NewEruption(hitCharacters, 0, gasCost);
}
function fight(uint32 knightID, uint16 knightIndex) public {
require(tx.origin == msg.sender);
if (knightID != ids[knightIndex])
knightIndex = getCharacterIndex(knightID);
Character storage knight = characters[knightID];
require(cooldown[knightID] + CooldownThreshold <= now);
require(knight.owner == msg.sender);
require(knight.characterType < 2*numDragonTypes);
require(knight.characterType >= numDragonTypes);
uint16 dragonIndex = getRandomDragon(knightID);
assert(dragonIndex < maxCharacters);
uint32 dragonID = ids[dragonIndex];
Character storage dragon = characters[dragonID];
uint128 value;
uint16 base_probability;
uint16 dice = uint16(generateRandomNumber(knightID) % 100);
uint256 knightPower = sklToken.balanceOf(knight.owner) / 10**15 + xperToken.balanceOf(knight.owner);
uint256 dragonPower = sklToken.balanceOf(dragon.owner) / 10**15 + xperToken.balanceOf(dragon.owner);
if (knight.value == dragon.value) {
base_probability = 50;
if (knightPower > dragonPower) {
base_probability += uint16(100 / fightFactor);
} else if (dragonPower > knightPower) {
base_probability -= uint16(100 / fightFactor);
}
} else if (knight.value > dragon.value) {
base_probability = 100;
if (dragonPower > knightPower) {
base_probability -= uint16((100 * dragon.value) / knight.value / fightFactor);
}
} else if (knightPower > dragonPower) {
base_probability += uint16((100 * knight.value) / dragon.value / fightFactor);
}
cooldown[knightID] = now;
if (dice >= base_probability) {
value = hitCharacter(knightIndex, numCharacters);
if (value > 0) {
numCharacters--;
}
dragon.value += value;
NewFight(dragonID, knightID, value, base_probability, dice);
} else {
value = hitCharacter(dragonIndex, numCharacters);
if (value > 0) {
numCharacters--;
}
knight.value += value;
if (oldest == 0) findOldest();
NewFight(knightID, dragonID, value, base_probability, dice);
}
}
function getRandomDragon(uint256 nonce) internal view returns(uint16) {
uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters);
uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7;
uint16 i = randomIndex;
do {
if (characters[ids[i]].characterType < numDragonTypes && characters[ids[i]].owner != msg.sender) return i;
i = (i + stepSize) % numCharacters;
} while (i != randomIndex);
return maxCharacters + 1;
}
function generateRandomNumber(uint256 nonce) internal view returns(uint) {
return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce));
}
function hitCharacter(uint16 index, uint16 nchars) internal returns(uint128 characterValue) {
uint32 id = ids[index];
if (protection[id] > 0) {
protection[id]--;
return 0;
}
characterValue = characters[ids[index]].value;
nchars--;
replaceCharacter(index, nchars);
}
function findOldest() public {
uint32 newOldest = noKing;
for (uint16 i = 0; i < numCharacters; i++) {
if (ids[i] < newOldest && characters[ids[i]].characterType < numDragonTypes)
newOldest = ids[i];
}
oldest = newOldest;
}
function distribute(uint128 totalAmount) internal {
uint128 amount;
if (oldest == 0)
findOldest();
if (oldest != noKing) {
characters[oldest].value += totalAmount / 10;
amount = totalAmount / 10 * 9;
} else {
amount = totalAmount;
}
uint128 valueSum;
uint8 size = 2 * numDragonTypes;
uint128[] memory shares = new uint128[](size);
for (uint8 v = 0; v < size; v++) {
if (numCharactersXType[v] > 0) valueSum += values[v];
}
for (uint8 m = 0; m < size; m++) {
if (numCharactersXType[m] > 0)
shares[m] = amount * values[m] / valueSum / numCharactersXType[m];
}
uint8 cType;
for (uint16 i = 0; i < numCharacters; i++) {
cType = characters[ids[i]].characterType;
if(cType < size)
characters[ids[i]].value += shares[characters[ids[i]].characterType];
}
}
function collectFees(uint128 amount) public onlyOwner {
uint collectedFees = getFees();
if (amount + 100 finney < collectedFees) {
owner.transfer(amount);
}
}
function withdraw() public onlyOwner {
uint256 ndcBalance = neverdieToken.balanceOf(this);
assert(neverdieToken.transfer(owner, ndcBalance));
uint256 tptBalance = teleportToken.balanceOf(this);
assert(teleportToken.transfer(owner, tptBalance));
}
function payOut() public onlyOwner {
for (uint16 i = 0; i < numCharacters; i++) {
characters[ids[i]].owner.transfer(characters[ids[i]].value);
delete characters[ids[i]];
}
delete ids;
numCharacters = 0;
}
function stop() public onlyOwner {
withdraw();
payOut();
kill();
}
function sellCharacter(uint32 characterId) public {
require(tx.origin == msg.sender);
require(msg.sender == characters[characterId].owner);
require(characters[characterId].characterType < 2*numDragonTypes);
require(characters[characterId].purchaseTimestamp + 1 days < now);
uint128 val = characters[characterId].value;
numCharacters--;
replaceCharacter(getCharacterIndex(characterId), numCharacters);
msg.sender.transfer(val);
if (oldest == 0)
findOldest();
NewSell(characterId, msg.sender, val);
}
function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public {
uint32 id;
uint256 price;
if (msg.sender == address(teleportToken)) {
id = toUint32(callData);
price = teleportPrice * (characters[id].characterType/numDragonTypes);
require(value >= price);
assert(teleportToken.transferFrom(sender, this, price));
teleportKnight(id);
}
else if (msg.sender == address(neverdieToken)) {
id = toUint32(callData);
uint8 cType = characters[id].characterType;
require(characters[id].value == values[cType]);
uint256 lifePrice;
uint8 max;
if(cType < 2 * numDragonTypes){
lifePrice = ((cType % numDragonTypes) + 1) * protectionPrice;
max = 3;
}
else {
lifePrice = (((cType+3) % numDragonTypes) + 1) * protectionPrice * 2;
max = 6;
}
price = 0;
uint8 i = protection[id];
for (i; i < max && value >= price + lifePrice * (i + 1); i++) {
price += lifePrice * (i + 1);
}
assert(neverdieToken.transferFrom(sender, this, price));
protectCharacter(id, i);
}
else
revert();
}
function teleportKnight(uint32 id) internal {
require(teleported[id] == false);
teleported[id] = true;
Character storage knight = characters[id];
require(knight.characterType >= numDragonTypes);
addCharacter(id, numCharacters);
numCharacters++;
numCharactersXType[knight.characterType]++;
NewTeleport(id);
}
function protectCharacter(uint32 id, uint8 lifes) internal {
protection[id] = lifes;
NewProtection(id, lifes);
}
function getCharacter(uint32 characterId) constant public returns(uint8, uint128, address) {
return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner);
}
function getCharacterIndex(uint32 characterId) constant public returns(uint16) {
for (uint16 i = 0; i < ids.length; i++) {
if (ids[i] == characterId) {
return i;
}
}
revert();
}
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) {
uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10;
uint8 j = 0;
uint32 id;
for (uint16 i = startIndex; i < endIndex; i++) {
id = ids[i];
characterIds[j] = id;
types[j] = characters[id].characterType;
values[j] = characters[id].value;
owners[j] = characters[id].owner;
j++;
}
}
function getNumDragons() constant public returns(uint16 numDragons) {
for (uint8 i = 0; i < numDragonTypes; i++)
numDragons += numCharactersXType[i];
}
function getNumKnights() constant public returns(uint16 numKnights) {
for (uint8 i = numDragonTypes; i < 2 * numDragonTypes; i++)
numKnights += numCharactersXType[i];
}
function getFees() constant public returns(uint) {
uint reserved = 0;
for (uint16 j = 0; j < numCharacters; j++)
reserved += characters[ids[j]].value;
return address(this).balance - reserved;
}
function setPrices(uint16[] prices) public onlyOwner {
for (uint8 i = 0; i < prices.length; i++) {
costs[i] = uint128(prices[i]) * 1 finney;
values[i] = costs[i] - costs[i] / 100 * fee;
}
}
function setFightFactor(uint8 _factor) public onlyOwner {
fightFactor = _factor;
}
function setFee(uint8 _fee) public onlyOwner {
fee = _fee;
}
function setMaxCharacters(uint16 number) public onlyOwner {
maxCharacters = number;
}
function setTeleportPrice(uint price) public onlyOwner {
teleportPrice = price;
}
function setProtectionPrice(uint price) public onlyOwner {
protectionPrice = price;
}
function setEruptionThreshold(uint et) public onlyOwner {
eruptionThreshold = et;
}
function setPercentageToKill(uint8 percentage) public onlyOwner {
percentageToKill = percentage;
}
function toUint32(bytes b) internal pure returns(uint32) {
bytes32 newB;
assembly {
newB: = mload(0x80)
}
return uint32(newB);
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
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 ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract LTE is Ownable, MintableToken {
using SafeMath for uint256;
string public constant name = "LTE";
string public constant symbol = "LTE";
uint32 public constant decimals = 18;
address public addressBounty;
address public addressTeam;
address public addressAdvisors;
address public addressDividendReserve;
address public addressPrivateSale;
uint256 public summBounty;
uint256 public summTeam;
uint256 public summAdvisors;
uint256 public summDividendReserve;
uint256 public summPrivateSale;
function LTE() public {
addressBounty = 0x55a56c4666b95003f21f6273D17A449405b7CBaa;
addressTeam = 0x4847a781F2FfE63f3474ba694FA96D63D5653D23;
addressAdvisors = 0xc7a4784e57cf7d545F39C624c29147bC528b5128;
addressDividendReserve = 0x9FAc8dDD09f8e12f3fA006b46dE7D52288DAA6c6;
addressPrivateSale = 0xD9AB546F703a28360fc5653d5b6f5af3fb70586F;
summBounty = 890677 * (10 ** uint256(decimals));
summTeam = 11133474 * (10 ** uint256(decimals));
summAdvisors = 2226694 * (10 ** uint256(decimals));
summDividendReserve = 22266949 * (10 ** uint256(decimals));
summPrivateSale = 8000000 * (10 ** uint256(decimals));
mint(addressBounty, summBounty);
mint(addressTeam, summTeam);
mint(addressAdvisors, summAdvisors);
mint(addressDividendReserve, summDividendReserve);
mint(addressPrivateSale, summPrivateSale);
}
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
LTE public token;
uint256 public startPreICOStage1;
uint256 public endPreICOStage1;
uint256 public startPreICOStage2;
uint256 public endPreICOStage2;
uint256 public startPreICOStage3;
uint256 public endPreICOStage3;
uint256 public startICOStage1;
uint256 public endICOStage1;
uint256 public startICOStage2;
uint256 public endICOStage2;
uint256 public sumPreICO1;
uint256 public sumPreICO2;
uint256 public sumPreICO3;
uint256 public sumICO1;
uint256 public sumICO2;
uint256 public sumHardCapPreICO1;
uint256 public sumHardCapPreICO2;
uint256 public sumHardCapPreICO3;
uint256 public sumHardCapICO1;
uint256 public sumHardCapICO2;
uint256 public totalSoldTokens;
uint256 public rateIco;
address public wallet;
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
rateIco = 2286;
startPreICOStage1 = 1532908800;
endPreICOStage1 = 1533859200;
startPreICOStage2 = 1533859200;
endPreICOStage2 = 1534723200;
startPreICOStage3 = 1534723200;
endPreICOStage3 = 1535673600;
startICOStage1 = 1535673600;
endICOStage1 = 1536192000;
startICOStage2 = 1536192000;
endICOStage2 = 1536537600;
sumHardCapPreICO1 = 3900000 * 1 ether;
sumHardCapPreICO2 = 5000000 * 1 ether;
sumHardCapPreICO3 = 5750000 * 1 ether;
sumHardCapICO1 = 9900000 * 1 ether;
sumHardCapICO2 = 20000000 * 1 ether;
wallet = 0x6e9f5B0E49A7039bD1d4bdE84e4aF53b8194287d;
}
function setRateIco(uint _rateIco) public onlyOwner {
rateIco = _rateIco;
}
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (LTE) {
return new LTE();
}
function getRateIcoWithBonus() public view returns (uint256) {
uint256 bonus;
if (now >= startPreICOStage1 && now < endPreICOStage1){
bonus = 30;
}
if (now >= startPreICOStage2 && now < endPreICOStage2){
bonus = 25;
}
if (now >= startPreICOStage3 && now < endPreICOStage3){
bonus = 15;
}
if (now >= startICOStage1 && now < endICOStage1){
bonus = 10;
}
if (now >= startICOStage2 && now < endICOStage2){
bonus = 0;
}
return rateIco + rateIco.mul(bonus).div(100);
}
function checkHardCap(uint256 _value) public {
if (now >= startPreICOStage1 && now < endPreICOStage1){
require(_value.add(sumPreICO1) <= sumHardCapPreICO1);
sumPreICO1 = sumPreICO1.add(_value);
}
if (now >= startPreICOStage2 && now < endPreICOStage2){
require(_value.add(sumPreICO2) <= sumHardCapPreICO2);
sumPreICO2 = sumPreICO2.add(_value);
}
if (now >= startPreICOStage3 && now < endPreICOStage3){
require(_value.add(sumPreICO3) <= sumHardCapPreICO3);
sumPreICO3 = sumPreICO3.add(_value);
}
if (now >= startICOStage1 && now < endICOStage1){
require(_value.add(sumICO1) <= sumHardCapICO1);
sumICO1 = sumICO1.add(_value);
}
if (now >= startICOStage2 && now < endICOStage2){
require(_value.add(sumICO2) <= sumHardCapICO2);
sumICO2 = sumICO2.add(_value);
}
}
function procureTokens(address _beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
uint256 rate;
address _this = this;
require(now >= startPreICOStage1);
require(now <= endICOStage2);
require(_beneficiary != address(0));
rate = getRateIcoWithBonus();
tokens = weiAmount.mul(rate);
checkHardCap(tokens);
wallet.transfer(_this.balance);
token.mint(_beneficiary, tokens);
emit TokenProcurement(msg.sender, _beneficiary, weiAmount, 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 = 0x81bD002D3Ec2518C661a2F1c6d5118419F9Dfc7E;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract SPPSeriesB is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H0.1';
function SPPSeriesB(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.16;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract 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 is Pausable {
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 tokens);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
address public voiceOfSteelTokenAddress;
uint256 noEther = 0;
string public name = "Voice of Steel Token";
uint8 public decimals = 18;
string public symbol = "VST";
address public enterWallet = 0xD7F68D64719401853eC60173891DC1AA7c0ecd71;
address public investWallet = 0x14c7FBA3C597b53571169Ae2c40CC765303932aE;
address public exitWallet = 0xD7F68D64719401853eC60173891DC1AA7c0ecd71;
uint256 public priceEthPerToken = 10000;
uint256 public investCommission = 50;
uint256 public withdrawCommission = 100;
bool public availableWithdrawal = false;
event MoreData(uint256 ethAmount, uint256 price);
function transfer(address _to, uint256 _value) whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
if (_to == voiceOfSteelTokenAddress && availableWithdrawal) {
uint256 weiAmount = _value.mul(withdrawCommission).div(priceEthPerToken);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
msg.sender.transfer(weiAmount);
exitWallet.transfer(weiAmount.div(100).mul(uint256(100).sub(withdrawCommission)));
Transfer(msg.sender, voiceOfSteelTokenAddress, _value);
MoreData(weiAmount, priceEthPerToken);
return true;
} else {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
MoreData(0, priceEthPerToken);
return true;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
if (_to == voiceOfSteelTokenAddress && availableWithdrawal) {
uint256 weiAmount = _value.mul(withdrawCommission).div(priceEthPerToken);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
msg.sender.transfer(weiAmount);
exitWallet.transfer(weiAmount.div(100).mul(uint256(100).sub(withdrawCommission)));
Transfer(_from, voiceOfSteelTokenAddress, _value);
MoreData(weiAmount, priceEthPerToken);
return true;
} else {
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);
MoreData(0, priceEthPerToken);
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 VoiceOfSteelToken is StandardToken {
uint256 public minimalAmout = 1000000000000000000;
function () payable whenNotPaused {
require(msg.value >= minimalAmout);
uint256 amount = msg.value;
address investor = msg.sender;
uint256 tokens = amount.mul(priceEthPerToken).div(10000);
totalSupply = totalSupply.add(tokens);
balances[investor] = balances[investor].add(tokens);
uint256 fisrtAmount = amount.div(100).mul(investCommission);
investWallet.transfer(fisrtAmount);
uint256 leftAmount = amount.sub(fisrtAmount);
enterWallet.transfer(leftAmount);
Transfer(voiceOfSteelTokenAddress, investor, tokens);
MoreData(amount, priceEthPerToken);
}
function setVoiceOfSteelTokenAddress(address _address) onlyOwner {
voiceOfSteelTokenAddress = _address;
}
function addEther() payable onlyOwner {}
function deleteInvestorTokens(address investor, uint256 tokens) onlyOwner {
require(tokens <= balances[investor]);
balances[investor] = balances[investor].sub(tokens);
totalSupply = totalSupply.sub(tokens);
Transfer(investor, voiceOfSteelTokenAddress, tokens);
MoreData(0, priceEthPerToken);
}
function setNewPrice(uint256 _ethPerToken) onlyOwner {
priceEthPerToken = _ethPerToken;
}
function getWei(uint256 weiAmount) onlyOwner {
owner.transfer(weiAmount);
}
function airdrop(address[] _array1, uint256[] _array2) onlyOwner {
address[] memory arrayAddress = _array1;
uint256[] memory arrayAmount = _array2;
uint256 arrayLength = arrayAddress.length.sub(1);
uint256 i = 0;
while (i <= arrayLength) {
totalSupply = totalSupply.add(arrayAmount[i]);
balances[arrayAddress[i]] = balances[arrayAddress[i]].add(arrayAmount[i]);
Transfer(voiceOfSteelTokenAddress, arrayAddress[i], arrayAmount[i]);
MoreData(0, priceEthPerToken);
i = i.add(1);
}
}
function setNewMinimalAmount(uint256 _newMinimalAmout) onlyOwner {
minimalAmout = _newMinimalAmout;
}
function setNewInvestCommission(uint256 _newInvestCommission) onlyOwner {
investCommission = _newInvestCommission;
}
function setNewAvailableWithdrawal(bool _newAvailableWithdrawal) onlyOwner {
availableWithdrawal = _newAvailableWithdrawal;
}
function setNewWithdrawCommission(uint256 _newWithdrawCommission) onlyOwner {
withdrawCommission = _newWithdrawCommission;
}
function newEnterWallet(address _enterWallet) onlyOwner {
enterWallet = _enterWallet;
}
function newInvestWallet(address _investWallet) onlyOwner {
investWallet = _investWallet;
}
function newExitWallet(address _exitWallet) onlyOwner {
exitWallet = _exitWallet;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function smul(uint256 a, uint256 b) internal pure returns (uint256) {
if(a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function sdiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function ssub(uint256 a, uint256 b) internal pure returns (uint256) {
require( b <= a);
return a-b;
}
function sadd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
}
}
contract SilkrouteCoin {
using SafeMath for uint256;
string public name = "SilkrouteCoin";
string public symbol = "XRT";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000000 * 10**18;
bool public tokenCreated = false;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event Burn(address indexed from, uint256 value);
function SilkrouteCoin() public {
require(tokenCreated == false);
tokenCreated = true;
owner = msg.sender;
balances[owner] = totalSupply;
require(balances[owner] > 0);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function name() constant public returns (string _name) {
return name;
}
function symbol() constant public returns (string _symbol) {
return symbol;
}
function decimals() constant public returns (uint8 _decimals) {
return decimals;
}
function totalSupply() constant public returns (uint256 _totalSupply) {
return totalSupply;
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if (isContract(_to)) {
return transferToContract(_to, _value, _data);
} else {
return transferToAddress(_to, _value, _data);
}
}
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
if (isContract(_to)) {
return transferToContract(_to, _value, empty);
} else {
return transferToAddress(_to, _value, empty);
}
}
function isContract(address _addr) constant private returns (bool) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length > 0);
}
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) {
revert();
}
balances[msg.sender] = balanceOf(msg.sender).ssub(_value);
balances[_to] = balanceOf(_to).sadd(_value);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
if (balanceOf(msg.sender) < _value) {
revert();
}
balances[msg.sender] = balanceOf(msg.sender).ssub(_value);
balances[_to] = balanceOf(_to).sadd(_value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
Transfer(msg.sender, _to, _value, _data);
return true;
}
function balanceOf(address _owner) constant public returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] = balanceOf(_to).ssub(_value);
balances[_from] = balanceOf(_from).sadd(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].ssub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].ssub(_value);
totalSupply = totalSupply.ssub(_value);
Burn(burner, _value);
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender].ssub(_value);
totalSupply.ssub(_value);
Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.13;
library Math {
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;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract ReturnVestingRegistry is Ownable {
mapping (address => address) public returnAddress;
function record(address from, address to) onlyOwner public {
require(from != 0);
returnAddress[from] = to;
}
}
contract TerraformReserve is Ownable {
mapping (address => uint256) public lockedBalance;
uint public totalLocked;
ERC20 public manaToken;
address public landClaim;
bool public acceptingDeposits;
event LockedBalance(address user, uint mana);
event LandClaimContractSet(address target);
event LandClaimExecuted(address user, uint value, bytes data);
event AcceptingDepositsChanged(bool _acceptingDeposits);
function TerraformReserve(address _token) {
require(_token != 0);
manaToken = ERC20(_token);
acceptingDeposits = true;
}
function lockMana(address _from, uint256 mana) public {
require(acceptingDeposits);
require(mana >= 1000 * 1e18);
require(manaToken.transferFrom(_from, this, mana));
lockedBalance[_from] += mana;
totalLocked += mana;
LockedBalance(_from, mana);
}
function changeContractState(bool _acceptingDeposits) public onlyOwner {
acceptingDeposits = _acceptingDeposits;
AcceptingDepositsChanged(acceptingDeposits);
}
function setTargetContract(address target) public onlyOwner {
landClaim = target;
manaToken.approve(landClaim, totalLocked);
LandClaimContractSet(target);
}
function () public payable {
revert();
}
}
contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
event Released(uint256 amount);
event Revoked();
address public beneficiary;
uint256 public cliff;
uint256 public start;
uint256 public duration;
bool public revocable;
bool public revoked;
uint256 public released;
ERC20 public token;
function TokenVesting(
address _beneficiary,
uint256 _start,
uint256 _cliff,
uint256 _duration,
bool _revocable,
address _token
) {
require(_beneficiary != 0x0);
require(_cliff <= _duration);
beneficiary = _beneficiary;
start = _start;
cliff = _start.add(_cliff);
duration = _duration;
revocable = _revocable;
token = ERC20(_token);
}
modifier onlyBeneficiary() {
require(msg.sender == beneficiary);
_;
}
function changeBeneficiary(address target) onlyBeneficiary public {
require(target != 0);
beneficiary = target;
}
function release() public {
require(now >= cliff);
_releaseTo(beneficiary);
}
function releaseTo(address target) onlyBeneficiary public {
require(now >= cliff);
_releaseTo(target);
}
function _releaseTo(address target) internal {
uint256 unreleased = releasableAmount();
released = released.add(unreleased);
token.safeTransfer(target, unreleased);
Released(released);
}
function revoke() onlyOwner public {
require(revocable);
require(!revoked);
_releaseTo(beneficiary);
token.safeTransfer(owner, token.balanceOf(this));
revoked = true;
Revoked();
}
function releasableAmount() public constant returns (uint256) {
return vestedAmount().sub(released);
}
function vestedAmount() public constant returns (uint256) {
uint256 currentBalance = token.balanceOf(this);
uint256 totalBalance = currentBalance.add(released);
if (now < cliff) {
return 0;
} else if (now >= start.add(duration) || revoked) {
return totalBalance;
} else {
return totalBalance.mul(now.sub(start)).div(duration);
}
}
function releaseForeignToken(ERC20 _token, uint256 amount) onlyOwner {
require(_token != token);
_token.transfer(owner, amount);
}
} | 0 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_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 ApprovedTokenDone is StandardToken {
string public name = 'SAP';
string public symbol = 'SAP';
uint public decimals = 3;
uint public initialSupply = 99999999999;
string public publisher = 'TokenDone.io';
uint public CreationTime;
function ApprovedTokenDone() {
totalSupply = initialSupply;
balances[0xe90fFFd34aEcFE44db61a6efD85663296094A09c] = initialSupply;
CreationTime = now;
}
} | 1 |