source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^0.4.24;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
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 ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract 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 BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistAdminAdded(address indexed account);
event BlacklistAdminRemoved(address indexed account);
Roles.Role private _blacklistAdmins;
constructor () internal {
_addBlacklistAdmin(msg.sender);
}
modifier onlyBlacklistAdmin() {
require(isBlacklistAdmin(msg.sender));
_;
}
function isBlacklistAdmin(address account) public view returns (bool) {
return _blacklistAdmins.has(account);
}
function addBlacklistAdmin(address account) public onlyBlacklistAdmin {
_addBlacklistAdmin(account);
}
function renounceBlacklistAdmin() public {
_removeBlacklistAdmin(msg.sender);
}
function _addBlacklistAdmin(address account) internal {
_blacklistAdmins.add(account);
emit BlacklistAdminAdded(account);
}
function _removeBlacklistAdmin(address account) internal {
_blacklistAdmins.remove(account);
emit BlacklistAdminRemoved(account);
}
}
contract BlacklistedRole is BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistedAdded(address indexed account);
event BlacklistedRemoved(address indexed account);
Roles.Role private _blacklisteds;
modifier onlyBlacklisted() {
require(isBlacklisted(msg.sender));
_;
}
modifier onlyNotBlacklisted() {
require(!isBlacklisted(msg.sender));
_;
}
function isBlacklisted(address account) public view returns (bool) {
return _blacklisteds.has(account);
}
function addBlacklisted(address account) public onlyBlacklistAdmin {
_addBlacklisted(account);
}
function removeBlacklisted(address account) public onlyBlacklistAdmin {
_removeBlacklisted(account);
}
function renounceBlacklisted() public {
_removeBlacklisted(msg.sender);
}
function _addBlacklisted(address account) internal {
_blacklisteds.add(account);
emit BlacklistedAdded(account);
}
function _removeBlacklisted(address account) internal {
_blacklisteds.remove(account);
emit BlacklistedRemoved(account);
}
}
contract GiniAuditioTokenPausable is ERC20, Pausable, BlacklistedRole {
function transfer(address to, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused onlyNotBlacklisted returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused onlyNotBlacklisted returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused onlyNotBlacklisted returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract GiniAuditio is ERC20Detailed, ERC20Burnable, ERC20Mintable, GiniAuditioTokenPausable {
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 3000000000 * (10 ** uint256(DECIMALS));
constructor () public ERC20Detailed("Gini Audition Coin", "GAC", DECIMALS) {
_mint(msg.sender, INITIAL_SUPPLY);
}
} | 1 |
pragma solidity ^0.4.11;
contract MultiSigWallet {
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()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
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);
OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
tx.executed = true;
if (tx.destination.call.value(tx.value)(tx.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
} | 1 |
pragma solidity ^0.4.11;
contract ERC20 {
function balanceOf(address who) constant public returns (uint);
function allowance(address owner, address spender) constant public returns (uint);
function transfer(address to, uint value) public returns (bool ok);
function transferFrom(address from, address to, uint value) public returns (bool ok);
function approve(address spender, uint value) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract TokenController {
function proxyPayment(address _owner) payable public returns(bool);
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract Controlled {
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
function changeController(address _newController) onlyController public {
controller = _newController;
}
}
contract ControlledToken is ERC20, Controlled {
uint256 constant MAX_UINT256 = 2**256 - 1;
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
string public name;
uint8 public decimals;
string public symbol;
string public version = '1.0';
uint256 public totalSupply;
function ControlledToken(
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(msg.sender, _to, _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) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _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) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _value));
}
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function generateTokens(address _owner, uint _amount ) onlyController returns (bool) {
uint curTotalSupply = totalSupply;
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
totalSupply = curTotalSupply + _amount;
balances[_owner] = previousBalanceTo + _amount;
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply;
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
totalSupply = curTotalSupply - _amount;
balances[_owner] = previousBalanceFrom - _amount;
Transfer(_owner, 0, _amount);
return true;
}
function () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
ControlledToken token = ControlledToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract IZXToken is ControlledToken {
function IZXToken() ControlledToken( 1, 'IZX Token', 18, 'IZX' ) public {}
} | 1 |
pragma solidity ^0.4.25;
contract EtherDice {
address public constant OWNER = 0x8026F25c6f898b4afE03d05F87e6c2AFeaaC3a3D;
address public constant MANAGER = 0xD25BD6c44D6cF3C0358AB30ed5E89F2090409a79;
uint constant public FEE_PERCENT = 2;
uint public minBet;
uint public maxBet;
uint public currentIndex;
uint public lockBalance;
uint public betsOfBlock;
uint entropy;
struct Bet {
address player;
uint deposit;
uint block;
}
Bet[] public bets;
event PlaceBet(uint num, address player, uint bet, uint payout, uint roll, uint time);
modifier onlyOwner {
require(OWNER == msg.sender || MANAGER == msg.sender);
_;
}
function() public payable {
if (msg.value > 0) {
createBet(msg.sender, msg.value);
}
placeBets();
}
function createBet(address _player, uint _deposit) internal {
require(_deposit >= minBet && _deposit <= maxBet);
uint lastBlock = bets.length > 0 ? bets[bets.length-1].block : 0;
require(block.number != lastBlock || betsOfBlock < 50);
uint fee = _deposit * FEE_PERCENT / 100;
uint betAmount = _deposit - fee;
require(betAmount * 2 + fee <= address(this).balance - lockBalance);
sendOwner(fee);
betsOfBlock = block.number != lastBlock ? 1 : betsOfBlock + 1;
lockBalance += betAmount * 2;
bets.push(Bet(_player, _deposit, block.number));
}
function placeBets() internal {
for (uint i = currentIndex; i < bets.length; i++) {
Bet memory bet = bets[i];
if (bet.block < block.number) {
uint betAmount = bet.deposit - bet.deposit * FEE_PERCENT / 100;
lockBalance -= betAmount * 2;
if (block.number - bet.block <= 256) {
entropy = uint(keccak256(abi.encodePacked(blockhash(bet.block), entropy)));
uint roll = entropy % 100 + 1;
uint payout = roll < 50 ? betAmount * 2 : 0;
send(bet.player, payout);
emit PlaceBet(i + 1, bet.player, bet.deposit, payout, roll, now);
}
} else {
break;
}
}
currentIndex = i;
}
function send(address _receiver, uint _amount) internal {
if (_amount > 0 && _receiver != address(0)) {
_receiver.send(_amount);
}
}
function sendOwner(uint _amount) internal {
send(OWNER, _amount * 7 / 10);
send(MANAGER, _amount * 3 / 10);
}
function withdraw(uint _amount) public onlyOwner {
require(_amount <= address(this).balance - lockBalance);
sendOwner(_amount);
}
function configure(uint _minBet, uint _maxBet) onlyOwner public {
require(_minBet >= 0.001 ether && _minBet <= _maxBet);
minBet = _minBet;
maxBet = _maxBet;
}
function deposit() public payable {}
function totalBets() public view returns(uint) {
return bets.length;
}
} | 1 |
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;
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 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)
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue)
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 IDealToken {
function spend(address _from, uint256 _value) returns (bool success);
}
contract DealToken is MintableToken, IDealToken {
string public constant name = "Deal Token";
string public constant symbol = "DEAL";
uint8 public constant decimals = 0;
uint256 public totalTokensBurnt = 0;
event TokensSpent(address indexed _from, uint256 _value);
function DealToken() public { }
function spend(address _from, uint256 _value) public returns (bool) {
require(_value > 0);
if (balances[_from] < _value || allowed[_from][msg.sender] < _value) {
return false;
}
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
totalTokensBurnt = totalTokensBurnt.add(_value);
totalSupply = totalSupply.sub(_value);
TokensSpent(_from, _value);
return true;
}
function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes _extraData) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
_spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
contract IForeground {
function payConversionFromTransaction(uint256 _promotionID, address _recipientAddress, uint256 _transactionAmount) external payable;
function createNewDynamicPaymentAddress(uint256 _promotionID, address referrer) external;
function calculateTotalDue(uint256 _promotionID, uint256 _transactionAmount) public constant returns (uint256 _totalPayment);
}
contract IForegroundEnabledContract {
function receiveEtherFromForegroundAddress(address _originatingAddress, address _relayedFromAddress, uint256 _promotionID, address _referrer) public payable;
}
contract ForegroundCaller is IForegroundEnabledContract {
IForeground public foreground;
function ForegroundCaller(IForeground _foreground) public {
foreground = _foreground;
}
event EtherReceivedFromRelay(address indexed _originatingAddress, uint256 indexed _promotionID, address indexed _referrer);
event ForegroundPaymentResult(bool _success, uint256 indexed _promotionID, address indexed _referrer, uint256 _value);
event ContractFunded(address indexed _sender, uint256 _value);
function receiveEtherFromForegroundAddress(address _originatingAddress, address _relayedFromAddress, uint256 _promotionID, address _referrer) public payable {
EtherReceivedFromRelay(_originatingAddress, _promotionID, _referrer);
uint256 _amountSpent = receiveEtherFromRelayAddress(_originatingAddress, msg.value);
uint256 _paymentToForeground = foreground.calculateTotalDue(_promotionID, _amountSpent);
bool _success = foreground.call.gas(1000000).value(_paymentToForeground)(bytes4(keccak256("payConversionFromTransaction(uint256,address,uint256)")), _promotionID, _referrer, _amountSpent);
ForegroundPaymentResult(_success, _promotionID, _referrer, msg.value);
}
function receiveEtherFromRelayAddress(address _originatingAddress, uint256 _amount) internal returns(uint256 _amountSpent);
function fundContract() payable {
ContractFunded(msg.sender, msg.value);
}
}
contract ForegroundTokenSale is Ownable, ForegroundCaller {
using SafeMath for uint256;
uint256 public publicTokenCap;
uint256 public baseTokenPrice;
uint256 public currentTokenPrice;
uint256 public priceStepDuration;
uint256 public numberOfParticipants;
uint256 public maxSaleBalance;
uint256 public minSaleBalance;
uint256 public saleBalance;
uint256 public tokenBalance;
uint256 public startBlock;
uint256 public endBlock;
address public saleWalletAddress;
address public devTeamTokenAddress;
address public partnershipsTokenAddress;
address public incentiveTokenAddress;
address public bountyTokenAddress;
bool public saleSuspended = false;
DealToken public dealToken;
SaleState public state;
mapping (address => PurchaseDetails) public purchases;
struct PurchaseDetails {
uint256 tokenBalance;
uint256 weiBalance;
}
enum SaleState {Prepared, Deployed, Configured, Started, Ended, Finalized, Refunding}
event TokenPurchased(address indexed buyer, uint256 tokenPrice, uint256 txAmount, uint256 actualPurchaseAmount, uint256 refundedAmount, uint256 tokensPurchased);
event SaleStarted();
event SaleEnded();
event Claimed(address indexed owner, uint256 tokensClaimed);
event Refunded(address indexed buyer, uint256 amountRefunded);
modifier evaluateSaleState {
require(saleSuspended == false);
if (state == SaleState.Configured && block.number >= startBlock) {
state = SaleState.Started;
SaleStarted();
}
if (state == SaleState.Started) {
setCurrentPrice();
}
if (state == SaleState.Started && (block.number > endBlock || saleBalance == maxSaleBalance || maxSaleBalance.sub(saleBalance) < currentTokenPrice)) {
endSale();
}
if (state == SaleState.Ended) {
finalizeSale();
}
_;
}
function ForegroundTokenSale(
uint256 _publicTokenCap,
uint256 _tokenFloor,
uint256 _tokenRate,
IForeground _foreground
)
public
ForegroundCaller(_foreground)
{
require(_publicTokenCap > 0);
require(_tokenFloor < _publicTokenCap);
require(_tokenRate > 0);
publicTokenCap = _publicTokenCap;
baseTokenPrice = _tokenRate;
currentTokenPrice = _tokenRate;
dealToken = new DealToken();
maxSaleBalance = publicTokenCap.mul(currentTokenPrice);
minSaleBalance = _tokenFloor.mul(currentTokenPrice);
state = SaleState.Deployed;
}
function() public payable {
purchaseToken(msg.sender, msg.value);
}
function configureSale(
uint256 _startBlock,
uint256 _endBlock,
address _wallet,
uint256 _stepDuration,
address _devAddress,
address _partnershipAddress,
address _incentiveAddress,
address _bountyAddress
)
external
onlyOwner
{
require(_startBlock >= block.number);
require(_endBlock >= _startBlock);
require(state == SaleState.Deployed);
require(_wallet != 0x0);
require(_stepDuration > 0);
require(_devAddress != 0x0);
require(_partnershipAddress != 0x0);
require(_incentiveAddress != 0x0);
require(_bountyAddress != 0x0);
state = SaleState.Configured;
startBlock = _startBlock;
endBlock = _endBlock;
saleWalletAddress = _wallet;
priceStepDuration = _stepDuration;
devTeamTokenAddress = _devAddress;
partnershipsTokenAddress = _partnershipAddress;
incentiveTokenAddress = _incentiveAddress;
bountyTokenAddress = _bountyAddress;
}
function claimToken()
external
evaluateSaleState
{
require(state == SaleState.Finalized);
require(purchases[msg.sender].tokenBalance > 0);
uint256 _tokensPurchased = purchases[msg.sender].tokenBalance;
purchases[msg.sender].tokenBalance = 0;
purchases[msg.sender].weiBalance = 0;
dealToken.transfer(msg.sender, _tokensPurchased);
Claimed(msg.sender, _tokensPurchased);
}
function claimRefund()
external
{
require(state == SaleState.Refunding);
uint256 _amountToRefund = purchases[msg.sender].weiBalance;
require(_amountToRefund > 0);
purchases[msg.sender].weiBalance = 0;
purchases[msg.sender].tokenBalance = 0;
msg.sender.transfer(_amountToRefund);
Refunded(msg.sender, _amountToRefund);
}
function suspendSale(bool _suspend)
external
onlyOwner
{
saleSuspended = _suspend;
}
function updateLatestSaleState()
external
evaluateSaleState
returns (uint256)
{
return uint256(state);
}
function purchaseToken(address _recipient, uint256 _amount)
internal
evaluateSaleState
returns (uint256)
{
require(state == SaleState.Started);
require(_amount >= currentTokenPrice);
uint256 _saleRemainingBalance = maxSaleBalance.sub(saleBalance);
bool _shouldEndSale = false;
uint256 _amountToRefund = _amount % currentTokenPrice;
uint256 _purchaseAmount = _amount.sub(_amountToRefund);
if (_saleRemainingBalance < _purchaseAmount) {
uint256 _endOfSaleRefund = _saleRemainingBalance % currentTokenPrice;
_amountToRefund = _amountToRefund.add(_purchaseAmount.sub(_saleRemainingBalance).add(_endOfSaleRefund));
_purchaseAmount = _saleRemainingBalance.sub(_endOfSaleRefund);
_shouldEndSale = true;
}
if (purchases[_recipient].tokenBalance == 0) {
numberOfParticipants = numberOfParticipants.add(1);
}
uint256 _tokensPurchased = _purchaseAmount.div(currentTokenPrice);
purchases[_recipient].tokenBalance = purchases[_recipient].tokenBalance.add(_tokensPurchased);
purchases[_recipient].weiBalance = purchases[_recipient].weiBalance.add(_purchaseAmount);
saleBalance = saleBalance.add(_purchaseAmount);
tokenBalance = tokenBalance.add(_tokensPurchased);
if (_purchaseAmount == _saleRemainingBalance || _shouldEndSale) {
endSale();
}
if (_amountToRefund > 0) {
_recipient.transfer(_amountToRefund);
}
TokenPurchased(_recipient, currentTokenPrice, msg.value, _purchaseAmount, _amountToRefund, _tokensPurchased);
return _purchaseAmount;
}
function receiveEtherFromRelayAddress(address _originatingAddress, uint256 _amount)
internal
returns (uint256)
{
return purchaseToken(_originatingAddress, _amount);
}
function setCurrentPrice() internal {
uint256 _saleBlockNo = block.number - startBlock;
uint256 _numIncreases = _saleBlockNo.div(priceStepDuration);
if (_numIncreases == 0)
currentTokenPrice = baseTokenPrice;
else if (_numIncreases == 1)
currentTokenPrice = 0.06 ether;
else if (_numIncreases == 2)
currentTokenPrice = 0.065 ether;
else if (_numIncreases == 3)
currentTokenPrice = 0.07 ether;
else if (_numIncreases >= 4)
currentTokenPrice = 0.08 ether;
}
function endSale() internal {
if (saleBalance < minSaleBalance) {
state = SaleState.Refunding;
} else {
state = SaleState.Ended;
mintTokens();
}
SaleEnded();
}
function mintTokens() internal {
uint256 _totalTokens = (tokenBalance.mul(10 ** 18)).div(74).mul(100);
dealToken.mint(address(this), _totalTokens.div(10 ** 18));
dealToken.transfer(devTeamTokenAddress, (_totalTokens.mul(10).div(100)).div(10 ** 18));
dealToken.transfer(partnershipsTokenAddress, (_totalTokens.mul(10).div(100)).div(10 ** 18));
dealToken.transfer(incentiveTokenAddress, (_totalTokens.mul(4).div(100)).div(10 ** 18));
dealToken.transfer(bountyTokenAddress, (_totalTokens.mul(2).div(100)).div(10 ** 18));
dealToken.finishMinting();
}
function finalizeSale() internal {
state = SaleState.Finalized;
saleWalletAddress.transfer(this.balance);
}
}
contract ITokenRecipient {
function receiveApproval(address _from, uint _value, address _token, bytes _extraData);
} | 1 |
pragma solidity ^0.4.21;
library CampaignLibrary {
struct Campaign {
bytes32 bidId;
uint price;
uint budget;
uint startDate;
uint endDate;
bool valid;
address owner;
}
function convertCountryIndexToBytes(uint[] countries) internal returns (uint,uint,uint){
uint countries1 = 0;
uint countries2 = 0;
uint countries3 = 0;
for(uint i = 0; i < countries.length; i++){
uint index = countries[i];
if(index<256){
countries1 = countries1 | uint(1) << index;
} else if (index<512) {
countries2 = countries2 | uint(1) << (index - 256);
} else {
countries3 = countries3 | uint(1) << (index - 512);
}
}
return (countries1,countries2,countries3);
}
}
contract AdvertisementStorage {
mapping (bytes32 => CampaignLibrary.Campaign) campaigns;
mapping (address => bool) allowedAddresses;
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyAllowedAddress() {
require(allowedAddresses[msg.sender]);
_;
}
event CampaignCreated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
event CampaignUpdated
(
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
);
function AdvertisementStorage() public {
owner = msg.sender;
allowedAddresses[msg.sender] = true;
}
function setAllowedAddresses(address newAddress, bool isAllowed) public onlyOwner {
allowedAddresses[newAddress] = isAllowed;
}
function getCampaign(bytes32 campaignId)
public
view
returns (
bytes32,
uint,
uint,
uint,
uint,
bool,
address
) {
CampaignLibrary.Campaign storage campaign = campaigns[campaignId];
return (
campaign.bidId,
campaign.price,
campaign.budget,
campaign.startDate,
campaign.endDate,
campaign.valid,
campaign.owner
);
}
function setCampaign (
bytes32 bidId,
uint price,
uint budget,
uint startDate,
uint endDate,
bool valid,
address owner
)
public
onlyAllowedAddress {
CampaignLibrary.Campaign memory campaign = campaigns[campaign.bidId];
campaign = CampaignLibrary.Campaign({
bidId: bidId,
price: price,
budget: budget,
startDate: startDate,
endDate: endDate,
valid: valid,
owner: owner
});
emitEvent(campaign);
campaigns[campaign.bidId] = campaign;
}
function getCampaignPriceById(bytes32 bidId)
public
view
returns (uint) {
return campaigns[bidId].price;
}
function setCampaignPriceById(bytes32 bidId, uint price)
public
onlyAllowedAddress
{
campaigns[bidId].price = price;
emitEvent(campaigns[bidId]);
}
function getCampaignBudgetById(bytes32 bidId)
public
view
returns (uint) {
return campaigns[bidId].budget;
}
function setCampaignBudgetById(bytes32 bidId, uint newBudget)
public
onlyAllowedAddress
{
campaigns[bidId].budget = newBudget;
emitEvent(campaigns[bidId]);
}
function getCampaignStartDateById(bytes32 bidId)
public
view
returns (uint) {
return campaigns[bidId].startDate;
}
function setCampaignStartDateById(bytes32 bidId, uint newStartDate)
public
onlyAllowedAddress
{
campaigns[bidId].startDate = newStartDate;
emitEvent(campaigns[bidId]);
}
function getCampaignEndDateById(bytes32 bidId)
public
view
returns (uint) {
return campaigns[bidId].endDate;
}
function setCampaignEndDateById(bytes32 bidId, uint newEndDate)
public
onlyAllowedAddress
{
campaigns[bidId].endDate = newEndDate;
emitEvent(campaigns[bidId]);
}
function getCampaignValidById(bytes32 bidId)
public
view
returns (bool) {
return campaigns[bidId].valid;
}
function setCampaignValidById(bytes32 bidId, bool isValid)
public
onlyAllowedAddress
{
campaigns[bidId].valid = isValid;
emitEvent(campaigns[bidId]);
}
function getCampaignOwnerById(bytes32 bidId)
public
view
returns (address) {
return campaigns[bidId].owner;
}
function setCampaignOwnerById(bytes32 bidId, address newOwner)
public
onlyAllowedAddress
{
campaigns[bidId].owner = newOwner;
emitEvent(campaigns[bidId]);
}
function emitEvent(CampaignLibrary.Campaign campaign) private {
if (campaigns[campaign.bidId].bidId == 0x0) {
emit CampaignCreated(
campaign.bidId,
campaign.price,
campaign.budget,
campaign.startDate,
campaign.endDate,
campaign.valid,
campaign.owner
);
} else {
emit CampaignUpdated(
campaign.bidId,
campaign.price,
campaign.budget,
campaign.startDate,
campaign.endDate,
campaign.valid,
campaign.owner
);
}
}
}
contract AdvertisementFinance {
mapping (address => uint256) balanceDevelopers;
mapping (address => bool) developerExists;
address[] developers;
address owner;
address advertisementContract;
address advStorageContract;
AppCoins appc;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAds() {
require(advertisementContract == msg.sender);
_;
}
modifier onlyOwnerOrAds() {
require(msg.sender == owner || msg.sender == advertisementContract);
_;
}
function AdvertisementFinance (address _addrAppc)
public {
owner = msg.sender;
appc = AppCoins(_addrAppc);
advStorageContract = 0x0;
}
function setAdsStorageAddress (address _addrStorage) external onlyOwnerOrAds {
reset();
advStorageContract = _addrStorage;
}
function setAdsContractAddress (address _addrAdvert) external onlyOwner {
if (advertisementContract != 0x0){
Advertisement adsContract = Advertisement(advertisementContract);
address adsStorage = adsContract.getAdvertisementStorageAddress();
require (adsStorage == advStorageContract);
}
advertisementContract = _addrAdvert;
}
function increaseBalance(address _developer, uint256 _value)
public onlyAds{
if(developerExists[_developer] == false){
developers.push(_developer);
developerExists[_developer] = true;
}
balanceDevelopers[_developer] += _value;
}
function pay(address _developer, address _destination, uint256 _value)
public onlyAds{
appc.transfer( _destination, _value);
balanceDevelopers[_developer] -= _value;
}
function withdraw(address _developer, uint256 _value) public onlyOwnerOrAds {
require(balanceDevelopers[_developer] >= _value);
appc.transfer(_developer, _value);
balanceDevelopers[_developer] -= _value;
}
function reset() public onlyOwnerOrAds {
for(uint i = 0; i < developers.length; i++){
withdraw(developers[i],balanceDevelopers[developers[i]]);
}
}
}
contract ERC20Interface {
function name() public view returns(bytes32);
function symbol() public view returns(bytes32);
function balanceOf (address _owner) public view returns(uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (uint);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract AppCoins is ERC20Interface{
address public owner;
bytes32 private token_name;
bytes32 private token_symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balances;
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 AppCoins() public {
owner = msg.sender;
token_name = "AppCoins";
token_symbol = "APPC";
uint256 _totalSupply = 1000000;
totalSupply = _totalSupply * 10 ** uint256(decimals);
balances[owner] = totalSupply;
}
function name() public view returns(bytes32) {
return token_name;
}
function symbol() public view returns(bytes32) {
return token_symbol;
}
function balanceOf (address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
function _transfer(address _from, address _to, uint _value) internal returns (bool) {
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint previousBalances = balances[_from] + balances[_to];
balances[_from] -= _value;
balances[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
}
function transfer (address _to, uint256 _amount) public returns (bool success) {
if( balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (uint) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return allowance[_from][msg.sender];
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balances[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract Advertisement {
struct ValidationRules {
bool vercode;
bool ipValidation;
bool country;
uint constipDailyConversions;
uint walletDailyConversions;
}
uint constant expectedPoALength = 12;
ValidationRules public rules;
bytes32[] bidIdList;
AppCoins appc;
AdvertisementStorage advertisementStorage;
AdvertisementFinance advertisementFinance;
address public owner;
mapping (address => mapping (bytes32 => bool)) userAttributions;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
event PoARegistered(bytes32 bidId, string packageName,uint64[] timestampList,uint64[] nonceList,string walletName, bytes2 countryCode);
event Error(string func, string message);
event CampaignInformation
(
bytes32 bidId,
address owner,
string ipValidator,
string packageName,
uint[3] countries,
uint[] vercodes
);
function Advertisement (address _addrAppc, address _addrAdverStorage, address _addrAdverFinance) public {
rules = ValidationRules(false, true, true, 2, 1);
owner = msg.sender;
appc = AppCoins(_addrAppc);
advertisementStorage = AdvertisementStorage(_addrAdverStorage);
advertisementFinance = AdvertisementFinance(_addrAdverFinance);
}
struct Map {
mapping (address => uint256) balance;
address[] devs;
}
function upgradeFinance (address addrAdverFinance) public onlyOwner {
AdvertisementFinance newAdvFinance = AdvertisementFinance(addrAdverFinance);
Map storage devBalance;
for(uint i = 0; i < bidIdList.length; i++) {
address dev = advertisementStorage.getCampaignOwnerById(bidIdList[i]);
if(devBalance.balance[dev] == 0){
devBalance.devs.push(dev);
}
devBalance.balance[dev] += advertisementStorage.getCampaignBudgetById(bidIdList[i]);
}
for(i = 0; i < devBalance.devs.length; i++) {
advertisementFinance.pay(devBalance.devs[i],address(newAdvFinance),devBalance.balance[devBalance.devs[i]]);
newAdvFinance.increaseBalance(devBalance.devs[i],devBalance.balance[devBalance.devs[i]]);
}
uint256 oldBalance = appc.balances(address(advertisementFinance));
require(oldBalance == 0);
advertisementFinance = newAdvFinance;
}
function upgradeStorage (address addrAdverStorage) public onlyOwner {
for(uint i = 0; i < bidIdList.length; i++) {
cancelCampaign(bidIdList[i]);
}
delete bidIdList;
advertisementFinance.reset();
advertisementFinance.setAdsStorageAddress(addrAdverStorage);
advertisementStorage = AdvertisementStorage(addrAdverStorage);
}
function getAdvertisementStorageAddress() public view returns(address _contract) {
require (msg.sender == address(advertisementFinance));
return address(advertisementStorage);
}
function createCampaign (
string packageName,
uint[3] countries,
uint[] vercodes,
uint price,
uint budget,
uint startDate,
uint endDate)
external {
require(budget >= price);
require(endDate >= startDate);
CampaignLibrary.Campaign memory newCampaign;
newCampaign.price = price;
newCampaign.startDate = startDate;
newCampaign.endDate = endDate;
if(appc.allowance(msg.sender, address(this)) < budget){
emit Error("createCampaign","Not enough allowance");
return;
}
appc.transferFrom(msg.sender, address(advertisementFinance), budget);
advertisementFinance.increaseBalance(msg.sender,budget);
newCampaign.budget = budget;
newCampaign.owner = msg.sender;
newCampaign.valid = true;
newCampaign.bidId = uintToBytes(bidIdList.length);
addCampaign(newCampaign);
emit CampaignInformation(
newCampaign.bidId,
newCampaign.owner,
"",
packageName,
countries,
vercodes);
}
function addCampaign(CampaignLibrary.Campaign campaign) internal {
bidIdList.push(campaign.bidId);
advertisementStorage.setCampaign(
campaign.bidId,
campaign.price,
campaign.budget,
campaign.startDate,
campaign.endDate,
campaign.valid,
campaign.owner
);
}
function registerPoA (
string packageName, bytes32 bidId,
uint64[] timestampList, uint64[] nonces,
address appstore, address oem,
string walletName, bytes2 countryCode) external {
if(!isCampaignValid(bidId)){
emit Error(
"registerPoA","Registering a Proof of attention to a invalid campaign");
return;
}
if(timestampList.length != expectedPoALength){
emit Error("registerPoA","Proof-of-attention should have exactly 12 proofs");
return;
}
if(timestampList.length != nonces.length){
emit Error(
"registerPoA","Nounce list and timestamp list must have same length");
return;
}
for (uint i = 0; i < timestampList.length - 1; i++) {
uint timestampDiff = (timestampList[i+1]-timestampList[i]);
if((timestampDiff / 1000) != 10){
emit Error(
"registerPoA","Timestamps should be spaced exactly 10 secounds");
return;
}
}
if(userAttributions[msg.sender][bidId]){
emit Error(
"registerPoA","User already registered a proof of attention for this campaign");
return;
}
userAttributions[msg.sender][bidId] = true;
payFromCampaign(bidId, appstore, oem);
emit PoARegistered(bidId, packageName, timestampList, nonces, walletName, countryCode);
}
function cancelCampaign (bytes32 bidId) public {
address campaignOwner = getOwnerOfCampaign(bidId);
require(owner == msg.sender || campaignOwner == msg.sender);
uint budget = getBudgetOfCampaign(bidId);
advertisementFinance.withdraw(campaignOwner, budget);
advertisementStorage.setCampaignBudgetById(bidId, 0);
advertisementStorage.setCampaignValidById(bidId, false);
}
function getCampaignValidity(bytes32 bidId) public view returns(bool){
return advertisementStorage.getCampaignValidById(bidId);
}
function getPriceOfCampaign (bytes32 bidId) public view returns(uint) {
return advertisementStorage.getCampaignPriceById(bidId);
}
function getStartDateOfCampaign (bytes32 bidId) public view returns(uint) {
return advertisementStorage.getCampaignStartDateById(bidId);
}
function getEndDateOfCampaign (bytes32 bidId) public view returns(uint) {
return advertisementStorage.getCampaignEndDateById(bidId);
}
function getBudgetOfCampaign (bytes32 bidId) public view returns(uint) {
return advertisementStorage.getCampaignBudgetById(bidId);
}
function getOwnerOfCampaign (bytes32 bidId) public view returns(address) {
return advertisementStorage.getCampaignOwnerById(bidId);
}
function getBidIdList() public view returns(bytes32[]) {
return bidIdList;
}
function isCampaignValid(bytes32 bidId) public view returns(bool) {
uint startDate = advertisementStorage.getCampaignStartDateById(bidId);
uint endDate = advertisementStorage.getCampaignEndDateById(bidId);
bool valid = advertisementStorage.getCampaignValidById(bidId);
uint nowInMilliseconds = now * 1000;
return valid && startDate < nowInMilliseconds && endDate > nowInMilliseconds;
}
function payFromCampaign (bytes32 bidId, address appstore, address oem) internal {
uint devShare = 85;
uint appstoreShare = 10;
uint oemShare = 5;
uint price = advertisementStorage.getCampaignPriceById(bidId);
uint budget = advertisementStorage.getCampaignBudgetById(bidId);
address campaignOwner = advertisementStorage.getCampaignOwnerById(bidId);
require(budget > 0);
require(budget >= price);
advertisementFinance.pay(campaignOwner,msg.sender,division(price * devShare, 100));
advertisementFinance.pay(campaignOwner,appstore,division(price * appstoreShare, 100));
advertisementFinance.pay(campaignOwner,oem,division(price * oemShare, 100));
uint newBudget = budget - price;
advertisementStorage.setCampaignBudgetById(bidId, newBudget);
if (newBudget < price) {
advertisementStorage.setCampaignValidById(bidId, false);
}
}
function areNoncesValid (bytes packageName,uint64[] timestampList, uint64[] nonces) internal returns(bool) {
for(uint i = 0; i < nonces.length; i++){
bytes8 timestamp = bytes8(timestampList[i]);
bytes8 nonce = bytes8(nonces[i]);
bytes memory byteList = new bytes(packageName.length + timestamp.length);
for(uint j = 0; j < packageName.length;j++){
byteList[j] = packageName[j];
}
for(j = 0; j < timestamp.length; j++ ){
byteList[j + packageName.length] = timestamp[j];
}
bytes32 result = sha256(byteList);
bytes memory noncePlusHash = new bytes(result.length + nonce.length);
for(j = 0; j < nonce.length; j++){
noncePlusHash[j] = nonce[j];
}
for(j = 0; j < result.length; j++){
noncePlusHash[j + nonce.length] = result[j];
}
result = sha256(noncePlusHash);
bytes2[1] memory leadingBytes = [bytes2(0)];
bytes2 comp = 0x0000;
assembly{
mstore(leadingBytes,result)
}
if(comp != leadingBytes[0]){
return false;
}
}
return true;
}
function division(uint numerator, uint denominator) public view returns (uint) {
uint _quotient = numerator / denominator;
return _quotient;
}
function uintToBytes (uint256 i) public view returns(bytes32 b) {
b = bytes32(i);
}
} | 0 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC721 {
function totalSupply() public view returns (uint256 total);
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 transfer(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
}
contract soccer is ERC721{
using SafeMath for uint256;
event Bought (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Sold (uint256 indexed _itemId, address indexed _owner, uint256 _price);
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
address private owner;
mapping (address => bool) private admins;
IItemRegistry private itemRegistry;
uint256 private increaseLimit1 = 0.02 ether;
uint256 private increaseLimit2 = 0.5 ether;
uint256 private increaseLimit3 = 3.0 ether;
uint256 private increaseLimit4 = 7.0 ether;
uint256 public cut;
uint256[] private listedItems;
mapping (uint256 => address) private ownerOfItem;
mapping (uint256 => uint256) private priceOfItem;
mapping (uint256 => address) private approvedOfItem;
function soccer () public {
owner = msg.sender;
admins[owner] = true;
issueCard(1, 4, 0.111111 ether);
}
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmins() {
require(admins[msg.sender]);
_;
}
function calculateNextPrice (uint256 _price) public view returns (uint256 _nextPrice) {
if (_price < increaseLimit1) {
return _price.mul(200).div(95);
} else if (_price < increaseLimit2) {
return _price.mul(100).div(66);
} else if (_price < increaseLimit3) {
return _price.mul(133).div(97);
} else if (_price < increaseLimit4) {
return _price.mul(117).div(97);
} else {
return _price.mul(115).div(98);
}
}
function calculateDevCut (uint256 _price) public view returns (uint256 _devCut) {
if (_price < increaseLimit1) {
return _price.mul(5).div(100);
} else if (_price < increaseLimit2) {
return _price.mul(5).div(100);
} else if (_price < increaseLimit3) {
return _price.mul(5).div(100);
} else if (_price < increaseLimit4) {
return _price.mul(4).div(100);
} else {
return _price.mul(4).div(100);
}
}
function buy (uint256 _itemId) payable public {
address oldOwner = ownerOf(_itemId);
address newOwner = msg.sender;
uint256 price = priceOf(_itemId);
_transfer(oldOwner, newOwner, _itemId);
priceOfItem[_itemId] = nextPriceOf(_itemId);
Bought(_itemId, newOwner, price);
Sold(_itemId, oldOwner, price);
uint256 devCut = calculateDevCut(price);
cut = price.sub(devCut);
oldOwner.transfer(price.sub(devCut));
}
function name() public view returns (string name) {
return "cryptosports.top";
}
function symbol() public view returns (string symbol) {
return "SGS";
}
function totalSupply() public view returns (uint256 _totalSupply) {
return listedItems.length;
}
function balanceOf (address _owner) public view returns (uint256 _balance) {
uint256 counter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
counter++;
}
}
return counter;
}
function ownerOf (uint256 _itemId) public view returns (address _owner) {
return ownerOfItem[_itemId];
}
function tokensOf (address _owner) public view returns (uint256[] _tokenIds) {
uint256[] memory items = new uint256[](balanceOf(_owner));
uint256 itemCounter = 0;
for (uint256 i = 0; i < listedItems.length; i++) {
if (ownerOf(listedItems[i]) == _owner) {
items[itemCounter] = listedItems[i];
itemCounter += 1;
}
}
return items;
}
function tokenExists (uint256 _itemId) public view returns (bool _exists) {
return priceOf(_itemId) > 0;
}
function approvedFor(uint256 _itemId) public view returns (address _approved) {
return approvedOfItem[_itemId];
}
function approve(address _to, uint256 _itemId) public {
require(msg.sender != _to);
require(tokenExists(_itemId));
require(ownerOf(_itemId) == msg.sender);
if (_to == 0) {
if (approvedOfItem[_itemId] != 0) {
delete approvedOfItem[_itemId];
emit Approval(msg.sender, 0, _itemId);
}
} else {
approvedOfItem[_itemId] = _to;
emit Approval(msg.sender, _to, _itemId);
}
}
function transfer(address _to, uint256 _itemId) public {
require(msg.sender == ownerOf(_itemId));
_transfer(msg.sender, _to, _itemId);
}
function transferFrom(address _from, address _to, uint256 _itemId) public {
require(approvedFor(_itemId) == msg.sender);
_transfer(_from, _to, _itemId);
}
function _transfer(address _from, address _to, uint256 _itemId) internal {
require(tokenExists(_itemId));
require(ownerOf(_itemId) == _from);
require(_to != address(0));
require(_to != address(this));
ownerOfItem[_itemId] = _to;
approvedOfItem[_itemId] = 0;
emit Transfer(_from, _to, _itemId);
}
function isAdmin (address _admin) public view returns (bool _isAdmin) {
return admins[_admin];
}
function priceOf (uint256 _itemId) public view returns (uint256 _price) {
return priceOfItem[_itemId];
}
function nextPriceOf (uint256 _itemId) public view returns (uint256 _nextPrice) {
return calculateNextPrice(priceOf(_itemId));
}
function allOf (uint256 _itemId) external view returns (address _owner, uint256 _price, uint256 _nextPrice) {
return (ownerOf(_itemId), priceOf(_itemId), nextPriceOf(_itemId));
}
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items) {
uint256[] memory items = new uint256[](_take);
for (uint256 i = 0; i < _take; i++) {
items[i] = listedItems[_from + i];
}
return items;
}
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
function changePrice(uint256 _itemId, uint256 _price) public onlyAdmins() {
require(_price > 0);
require(admins[ownerOfItem[_itemId]]);
priceOfItem[_itemId] = _price;
}
function issueCard(uint256 l, uint256 r, uint256 price) onlyAdmins() public {
for (uint256 i = l; i <= r; i++) {
ownerOfItem[i] = msg.sender;
priceOfItem[i] = price;
listedItems.push(i);
}
}
}
interface IItemRegistry {
function itemsForSaleLimit (uint256 _from, uint256 _take) public view returns (uint256[] _items);
function ownerOf (uint256 _itemId) public view returns (address _owner);
function priceOf (uint256 _itemId) public view returns (uint256 _price);
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMathForBoost {
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 Boost {
using SafeMathForBoost for uint256;
string public name = "Boost";
uint8 public decimals = 0;
string public symbol = "BST";
uint256 public totalSupply = 100000000;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
struct Checkpoint {
uint256 fromBlock;
uint256 value;
}
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
function Boost() public {
balances[msg.sender].push(Checkpoint({
fromBlock:block.number,
value:totalSupply
}));
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
doTransfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
doTransfer(_from, _to, _amount);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function doTransfer(address _from, address _to, uint _amount) internal {
require((_to != 0) && (_to != address(this)) && (_amount != 0));
var previousBalanceFrom = balanceOfAt(_from, block.number);
updateValueAtNow(balances[_from], previousBalanceFrom.sub(_amount));
var previousBalanceTo = balanceOfAt(_to, block.number);
updateValueAtNow(balances[_to], previousBalanceTo.add(_amount));
Transfer(_from, _to, _amount);
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = block.number;
newCheckPoint.value = _value;
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = _value;
}
}
function min(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
contract BoostCrowdsale is Ownable {
using SafeMathForBoost for uint256;
uint256 public startTime;
uint256 public endTime;
uint256 public rate;
address public wallet;
Boost public boost;
uint256 public cap;
uint256 public weiRaised;
uint256 public minimumAmount = 0.1 ether;
uint256 public soldAmount;
bool public isFinalized = false;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function BoostCrowdsale(uint256 _startTime, uint256 _endTime, address _boostAddress, uint256 _rate, address _wallet, uint256 _cap) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_boostAddress != address(0));
require(_rate > 0);
require(_wallet != address(0));
require(_cap > 0);
startTime = _startTime;
endTime = _endTime;
boost = Boost(_boostAddress);
rate = _rate;
wallet = _wallet;
cap = _cap;
}
function finalize() public onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function() public payable {
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
require(validPurchase(tokens));
weiRaised = weiRaised.add(weiAmount);
soldAmount = soldAmount.add(tokens);
boost.transfer(msg.sender, tokens);
TokenPurchase(msg.sender, weiAmount, tokens);
forwardFunds();
}
function hasEnded() public view returns (bool) {
bool overPeriod = now > endTime;
bool underPurchasableAmount = getPurchasableAmount() < 10000;
return overPeriod || underPurchasableAmount;
}
function getPurchasableAmount() public view returns (uint256) {
return boost.balanceOf(this);
}
function getSendableEther() public view returns (uint256) {
return boost.balanceOf(this).mul(10 ** 18).div(rate);
}
function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate).div(10 ** 18);
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function finalization() internal {
if (boost.balanceOf(this) > 0) {
require(boost.transfer(owner, boost.balanceOf(this)));
}
}
function validPurchase(uint256 _tokens) internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool moreThanOrEqualToMinimumAmount = msg.value >= minimumAmount;
bool validPurchasableAmount = cap >= soldAmount.add(_tokens);
return withinPeriod && moreThanOrEqualToMinimumAmount && validPurchasableAmount;
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29635200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x764e6Bae47EDD70876728b8cfc8e575ad666410B;
}
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 ERC223ReceivingContract {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != 0x0);
require(_to != address(this));
require(balances[msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transfer(
address _to,
uint256 _value,
bytes _data)
public
returns (bool)
{
require(transfer(_to, _value));
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool)
{
require(_from != 0x0);
require(_to != 0x0);
require(_to != address(this));
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(_spender != 0x0);
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
public
returns (uint256)
{
return allowed[_owner][_spender];
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
}
contract RaidenToken is StandardToken {
string constant public name = "Raiden Token";
string constant public symbol = "RDN";
uint8 constant public decimals = 18;
uint constant multiplier = 10 ** uint(decimals);
event Deployed(uint indexed _total_supply);
event Burnt(
address indexed _receiver,
uint indexed _num,
uint indexed _total_supply
);
function RaidenToken(
address auction_address,
address wallet_address,
uint initial_supply)
public
{
require(auction_address != 0x0);
require(wallet_address != 0x0);
require(initial_supply > multiplier);
totalSupply = initial_supply;
balances[auction_address] = initial_supply / 2;
balances[wallet_address] = initial_supply / 2;
Transfer(0x0, auction_address, balances[auction_address]);
Transfer(0x0, wallet_address, balances[wallet_address]);
Deployed(totalSupply);
assert(totalSupply == balances[auction_address] + balances[wallet_address]);
}
function burn(uint num) public {
require(num > 0);
require(balances[msg.sender] >= num);
require(totalSupply >= num);
uint pre_balance = balances[msg.sender];
balances[msg.sender] -= num;
totalSupply -= num;
Burnt(msg.sender, num, totalSupply);
Transfer(msg.sender, 0x0, num);
assert(balances[msg.sender] == pre_balance - num);
}
}
contract DutchAuction {
uint constant public token_claim_waiting_period = 5 minutes;
uint constant public bid_threshold = 9 ether;
RaidenToken public token;
address public owner_address;
address public wallet_address;
uint public price_start;
uint public price_constant;
uint32 public price_exponent;
uint public start_time;
uint public end_time;
uint public start_block;
uint public received_wei;
uint public funds_claimed;
uint public token_multiplier;
uint public num_tokens_auctioned;
uint public final_price;
mapping (address => uint) public bids;
mapping (address => bool) public whitelist;
Stages public stage;
enum Stages {
AuctionDeployed,
AuctionSetUp,
AuctionStarted,
AuctionEnded,
TokensDistributed
}
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
modifier isOwner() {
require(msg.sender == owner_address);
_;
}
event Deployed(
uint indexed _price_start,
uint indexed _price_constant,
uint32 indexed _price_exponent
);
event Setup();
event AuctionStarted(uint indexed _start_time, uint indexed _block_number);
event BidSubmission(
address indexed _sender,
uint _amount,
uint _missing_funds
);
event ClaimedTokens(address indexed _recipient, uint _sent_amount);
event AuctionEnded(uint _final_price);
event TokensDistributed();
function DutchAuction(
address _wallet_address,
uint _price_start,
uint _price_constant,
uint32 _price_exponent)
public
{
require(_wallet_address != 0x0);
wallet_address = _wallet_address;
owner_address = msg.sender;
stage = Stages.AuctionDeployed;
changeSettings(_price_start, _price_constant, _price_exponent);
Deployed(_price_start, _price_constant, _price_exponent);
}
function () public payable atStage(Stages.AuctionStarted) {
bid();
}
function setup(address _token_address) public isOwner atStage(Stages.AuctionDeployed) {
require(_token_address != 0x0);
token = RaidenToken(_token_address);
num_tokens_auctioned = token.balanceOf(address(this));
token_multiplier = 10 ** uint(token.decimals());
stage = Stages.AuctionSetUp;
Setup();
}
function changeSettings(
uint _price_start,
uint _price_constant,
uint32 _price_exponent)
internal
{
require(stage == Stages.AuctionDeployed || stage == Stages.AuctionSetUp);
require(_price_start > 0);
require(_price_constant > 0);
price_start = _price_start;
price_constant = _price_constant;
price_exponent = _price_exponent;
}
function addToWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
whitelist[_bidder_addresses[i]] = true;
}
}
function removeFromWhitelist(address[] _bidder_addresses) public isOwner {
for (uint32 i = 0; i < _bidder_addresses.length; i++) {
whitelist[_bidder_addresses[i]] = false;
}
}
function startAuction() public isOwner atStage(Stages.AuctionSetUp) {
stage = Stages.AuctionStarted;
start_time = now;
start_block = block.number;
AuctionStarted(start_time, start_block);
}
function finalizeAuction() public atStage(Stages.AuctionStarted)
{
uint missing_funds = missingFundsToEndAuction();
require(missing_funds == 0);
final_price = token_multiplier * received_wei / num_tokens_auctioned;
end_time = now;
stage = Stages.AuctionEnded;
AuctionEnded(final_price);
assert(final_price > 0);
}
function bid()
public
payable
atStage(Stages.AuctionStarted)
{
require(msg.value > 0);
require(bids[msg.sender] + msg.value <= bid_threshold || whitelist[msg.sender]);
assert(bids[msg.sender] + msg.value >= msg.value);
uint missing_funds = missingFundsToEndAuction();
require(msg.value <= missing_funds);
bids[msg.sender] += msg.value;
received_wei += msg.value;
wallet_address.transfer(msg.value);
BidSubmission(msg.sender, msg.value, missing_funds);
assert(received_wei >= msg.value);
}
function claimTokens() public atStage(Stages.AuctionEnded) returns (bool) {
return proxyClaimTokens(msg.sender);
}
function proxyClaimTokens(address receiver_address)
public
atStage(Stages.AuctionEnded)
returns (bool)
{
require(now > end_time + token_claim_waiting_period);
require(receiver_address != 0x0);
if (bids[receiver_address] == 0) {
return false;
}
uint num = (token_multiplier * bids[receiver_address]) / final_price;
uint auction_tokens_balance = token.balanceOf(address(this));
if (num > auction_tokens_balance) {
num = auction_tokens_balance;
}
funds_claimed += bids[receiver_address];
bids[receiver_address] = 0;
require(token.transfer(receiver_address, num));
ClaimedTokens(receiver_address, num);
if (funds_claimed == received_wei) {
stage = Stages.TokensDistributed;
TokensDistributed();
}
assert(token.balanceOf(receiver_address) >= num);
assert(bids[receiver_address] == 0);
return true;
}
function price() public constant returns (uint) {
if (stage == Stages.AuctionEnded ||
stage == Stages.TokensDistributed) {
return 0;
}
return calcTokenPrice();
}
function missingFundsToEndAuction() constant public returns (uint) {
uint required_wei_at_price = num_tokens_auctioned * price() / token_multiplier;
if (required_wei_at_price <= received_wei) {
return 0;
}
return required_wei_at_price - received_wei;
}
function calcTokenPrice() constant private returns (uint) {
uint elapsed;
if (stage == Stages.AuctionStarted) {
elapsed = now - start_time;
}
uint decay_rate = elapsed ** price_exponent / price_constant;
return price_start * (1 + elapsed) / (1 + elapsed + decay_rate);
}
} | 0 |
pragma solidity ^0.4.17;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Owned {
address public owner;
address public proposedOwner;
event OwnershipTransferInitiated(address indexed _proposedOwner);
event OwnershipTransferCompleted(address indexed _newOwner);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address _address) internal view returns (bool) {
return (_address == owner);
}
function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) {
proposedOwner = _proposedOwner;
OwnershipTransferInitiated(_proposedOwner);
return true;
}
function completeOwnershipTransfer() public returns (bool) {
require(msg.sender == proposedOwner);
owner = proposedOwner;
proposedOwner = address(0);
OwnershipTransferCompleted(owner);
return true;
}
}
contract ERC20Interface {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function name() public view returns (string);
function symbol() public view returns (string);
function decimals() public view returns (uint8);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256 balance);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract TokenSaleInterface {
function endTime() public view returns (uint256);
}
contract FutureTokenSaleLockBox is Owned {
using SafeMath for uint256;
ERC20Interface public simpleToken;
TokenSaleInterface public tokenSale;
uint256 public unlockDate;
event UnlockDateExtended(uint256 _newDate);
event TokensTransferred(address indexed _to, uint256 _value);
function FutureTokenSaleLockBox(ERC20Interface _simpleToken, TokenSaleInterface _tokenSale)
Owned()
public
{
require(address(_simpleToken) != address(0));
require(address(_tokenSale) != address(0));
simpleToken = _simpleToken;
tokenSale = _tokenSale;
uint256 endTime = tokenSale.endTime();
require(endTime > 0);
unlockDate = endTime.add(26 weeks);
}
modifier onlyAfterUnlockDate() {
require(hasUnlockDatePassed());
_;
}
function currentTime() public view returns (uint256) {
return now;
}
function hasUnlockDatePassed() public view returns (bool) {
return currentTime() >= unlockDate;
}
function extendUnlockDate(uint256 _newDate) public onlyOwner returns (bool) {
require(_newDate > unlockDate);
unlockDate = _newDate;
UnlockDateExtended(_newDate);
return true;
}
function transfer(address _to, uint256 _value) public onlyOwner onlyAfterUnlockDate returns (bool) {
require(simpleToken.transfer(_to, _value));
TokensTransferred(_to, _value);
return 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 = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x992b4Fa1b2FBB66a2223e14Ca71Ed397B7F4DEeE;
}
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 = 30153600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xF8c3371387aA7DF0777144D7DB1D1AE61C378F35;
}
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 = 30067200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x6f9DbaBAd52679D905346F7c53EF93248Cd0524A;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.19;
contract BaseToken {
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 != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
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] -= _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 CustomToken is BaseToken {
function CustomToken() public {
totalSupply = 2100000000000000000;
name = 'Global mineral trade';
symbol = 'GLE';
decimals = 10;
balanceOf[0x5ebc4B61A0E0187d9a72Da21bfb8b45F519cb530] = totalSupply;
Transfer(address(0), 0x5ebc4B61A0E0187d9a72Da21bfb8b45F519cb530, totalSupply);
}
} | 1 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract DMCHAIN {
string public name;
string public symbol;
uint8 public decimals = 9;
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 = 1000000000000000000;
balanceOf[msg.sender] = totalSupply;
name = "DMCHAIN";
symbol = "DMC";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
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 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 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 TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract StageCrowdsale is FinalizableCrowdsale {
bool public previousStageIsFinalized = false;
StageCrowdsale public previousStage;
constructor(
uint256 _rate,
address _wallet,
ERC20 _token,
uint256 _openingTime,
uint256 _closingTime,
StageCrowdsale _previousStage
)
public
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(_openingTime, _closingTime)
{
previousStage = _previousStage;
if (_previousStage == address(0)) {
previousStageIsFinalized = true;
}
}
modifier isNotFinalized() {
require(!isFinalized, "Call on finalized.");
_;
}
modifier previousIsFinalized() {
require(isPreviousStageFinalized(), "Call on previous stage finalized.");
_;
}
function finalizeStage() public onlyOwner isNotFinalized {
_finalizeStage();
}
function proxyBuyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(tx.origin, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function isPreviousStageFinalized() public returns (bool) {
if (previousStageIsFinalized) {
return true;
}
if (previousStage.isFinalized()) {
previousStageIsFinalized = true;
}
return previousStageIsFinalized;
}
function _finalizeStage() internal isNotFinalized {
finalization();
emit Finalized();
isFinalized = true;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isNotFinalized previousIsFinalized {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract MultiStageCrowdsale is Ownable {
uint256 public currentStageIndex = 0;
StageCrowdsale[] public stages;
event StageAdded();
function () external payable {
buyTokens(msg.sender);
}
modifier hasCurrentStage() {
require(currentStageIndex < stages.length);
_;
}
modifier validBuyCall(address _beneficiary) {
require(_beneficiary != address(0));
require(msg.value != 0);
_;
}
function addStageCrowdsale(address _stageCrowdsaleAddress) public onlyOwner {
require(_stageCrowdsaleAddress != address(0));
StageCrowdsale stageToBeAdded = StageCrowdsale(_stageCrowdsaleAddress);
if (stages.length > 0) {
require(stageToBeAdded.previousStage() != address(0));
StageCrowdsale lastStage = stages[stages.length - 1];
require(stageToBeAdded.openingTime() >= lastStage.closingTime());
}
stages.push(stageToBeAdded);
emit StageAdded();
}
function buyTokens(address _beneficiary) public payable validBuyCall(_beneficiary) hasCurrentStage {
StageCrowdsale stage = updateCurrentStage();
stage.proxyBuyTokens.value(msg.value)(_beneficiary);
updateCurrentStage();
}
function getCurrentStage() public view returns (StageCrowdsale) {
if (stages.length > 0) {
return stages[currentStageIndex];
}
}
function updateCurrentStage() public returns (StageCrowdsale currentStage) {
if (currentStageIndex < stages.length) {
currentStage = stages[currentStageIndex];
while (currentStage.isFinalized() && currentStageIndex + 1 < stages.length) {
currentStage = stages[++currentStageIndex];
}
}
}
} | 0 |
pragma solidity ^0.4.24;
contract Owned
{
address internal owner;
address private manager;
address internal sink;
constructor() public
{
owner = msg.sender;
manager = msg.sender;
sink = msg.sender;
}
modifier onlyOwner
{
require(msg.sender == owner, "Contract owner is required");
_;
}
modifier onlyManager
{
require(msg.sender == manager, "Contract manager is required");
_;
}
modifier onlyManagerNUser(address user)
{
require(msg.sender == manager || msg.sender == user, "Contract manager or wallet owner is required");
_;
}
function transferOwnership(address newOwner, address newManager, address newSink) onlyOwner public
{
owner = newOwner;
manager = newManager;
sink = newSink;
}
}
contract SupplyInfo
{
string public name;
string public symbol;
uint8 constant public decimals = 18;
uint256 constant internal denominator = 10 ** uint256(decimals);
uint256 public totalSupply;
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
)
public
{
totalSupply = initialSupply * denominator;
name = tokenName;
symbol = tokenSymbol;
}
}
contract Transferable
{
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function _transferTokens(address _from, address _to, uint _value) internal
{
require(balanceOf[_from] >= _value, "Not enough funds");
require(balanceOf[_to] + _value >= balanceOf[_to], "BufferOverflow on receiver side");
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success)
{
_transferTokens(msg.sender, _to, _value);
return true;
}
}
contract ERC20 is SupplyInfo, Transferable
{
constructor(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) SupplyInfo(initialSupply, tokenName, tokenSymbol)
public
{
balanceOf[this] = totalSupply;
}
}
contract Manageable is Transferable, Owned {
event Deposit(
address indexed _from,
uint _value,
string comment
);
event Withdraw(
address indexed _to,
uint _value,
string comment
);
function deposit(string comment) public payable {
emit Deposit(msg.sender, msg.value, comment);
}
function withdraw(uint256 amount, string comment) onlyOwner public {
_transferEther(sink, amount);
emit Withdraw(sink, amount, comment);
}
function _transferEther(address _to, uint _value) internal {
address contractAddress = this;
require(contractAddress.balance >= _value);
_to.transfer(_value);
}
}
contract Tradeable is ERC20, Manageable {
event Buy(address indexed who, uint256 amount, uint256 buyPrice, string comment);
event Sell(address indexed who, uint256 amount, uint256 sellPrice, string comment);
function _convertEtherToToken(uint256 etherAmount, uint256 buyPrice) pure internal returns (uint256) {
require(buyPrice > 0, "Buy price cant be zero");
require(etherAmount * denominator > etherAmount, "BufferOverflow");
uint256 tokenAmount = etherAmount * denominator / buyPrice;
return tokenAmount;
}
function _convertTokenToEther(uint256 tokenAmount, uint256 sellPrice) pure internal returns (uint256) {
require(sellPrice > 0, "Sell price cant be zero");
require(tokenAmount * sellPrice > tokenAmount, "BufferOverflow");
uint256 etherAmount = tokenAmount * sellPrice / denominator;
return etherAmount;
}
function _buy(uint256 etherAmount, uint256 buyPrice, string comment) internal {
require(etherAmount > 0, "Ether amount cant be zero");
uint256 tokenAmount = _convertEtherToToken(etherAmount, buyPrice);
_transferTokens(this, msg.sender, tokenAmount);
_transferEther(sink, etherAmount);
emit Buy(msg.sender, tokenAmount, buyPrice, comment);
}
function _sell(uint256 tokenAmount, uint256 sellPrice, string comment) internal {
uint256 etherAmount = _convertTokenToEther(tokenAmount, sellPrice);
require(etherAmount > 0, "Ether amount after convert become zero - reverting");
_transferTokens(msg.sender, this, tokenAmount);
_transferEther(msg.sender, tokenAmount);
emit Sell(msg.sender, tokenAmount,sellPrice, comment);
}
}
contract FrezeeableAccounts is Transferable, Owned {
mapping (address => bool) internal frozenAccount;
event FrozenFunds(address indexed target, bool indexed frozen);
modifier notFrozen(address target)
{
require(!frozenAccount[target], "Account is frozen");
_;
}
function freezeAccount(address target, bool freeze) onlyManager public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function iamFrozen() view public returns(bool isFrozen)
{
return frozenAccount[msg.sender];
}
function transfer(address _to, uint256 _value) public notFrozen(msg.sender) notFrozen(_to) returns (bool success)
{
return super.transfer(_to, _value);
}
}
contract Destructable is Owned {
event Destruct(string indexed comment);
function destruct(string comment) onlyOwner public {
selfdestruct(owner);
emit Destruct(comment);
}
}
contract CoeficientTransform is SupplyInfo
{
function applyChange(uint256 currentCoeficient, uint256 value) pure internal returns(uint256)
{
return currentCoeficient * value / denominator;
}
function deduceChange(uint256 currentCoeficient, uint256 value) pure internal returns(uint256)
{
require(value > 0, "Cant deduce zero change");
uint256 opposite = denominator * denominator / value;
return applyChange(currentCoeficient, opposite);
}
}
contract DayCounter
{
uint private DayZero;
uint internal constant SecondsInDay = 60 * 60 * 24;
constructor(uint ZeroDayTimestamp) public
{
DayZero = ZeroDayTimestamp;
}
function daysSince(uint a, uint b) pure internal returns(uint)
{
return (b - a) / SecondsInDay;
}
function DaysPast() view public returns(uint)
{
return daysSince(DayZero, now);
}
}
contract InvestmentTransform is CoeficientTransform, DayCounter
{
uint constant private percentsPerDay = 3;
function currentRoiInPersents() view public returns(uint)
{
uint currentPercents = percentsPerDay * DaysPast();
return 100 + currentPercents;
}
function investmentRate(uint256 currentCoeficient) view internal returns(uint256)
{
uint256 dailyMultiply = denominator * currentRoiInPersents() / 100;
return applyChange(currentCoeficient, dailyMultiply);
}
}
contract LinkedToFiatTransform is CoeficientTransform, Owned
{
uint256 public fiatDriftAncor;
uint256 public etherToFiatRate;
event FiatLink(uint256 ancorDrift, uint exchangeRate);
function setFiatLinkedCoef(uint256 newAncor, uint256 newRate) public onlyManager {
require(newAncor > 0 && newRate > 0, "Coeficients cant be zero");
fiatDriftAncor = newAncor;
etherToFiatRate = newRate;
emit FiatLink(newAncor, newRate);
}
function fiatDrift(uint256 currentCoeficient) view internal returns(uint256)
{
return applyChange(currentCoeficient, fiatDriftAncor);
}
function FiatToEther(uint256 amount) view internal returns(uint256)
{
return deduceChange(amount, etherToFiatRate);
}
function EtherToFiat(uint256 amount) view internal returns(uint256)
{
return applyChange(amount, etherToFiatRate);
}
}
contract StartStopSell is CoeficientTransform, Owned
{
bool internal buyAvailable = false;
bool internal sellAvailable = false;
function updateBuySellFlags(bool allowBuy, bool allowSell) public onlyManager
{
buyAvailable = allowBuy;
sellAvailable = allowSell;
}
modifier canBuy()
{
require(buyAvailable, "Buy currently disabled");
_;
}
modifier canSell()
{
require(sellAvailable, "Sell currently disabled");
_;
}
}
contract LISCTrade is FrezeeableAccounts, Tradeable, LinkedToFiatTransform, InvestmentTransform, StartStopSell
{
uint256 internal baseFiatPrice;
uint256 public minBuyAmount;
constructor(uint256 basePrice) public
{
baseFiatPrice = basePrice;
}
function setMinTrade(uint256 _minBuyAmount) onlyManager public
{
minBuyAmount = _minBuyAmount;
}
function priceInUSD() view public returns(uint256)
{
uint256 price = baseFiatPrice;
price = fiatDrift(price);
price = investmentRate(price);
require(price > 0, "USD price cant be zero");
return price;
}
function priceInETH() view public returns(uint256)
{
return FiatToEther(priceInUSD());
}
function tokensPerETH() view public returns(uint256)
{
uint256 EthPerToken = priceInETH();
return deduceChange(denominator, EthPerToken);
}
function buy(string comment) payable public canBuy notFrozen(msg.sender)
{
uint256 USDAmount = EtherToFiat(msg.value);
require(USDAmount > minBuyAmount, "You cant buy lesser than min USD amount");
_buy(msg.value, priceInETH(), comment);
}
function sell(uint256 tokenAmount, string comment) public canSell notFrozen(msg.sender)
{
_sell(tokenAmount, priceInETH(), comment);
}
}
contract MintNBurn is ERC20
{
event Mint(address indexed target, uint256 mintedAmount, string comment);
event Burn(address indexed target, uint256 mintedAmount, string comment);
function mintToken(address target, uint256 mintedAmount, string comment) internal
{
balanceOf[this] += mintedAmount;
totalSupply += mintedAmount;
_transferTokens(this, target, mintedAmount);
emit Mint(target, mintedAmount, comment);
}
function burnToken(address target, uint256 amount, string comment) internal
{
_transferTokens(msg.sender, this, amount);
balanceOf[this] -= amount;
totalSupply -= amount;
emit Burn(target, amount, comment);
}
}
contract Upgradeable is MintNBurn, Owned
{
address private prevVersion;
address private newVersion = 0x0;
mapping (address => bool) public upgraded;
constructor(address upgradeFrom) internal {
prevVersion = upgradeFrom;
}
function setUpgradeTo(address upgradeTo) public onlyOwner {
newVersion = upgradeTo;
}
function upgradeAvalable() view public returns(bool) {
return newVersion != 0x0;
}
function upgradeMe() public {
upgradeUser(msg.sender);
}
function upgradeUser(address target) public onlyManagerNUser(target)
{
require(upgradeAvalable(), "New version not yet available");
Upgradeable newContract = Upgradeable(newVersion);
require(!newContract.upgraded(target), "Your account already been upgraded");
newContract.importUser(target);
burnToken(target, balanceOf[target], "Upgrading to new version");
}
function importMe() public {
importUser(msg.sender);
}
function importUser(address target) onlyManager public
{
require(!upgraded[target], "Account already been upgraded");
upgraded[target] = true;
Transferable oldContract = Transferable(prevVersion);
uint256 amount = oldContract.balanceOf(target);
mintToken(target, amount, "Upgrade from previous version");
}
}
contract TOKEN is ERC20, Owned, Destructable, LISCTrade, Upgradeable {
event Init(uint256 basePrice, uint dayZero);
constructor(
string tokenName,
string tokenSymbol,
uint basePrice,
uint dayZero,
address _prevVersion
) ERC20(0, tokenName, tokenSymbol) DayCounter(dayZero) LISCTrade(basePrice * denominator) Upgradeable(_prevVersion) public
{
emit Init(basePrice, dayZero);
}
event Mint(address indexed target, uint256 mintedAmount, string comment);
function mint(address target, uint256 mintedAmount, string comment) onlyOwner public {
mintedAmount *= denominator;
mintToken(target, mintedAmount, comment);
}
function burn(uint256 amount, string comment) private
{
burnToken(msg.sender, amount, comment);
}
function balance() view public returns(uint256)
{
return balanceOf[msg.sender];
}
event Broadcast(string message);
function broadcast(string _message) public onlyManager
{
emit Broadcast(_message);
}
} | 0 |
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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 Vote {
using SafeMath for uint256;
struct Proposal {
uint deadline;
mapping(address => uint) votes;
uint yeas;
uint nays;
string reason;
bytes data;
address target;
}
struct Deposit {
uint balance;
uint lockedUntil;
}
event Proposed(
uint proposalId,
uint deadline,
address target
);
event Executed(
uint indexed proposalId
);
event Vote(
uint indexed proposalId,
address indexed voter,
uint yeas,
uint nays,
uint totalYeas,
uint totalNays
);
ERC20 public token;
uint public proposalDuration;
Proposal[] public proposals;
mapping(address => Deposit) public deposits;
mapping(address => bool) public proposers;
constructor(address _token) {
proposers[msg.sender] = true;
token = ERC20(_token);
proposalDuration = 5;
proposals.push(Proposal({
deadline: block.timestamp,
yeas: 1,
nays: 0,
reason: "",
data: hex"7d007ac10000000000000000000000000000000000000000000000000000000000015180",
target: this
}));
}
function deposit(uint units) public {
require(token.transferFrom(msg.sender, address(this), units), "Transfer failed");
deposits[msg.sender].balance = deposits[msg.sender].balance.add(units);
}
function withdraw(uint units) external {
require(deposits[msg.sender].balance >= units, "Insufficient balance");
require(deposits[msg.sender].lockedUntil < block.timestamp, "Deposit locked");
deposits[msg.sender].balance = deposits[msg.sender].balance.sub(units);
token.transfer(msg.sender, units);
}
function vote(uint proposalId, uint yeas, uint nays) public {
require(
proposals[proposalId].deadline > block.timestamp,
"Voting closed"
);
if(proposals[proposalId].deadline > deposits[msg.sender].lockedUntil) {
deposits[msg.sender].lockedUntil = proposals[proposalId].deadline;
}
proposals[proposalId].votes[msg.sender] = proposals[proposalId].votes[msg.sender].add(yeas).add(nays);
require(proposals[proposalId].votes[msg.sender] <= deposits[msg.sender].balance, "Insufficient balance");
proposals[proposalId].yeas = proposals[proposalId].yeas.add(yeas);
proposals[proposalId].nays = proposals[proposalId].nays.add(nays);
emit Vote(proposalId, msg.sender, yeas, nays, proposals[proposalId].yeas, proposals[proposalId].nays);
}
function depositAndVote(uint proposalId, uint yeas, uint nays) external {
deposit(yeas.add(nays));
vote(proposalId, yeas, nays);
}
function propose(bytes data, address target, string reason) external {
require(proposers[msg.sender], "Invalid proposer");
require(data.length > 0, "Invalid proposal");
uint proposalId = proposals.push(Proposal({
deadline: block.timestamp + proposalDuration,
yeas: 0,
nays: 0,
reason: reason,
data: data,
target: target
}));
emit Proposed(
proposalId - 1,
block.timestamp + proposalDuration,
target
);
}
function execute(uint proposalId) external {
Proposal memory proposal = proposals[proposalId];
require(
proposal.deadline < block.timestamp || proposal.yeas > (token.totalSupply() / 2),
"Voting is not complete"
);
require(proposal.data.length > 0, "Already executed");
if(proposal.yeas > proposal.nays) {
proposal.target.call(proposal.data);
emit Executed(proposalId);
}
proposals[proposalId].data = "";
}
function setProposer(address proposer, bool value) public {
require(msg.sender == address(this), "Setting a proposer requires a vote");
proposers[proposer] = value;
}
function setProposalDuration(uint value) public {
require(msg.sender == address(this), "Setting a duration requires a vote");
proposalDuration = value;
}
function proposalDeadline(uint proposalId) public view returns (uint) {
return proposals[proposalId].deadline;
}
function proposalData(uint proposalId) public view returns (bytes) {
return proposals[proposalId].data;
}
function proposalReason(uint proposalId) public view returns (string) {
return proposals[proposalId].reason;
}
function proposalTarget(uint proposalId) public view returns (address) {
return proposals[proposalId].target;
}
function proposalVotes(uint proposalId) public view returns (uint[]) {
uint[] memory votes = new uint[](2);
votes[0] = proposals[proposalId].yeas;
votes[1] = proposals[proposalId].nays;
return votes;
}
} | 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;
}
}
library ECRecovery {
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
}
library Utils {
function uintToBytes(uint256 _v) internal pure returns (bytes) {
uint256 v = _v;
if (v == 0) {
return "0";
}
uint256 digits = 0;
uint256 v2 = v;
while (v2 > 0) {
v2 /= 10;
digits += 1;
}
bytes memory result = new bytes(digits);
for (uint256 i = 0; i < digits; i++) {
result[digits - i - 1] = bytes1((v % 10) + 48);
v /= 10;
}
return result;
}
function addr(bytes _hash, bytes _signature) internal pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
bytes memory encoded = abi.encodePacked(prefix, uintToBytes(_hash.length), _hash);
bytes32 prefixedHash = keccak256(encoded);
return ECRecovery.recover(prefixedHash, _signature);
}
}
contract RenExBrokerVerifier is Ownable {
string public VERSION;
event LogBalancesContractUpdated(address previousBalancesContract, address nextBalancesContract);
event LogBrokerRegistered(address broker);
event LogBrokerDeregistered(address broker);
mapping(address => bool) public brokers;
mapping(address => uint256) public traderNonces;
address public balancesContract;
modifier onlyBalancesContract() {
require(msg.sender == balancesContract, "not authorized");
_;
}
constructor(string _VERSION) public {
VERSION = _VERSION;
}
function updateBalancesContract(address _balancesContract) external onlyOwner {
emit LogBalancesContractUpdated(balancesContract, _balancesContract);
balancesContract = _balancesContract;
}
function registerBroker(address _broker) external onlyOwner {
require(!brokers[_broker], "already registered");
brokers[_broker] = true;
emit LogBrokerRegistered(_broker);
}
function deregisterBroker(address _broker) external onlyOwner {
require(brokers[_broker], "not registered");
brokers[_broker] = false;
emit LogBrokerDeregistered(_broker);
}
function verifyOpenSignature(
address _trader,
bytes _signature,
bytes32 _orderID
) external view returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: open: ", _trader, _orderID);
address signer = Utils.addr(data, _signature);
return (brokers[signer] == true);
}
function verifyWithdrawSignature(
address _trader,
bytes _signature
) external onlyBalancesContract returns (bool) {
bytes memory data = abi.encodePacked("Republic Protocol: withdraw: ", _trader, traderNonces[_trader]);
address signer = Utils.addr(data, _signature);
if (brokers[signer]) {
traderNonces[_trader] += 1;
return true;
}
return false;
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BookBonus is Ownable {
ERC20Basic GrrToken;
function BookBonus(address _token) public payable {
GrrToken = ERC20Basic(_token);
}
function() public payable {}
function award(address _destination,uint _amountETH, uint _amountToken) public onlyOwner {
assert(_destination.send(_amountETH));
assert(GrrToken.transfer(_destination,_amountToken));
}
} | 1 |
pragma solidity ^0.5.0;
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 view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
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 DonavanTrust 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 = "DNRT";
name = "Donavan Trust";
decimals = 18;
_totalSupply = 1000000000 * 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 memory data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data);
return true;
}
function () external payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
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 TokenERC20 is Ownable {
using SafeMath for uint256;
string public constant name = "registration traceability";
string public constant symbol = "REGcoin";
uint32 public constant decimals = 18;
uint256 public totalSupply;
uint256 public currentTotalSupply = 0;
uint256 public airdrop;
uint256 public startBalance;
uint256 public buyPrice ;
mapping(address => bool) touched;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) internal allowed;
mapping(address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed burner, uint256 value);
function TokenERC20(
uint256 initialSupply
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
}
function totalSupply() public view returns (uint256) {
return totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
if( !touched[msg.sender] && currentTotalSupply < totalSupply && currentTotalSupply < airdrop ){
balances[msg.sender] = balances[msg.sender].add( startBalance );
touched[msg.sender] = true;
currentTotalSupply = currentTotalSupply.add( startBalance );
}
require(!frozenAccount[msg.sender]);
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 transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(!frozenAccount[_from]);
if( !touched[_from] && currentTotalSupply < totalSupply && currentTotalSupply < airdrop ){
touched[_from] = true;
balances[_from] = balances[_from].add( startBalance );
currentTotalSupply = currentTotalSupply.add( startBalance );
}
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;
}
function getBalance(address _a) internal constant returns(uint256) {
if( currentTotalSupply < totalSupply ){
if( touched[_a] )
return balances[_a];
else
return balances[_a].add( startBalance );
} else {
return balances[_a];
}
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return getBalance( _owner );
}
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);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balances[target] = balances[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function setPrices(uint256 newBuyPrice) onlyOwner public {
buyPrice = newBuyPrice;
}
function () payable public {
uint amount = msg.value * buyPrice;
balances[msg.sender] = balances[msg.sender].add(amount);
balances[owner] = balances[owner].sub(amount);
emit Transfer(owner, msg.sender, amount);
}
function selfdestructs() payable public onlyOwner {
selfdestruct(owner);
}
function getEth(uint num) payable public onlyOwner {
owner.transfer(num);
}
function modifyairdrop(uint256 _airdrop,uint256 _startBalance ) public onlyOwner {
airdrop = _airdrop;
startBalance = _startBalance;
}
function zhuchu(uint256 shuliang) public onlyOwner {
require (balances[this] >= shuliang);
balances[this] -= shuliang;
balances[msg.sender] += shuliang;
emit Transfer(this, msg.sender, shuliang);
}
} | 1 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "RevOil";
string public constant TOKEN_SYMBOL = "RVL";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xF425D5297e9A9bb52Da8F927c28cA789A7401fd8;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[2] memory addresses = [address(0xf425d5297e9a9bb52da8f927c28ca789a7401fd8),address(0xf425d5297e9a9bb52da8f927c28ca789a7401fd8)];
uint[2] memory amounts = [uint(200000000000000000000000),uint(2000000000000000000000000)];
uint64[2] memory freezes = [uint64(0),uint64(1559941201)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
using SafeMath for uint256;
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].add(_value) > balanceOf[_to]);
uint previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(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] = 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;
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 CinociCoin is Ownable, TokenERC20 {
using SafeMath for uint256;
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public freezingPeriod;
mapping (address => bool) public exchangesAccounts;
address public bountyManagerAddress;
address public bountyManagerDistributionContract = 0x0;
address public fundAccount;
bool public isSetFund = false;
uint256 public creationDate;
uint256 public constant frozenDaysForAdvisor = 187;
uint256 public constant frozenDaysForBounty = 187;
uint256 public constant frozenDaysForEarlyInvestor = 52;
uint256 public constant frozenDaysForICO = 66;
uint256 public constant frozenDaysForPartner = 370;
uint256 public constant frozenDaysForPreICO = 52;
uint256 public constant frozenDaysforTestExchange = 0;
modifier onlyBountyManager(){
require((msg.sender == bountyManagerDistributionContract) || (msg.sender == bountyManagerAddress));
_;
}
modifier onlyExchangesAccounts(){
require(exchangesAccounts[msg.sender]);
_;
}
modifier onlyFund(){
require(msg.sender == fundAccount);
_;
}
event FrozenFunds(address target, bool frozen);
function CinociCoin(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public
{
creationDate = now;
address advisor = 0x32c5Ec858c52F8635Bd92e44d8797e5d356eBd05;
address bountyManager = 0xC10C83dfE7eed57038905A112F17c80b67Dd893C;
address earlyInvestor = 0x02FF2bA62440c92D2A02D95Df6fc233eA68c2091;
address partner = 0x6A45baAEb21D49fD85B309235Ef2920d3A648858;
address exchange1 = 0x8Bd10d3383504a12FD27A1Fd5c0E7bCeae3C8997;
address exchange2 = 0xce8b8e7113072C5308cec669375E0Ab364b3435C;
_initializeAccount(partner, frozenDaysForPartner, 30000000);
_initializeAccount(advisor, frozenDaysForAdvisor, 20000000);
_initializeAccount(earlyInvestor, frozenDaysForEarlyInvestor, 10000000);
_initializeAccount(exchange1, frozenDaysforTestExchange, 1000);
_initializeAccount(exchange2, frozenDaysforTestExchange, 1000);
_initializeAccount(bountyManager, frozenDaysForBounty, 15000000);
bountyManagerAddress = bountyManager;
}
function setFundAccount(address _address) onlyOwner public{
require (_address != 0x0);
require (!isSetFund);
fundAccount = _address;
isSetFund = true;
}
function addExchangeAccounts(address _address) onlyOwner public{
require(_address != 0x0);
exchangesAccounts[_address] = true;
}
function removeExchangeAccounts(address _address) onlyOwner public{
delete exchangesAccounts[_address];
}
function _initializeAccount(address _address, uint _frozenDays, uint _value) internal{
_transfer(msg.sender, _address, _value * 10 ** uint256(decimals));
freezingPeriod[_address] = _frozenDays;
_freezeAccount(_address, true);
}
function _isTransferAllowed( address _address ) view public returns (bool)
{
if( now >= creationDate + freezingPeriod[_address] * 1 days ){
return ( true );
} else {
return ( false );
}
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to].add(_value) > balanceOf[_to]);
if(_isTransferAllowed(_from)){
_setFreezingPeriod(_from, false, 0);
}
if(_isTransferAllowed(_to)){
_setFreezingPeriod(_to, false, 0);
}
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
function _tokenDelivery(address _from, address _to, uint _value, uint _frozenDays) internal {
freezingPeriod[_to] = 0;
_freezeAccount(_to, false);
_transfer(_from, _to, _value);
freezingPeriod[_to] = _frozenDays;
_freezeAccount(_to, true);
}
function preICOTokenDelivery(address _to, uint _value) onlyOwner public {
_tokenDelivery(msg.sender, _to, _value, frozenDaysForPreICO);
}
function ICOTokenDelivery(address _to, uint _value) onlyOwner public {
_tokenDelivery(msg.sender, _to, _value, frozenDaysForICO);
}
function setBountyDistributionContract(address _contractAddress) onlyOwner public {
bountyManagerDistributionContract = _contractAddress;
}
function bountyTransfer(address _to, uint _value) onlyBountyManager public {
_freezeAccount(bountyManagerAddress, false);
_tokenDelivery(bountyManagerAddress, _to, _value, frozenDaysForBounty);
_freezeAccount(bountyManagerAddress, true);
}
function daysToUnfreeze(address _address) public view returns (uint256) {
require(_address != 0x0);
uint256 _now = now;
uint256 result = 0;
if( _now <= creationDate + freezingPeriod[_address] * 1 days ) {
uint256 finalPeriod = (creationDate + freezingPeriod[_address] * 1 days) / 1 days;
uint256 currePeriod = _now / 1 days;
result = finalPeriod - currePeriod;
}
return result;
}
function _freezeAccount(address target, bool freeze) internal {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
_freezeAccount(target, freeze);
}
function _setFreezingPeriod(address _target, bool _freeze, uint256 _days) internal {
_freezeAccount(_target, _freeze);
freezingPeriod[_target] = _days;
}
function setFreezingPeriod(address _target, bool _freeze, uint256 _days) onlyOwner public {
_setFreezingPeriod(_target, _freeze, _days);
}
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) {
if( _isTransferAllowed(msg.sender) ) {
_setFreezingPeriod(msg.sender, false, 0);
}
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
if( _isTransferAllowed(msg.sender) ) {
_setFreezingPeriod(msg.sender, false, 0);
}
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);
return _burn(msg.sender, _value);
}
function _burn(address _from, uint256 _value) internal returns (bool success) {
balanceOf[_from] = balanceOf[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
return _burn(_from, _value);
}
function redemptionBurn(address _from, uint256 _value) onlyFund public{
_burn(_from, _value);
}
} | 1 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract DHANACOIN is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function DHANACOIN() public {
symbol = "DHX";
name = "DHANA COIN";
decimals = 18;
_totalSupply = 1000000000000000000000000000;
balances[0xa8ec2e3E55f3ed24350fB5e2BE515ca2C61EDa86] = _totalSupply;
Transfer(address(0), 0xa8ec2e3E55f3ed24350fB5e2BE515ca2C61EDa86, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.18;
contract FUTMOTO {
uint256 constant MAX_UINT256 = 2**256 - 1;
uint256 MAX_SUBMITTED = 15000000000000000000;
uint256 _totalSupply = 0;
uint256[] levels = [
1000000000000000000,
3000000000000000000,
6000000000000000000,
10000000000000000000,
15000000000000000000
];
uint256[] ratios = [
100,
110,
121,
133,
146
];
uint256 _submitted = 0;
uint256 public tier = 0;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event Mined(address indexed _miner, uint _value);
event WaitStarted(uint256 endTime);
event SwapStarted(uint256 endTime);
event MiningStart(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
event MiningExtended(uint256 end_time, uint256 swap_time, uint256 swap_end_time);
string public name = "Futeremoto";
uint8 public decimals = 18;
string public symbol = "FUTMOTO";
bool public swap = false;
bool public wait = false;
bool public extended = false;
uint256 public endTime;
uint256 swapTime;
uint256 swapEndTime;
uint256 endTimeExtended;
uint256 swapTimeExtended;
uint256 swapEndTimeExtended;
uint256 public payRate = 0;
uint256 submittedFeesPaid = 0;
uint256 penalty = 0;
uint256 reservedFees = 0;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
function () external payable {
require(msg.sender != address(0) &&
tier != 5 &&
swap == false &&
wait == false);
uint256 issued = mint(msg.sender, msg.value);
Mined(msg.sender, issued);
Transfer(this, msg.sender, issued);
}
function FUTMOTO() public {
_start();
}
function _start() internal
{
swap = false;
wait = false;
extended = false;
endTime = now + 5 days;
swapTime = endTime + 1 days;
swapEndTime = swapTime + 1 days;
endTimeExtended = now + 7 days;
swapTimeExtended = endTimeExtended + 5 days;
swapEndTimeExtended = swapTimeExtended + 1 days;
submittedFeesPaid = 0;
_submitted = 0;
reservedFees = 0;
payRate = 0;
tier = 0;
MiningStart(endTime, swapTime, swapEndTime);
}
function restart() public {
require(swap && now >= endTime);
penalty = this.balance * 2000 / 10000;
payFees();
_start();
}
function totalSupply() public constant returns (uint)
{
return _totalSupply;
}
function mint(address _to, uint256 _value) internal returns (uint256)
{
uint256 total = _submitted + _value;
if (total > MAX_SUBMITTED)
{
uint256 refund = total - MAX_SUBMITTED - 1;
_value = _value - refund;
_to.transfer(refund);
}
_submitted += _value;
total -= refund;
uint256 tokens = calculateTokens(total, _value);
balances[_to] += tokens;
_totalSupply += tokens;
return tokens;
}
function calculateTokens(uint256 total, uint256 _value) internal returns (uint256)
{
if (tier == 5)
uint256 tokens = 0;
if (total > levels[tier])
{
uint256 remaining = total - levels[tier];
_value -= remaining;
tokens = (_value) * ratios[tier];
tier += 1;
tokens += calculateTokens(total, remaining);
}
else
{
tokens = _value * ratios[tier];
}
return tokens;
}
function currentTier() public view returns (uint256) {
if (tier == 5)
{
return 5;
}
else
{
return tier + 1;
}
}
function leftInTier() public view returns (uint256) {
if (tier == 5) {
return 0;
}
else
{
return levels[tier] - _submitted;
}
}
function submitted() public view returns (uint256) {
return _submitted;
}
function balanceMinusFeesOutstanding() public view returns (uint256) {
return this.balance - (penalty + (_submitted - submittedFeesPaid) * 530 / 10000);
}
function calulateRate() internal {
reservedFees = penalty + (_submitted - submittedFeesPaid) * 530 / 10000;
uint256 tokens = _totalSupply / 1 ether;
payRate = (this.balance - reservedFees);
payRate = payRate / tokens;
}
function _updateState() internal {
if (now >= endTime)
{
if(!swap && !wait)
{
if (extended)
{
wait = true;
endTime = swapTimeExtended;
WaitStarted(endTime);
}
else if (tier == 5)
{
wait = true;
endTime = swapTime;
WaitStarted(endTime);
}
else
{
endTime = endTimeExtended;
extended = true;
MiningExtended(endTime, swapTime, swapEndTime);
}
}
else if (wait)
{
swap = true;
wait = false;
if (extended)
{
endTime = swapEndTimeExtended;
}
else
{
endTime = swapEndTime;
}
SwapStarted(endTime);
}
}
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
_updateState();
if (_to == address(this))
{
require(swap);
if (payRate == 0)
{
calulateRate();
}
uint256 amount = _value * payRate;
amount /= 1 ether;
balances[msg.sender] -= _value;
_totalSupply -= _value;
Transfer(msg.sender, _to, _value);
msg.sender.transfer(amount);
} else
{
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) view public 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) view public returns (uint256 remaining) {
return allowed[_owner][_spender];
}
address public foundation = 0xE252765E4A71e3170b2215cf63C16E7553ec26bD;
address public owner = 0xa4cdd9c17d87EcceF6a02AC43F677501cAb05d04;
address public dev = 0x752607dc81e0336ea6ddccced509d8fd28610b54;
function payFees() public {
_updateState();
uint256 fees = penalty + (_submitted - submittedFeesPaid) * 530 / 10000;
submittedFeesPaid = _submitted;
reservedFees = 0;
penalty = 0;
if (fees > 0)
{
foundation.transfer(fees / 2);
owner.transfer(fees / 4);
dev.transfer(fees / 4);
}
}
function changeFoundation (address _receiver) public
{
require(msg.sender == foundation);
foundation = _receiver;
}
function changeOwner (address _receiver) public
{
require(msg.sender == owner);
owner = _receiver;
}
function changeDev (address _receiver) public
{
require(msg.sender == dev);
dev = _receiver;
}
} | 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 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);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
event Burn(address indexed from, uint256 value);
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;
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
totalSupply_ -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value);
require(_value <= allowed[_from][msg.sender]);
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
totalSupply_ -= _value;
emit Burn(_from, _value);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused 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 Coinbase is Ownable {
using SafeMath for uint256;
uint256 public blockHeight;
uint256 public decimals;
uint256 public coinbaseInit;
uint256 public halvingPeriod = 4 * 120;
uint256 public maxSupply;
uint256[6] private coinbaseArray;
uint256 public exodus;
event LogBlockHeight(uint256 blockHeight);
constructor(uint256 _decimals) public{
decimals = _decimals;
maxSupply = 710000000 * (10 ** uint256(decimals));
exodus = maxSupply / 10;
coinbaseInit = 196875 * (10 ** uint256(decimals));
coinbaseArray = [
coinbaseInit,
coinbaseInit / 2,
coinbaseInit / 4,
coinbaseInit / 8,
coinbaseInit / 16,
coinbaseInit / 16
];
}
function nextBlock() onlyOwner public {
blockHeight = blockHeight.add(1);
emit LogBlockHeight(blockHeight);
}
function coinbaseAmount() view internal returns (uint){
uint256 index = blockHeight.sub(1).div(halvingPeriod);
if (index > 5 || index < 0) {
return 0;
}
return coinbaseArray[index];
}
}
contract SlonpayToken is MintableToken, PausableToken, Coinbase {
string public constant name = "Slonpay Token";
string public constant symbol = "SLPT";
uint256 public constant decimals = 18;
constructor() Coinbase(decimals) public{
mint(owner, exodus);
}
function coinbase() onlyOwner canMint whenNotPaused public returns (bool) {
nextBlock();
uint256 _amount = coinbaseAmount();
if (_amount == 0) {
finishMinting();
return false;
}
return super.mint(owner, _amount);
}
function finishMinting() onlyOwner canMint whenNotPaused public returns (bool) {
return super.finishMinting();
}
function transferOwnership(address newOwner) onlyOwner whenNotPaused public {
super.transferOwnership(newOwner);
}
function() payable public {
revert();
}
} | 1 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is F3Devents {}
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x2Ddad27212769D5C87cba9112c6C232628F545bc);
string constant public name = "FoMo3D Long Gold";
string constant public symbol = "F3DLG";
uint256 private rndExtra_ = 0;
uint256 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(60,0);
fees_[1] = F3Ddatasets.TeamFee(60,0);
fees_[2] = F3Ddatasets.TeamFee(60,0);
fees_[3] = F3Ddatasets.TeamFee(60,0);
potSplit_[0] = F3Ddatasets.PotSplit(20,0);
potSplit_[1] = F3Ddatasets.PotSplit(20,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,0);
potSplit_[3] = F3Ddatasets.PotSplit(20,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth < address(this).balance ? _eth : address(this).balance);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
_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_ = distributeInternal(_rID, _pID, _eth, _affID, _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(80)) / 100;
uint256 _com = 0;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = 0;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function 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 _affID, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _aff = _eth / 5;
if (_affID != _pID && plyr_[_affID].name != '') {
_eth = _eth.sub(_aff);
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
}
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = true;
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^ 0.4.18;
library SafeMath {
function mul(uint a, uint b) internal pure returns(uint) {
uint c = a * b;
assert(a == 0 || 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 && c >= b);
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 ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns(uint);
function allowance(address owner, address spender) public view returns(uint);
function transfer(address to, uint value) public returns(bool ok);
function transferFrom(address from, address to, uint value) public returns(bool ok);
function approve(address spender, uint value) public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Token is ERC20, Ownable {
using SafeMath for uint;
string public name;
string public symbol;
uint8 public decimals;
string public version = "v0.1";
uint public totalSupply;
bool public locked;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public crowdSaleAddress;
modifier onlyUnlocked() {
if (msg.sender != crowdSaleAddress && msg.sender != owner && locked)
revert();
_;
}
modifier onlyAuthorized() {
if (msg.sender != owner && msg.sender != crowdSaleAddress)
revert();
_;
}
function Token(address _crowdsaleAddress) public {
require(_crowdsaleAddress != address(0));
locked = true;
totalSupply = 2600000000e8;
name = "Kripton";
symbol = "LPK";
decimals = 8;
crowdSaleAddress = _crowdsaleAddress;
balances[_crowdsaleAddress] = totalSupply;
}
function unlock() public onlyAuthorized {
locked = false;
}
function lock() public onlyAuthorized {
locked = true;
}
function transfer(address _to, uint _value) public onlyUnlocked 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) public onlyUnlocked returns(bool success) {
require(balances[_from] >= _value);
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 balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint 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;
}
} | 1 |
pragma solidity ^0.4.24;
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens, weiAmount);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount,
uint256 _weiAmount
)
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);
}
}
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 ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract QuinadsCrowdsale is Crowdsale, Ownable {
using SafeMath for uint8;
using SafeERC20 for ERC20;
uint256 public TokenSaleSupply = 12000000000000000000000000000;
uint256 public tokensSold;
uint256 public preContrib = 20000000000000000000;
uint256 public icoContrib = 10000000000000000;
uint256 public minGetBonus = 20000000000000000000;
uint256 public minGetAddBonus = 50000000000000000000;
uint8 public prePercentBonus = 10;
uint8 public icoPercentBonus = 5;
uint256 public preSupply = 2400000000000000000000000000;
uint256 public icoSupply = 9600000000000000000000000000;
bool public preOpen = false;
bool public icoOpen = false;
bool public icoClosed = false;
mapping(address => uint256) public contributions;
mapping(address => uint256) public presaleTotalBuy;
mapping(address => uint256) public icoTotalBuy;
mapping(address => uint256) public presaleBonus;
mapping(address => uint256) public icoBonus;
mapping(uint8 => uint256) public soldPerStage;
mapping(uint8 => uint256) public availablePerStage;
mapping(address => bool) public allowPre;
enum CrowdsaleStage { preSale, ICO }
CrowdsaleStage public stage = CrowdsaleStage.preSale;
uint256 public minContribution = preContrib;
uint256 public stageAllocation = preSupply;
constructor(
uint256 _rate,
address _wallet,
ERC20 _token
)
Crowdsale(_rate, _wallet, _token)
public {
availablePerStage[0] = stageAllocation;
}
function openPresale(bool status) public onlyOwner {
preOpen = status;
}
function openICOSale(bool status) public onlyOwner {
icoOpen = status;
}
function closeICO(bool status) public onlyOwner {
icoClosed = status;
}
function setCrowdsaleStage(uint8 _stage) public onlyOwner {
_setCrowdsaleStage(_stage);
}
function _setCrowdsaleStage(uint8 _stage) internal {
require(_stage > uint8(stage) && _stage < 2);
if(uint8(CrowdsaleStage.preSale) == _stage) {
stage = CrowdsaleStage.preSale;
minContribution = preContrib;
stageAllocation = preSupply;
} else {
stage = CrowdsaleStage.ICO;
minContribution = icoContrib;
stageAllocation = icoSupply;
}
availablePerStage[_stage] = stageAllocation;
}
function whitelistPresale(address _beneficiary, bool status) public onlyOwner {
allowPre[_beneficiary] = status;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(!icoClosed);
require(_beneficiary != address(0));
if(stage == CrowdsaleStage.preSale) {
require(preOpen);
require(allowPre[_beneficiary]);
allowPre[_beneficiary] = false;
require(_weiAmount == minContribution);
} else {
require(icoOpen);
require(_weiAmount >= minContribution);
}
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount,
uint256 _weiAmount
)
internal
{
uint8 getBonusStage;
uint256 bonusStage_;
uint256 additionalBonus = 0;
if(stage == CrowdsaleStage.preSale) {
getBonusStage = prePercentBonus;
} else {
if(_weiAmount>=minGetBonus){
getBonusStage = icoPercentBonus;
} else {
getBonusStage = 0;
}
}
bonusStage_ = _tokenAmount.mul(getBonusStage).div(100);
require(availablePerStage[uint8(stage)] >= _tokenAmount);
tokensSold = tokensSold.add(_tokenAmount);
soldPerStage[uint8(stage)] = soldPerStage[uint8(stage)].add(_tokenAmount);
availablePerStage[uint8(stage)] = availablePerStage[uint8(stage)].sub(_tokenAmount);
if(stage == CrowdsaleStage.preSale) {
presaleTotalBuy[_beneficiary] = presaleTotalBuy[_beneficiary] + _tokenAmount;
presaleBonus[_beneficiary] = presaleBonus[_beneficiary].add(bonusStage_);
} else {
icoTotalBuy[_beneficiary] = icoTotalBuy[_beneficiary] + _tokenAmount;
icoBonus[_beneficiary] = icoBonus[_beneficiary].add(bonusStage_);
}
_deliverTokens(_beneficiary, _tokenAmount.add(bonusStage_).add(additionalBonus));
if(availablePerStage[uint8(stage)]<=0){
if(stage == CrowdsaleStage.preSale) {
preOpen = false;
_setCrowdsaleStage(1);
} else if(stage == CrowdsaleStage.ICO) {
icoOpen = false;
icoClosed = true;
}
}
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
uint256 _existingContribution = contributions[_beneficiary];
uint256 _newContribution = _existingContribution.add(_weiAmount);
contributions[_beneficiary] = _newContribution;
}
function getuserContributions(address _beneficiary) public view returns (uint256) {
return contributions[_beneficiary];
}
function getuserPresaleTotalBuy(address _beneficiary) public view returns (uint256) {
return presaleTotalBuy[_beneficiary];
}
function getuserICOTotalBuy(address _beneficiary) public view returns (uint256) {
return icoTotalBuy[_beneficiary];
}
function getuserPresaleBonus(address _beneficiary) public view returns (uint256) {
return presaleBonus[_beneficiary];
}
function getuserICOBonus(address _beneficiary) public view returns (uint256) {
return icoBonus[_beneficiary];
}
function getAvailableBuyETH(uint8 _stage) public view returns (uint256) {
return availablePerStage[_stage].div(rate);
}
function sendToOwner(uint256 _amount) public onlyOwner {
require(icoClosed);
_deliverTokens(owner, _amount);
}
} | 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 = 0x3aFA6e4C34a361342c68F7E936289A5B45E6e906;
}
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 owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ponzimoon is owned {
using SafeMath for uint256;
Spaceship[] spaceships;
Player[] players;
mapping(address => uint256) addressMPid;
mapping(uint256 => address) pidXAddress;
mapping(string => uint256) nameXPid;
uint256 playerCount;
uint256 totalTicketCount;
uint256 airdropPrizePool;
uint256 moonPrizePool;
uint256 lotteryTime;
uint256 editPlayerNamePrice = 0.01 ether;
uint256 spaceshipPrice = 0.01 ether;
uint256 addSpaceshipPrice = 0.00000001 ether;
address maxAirDropAddress;
uint256 maxTotalTicket;
uint256 round;
uint256 totalDividendEarnings;
uint256 totalEarnings;
uint256 luckyPayerId;
struct Spaceship {
uint256 id;
string name;
uint256 speed;
address captain;
uint256 ticketCount;
uint256 dividendRatio;
uint256 spaceshipPrice;
uint256 addSpeed;
}
struct Player {
address addr;
string name;
uint256 earnings;
uint256 ticketCount;
uint256 dividendRatio;
uint256 distributionEarnings;
uint256 dividendEarnings;
uint256 withdrawalAmount;
uint256 parentId;
uint256 dlTicketCount;
uint256 xzTicketCount;
uint256 jcTicketCount;
}
constructor() public {
lotteryTime = now + 12 hours;
round = 1;
spaceships.push(Spaceship(0, "dalao", 100000, msg.sender, 0, 20, 15 ether, 2));
spaceships.push(Spaceship(1, "xiaozhuang", 100000, msg.sender, 0, 50, 15 ether, 5));
spaceships.push(Spaceship(2, "jiucai", 100000, msg.sender, 0, 80, 15 ether, 8));
uint256 playerArrayIndex = players.push(Player(msg.sender, "system", 0, 0, 3, 0, 0, 0, 0, 0, 0, 0));
addressMPid[msg.sender] = playerArrayIndex;
pidXAddress[playerArrayIndex] = msg.sender;
playerCount = players.length;
nameXPid["system"] = playerArrayIndex;
}
function getSpaceship(uint256 _spaceshipId) public view returns (
uint256 _id,
string _name,
uint256 _speed,
address _captain,
uint256 _ticketCount,
uint256 _dividendRatio,
uint256 _spaceshipPrice
){
_id = spaceships[_spaceshipId].id;
_name = spaceships[_spaceshipId].name;
_speed = spaceships[_spaceshipId].speed;
_captain = spaceships[_spaceshipId].captain;
_ticketCount = spaceships[_spaceshipId].ticketCount;
_dividendRatio = spaceships[_spaceshipId].dividendRatio;
_spaceshipPrice = spaceships[_spaceshipId].spaceshipPrice;
}
function getNowTime() public view returns (uint256){
return now;
}
function checkName(string _name) public view returns (bool){
if (nameXPid[_name] == 0) {
return false;
}
return true;
}
function setYxName(address _address, string _name) external onlyOwner {
if (addressMPid[_address] == 0) {
uint256 playerArrayIndex = players.push(Player(_address, _name, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
addressMPid[_address] = playerArrayIndex;
pidXAddress[playerArrayIndex] = _address;
playerCount = players.length;
nameXPid[_name] = playerArrayIndex;
} else {
uint256 _pid = addressMPid[_address];
Player storage _p = players[_pid.sub(1)];
_p.name = _name;
nameXPid[_name] = _pid;
}
}
function setName(string _name) external payable {
require(msg.value >= editPlayerNamePrice);
if (addressMPid[msg.sender] == 0) {
uint256 playerArrayIndex = players.push(Player(msg.sender, _name, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
addressMPid[msg.sender] = playerArrayIndex;
pidXAddress[playerArrayIndex] = msg.sender;
playerCount = players.length;
nameXPid[_name] = playerArrayIndex;
} else {
uint256 _pid = addressMPid[msg.sender];
Player storage _p = players[_pid.sub(1)];
_p.name = _name;
nameXPid[_name] = _pid;
}
Player storage _sysP = players[0];
_sysP.earnings = _sysP.earnings.add(msg.value);
_sysP.distributionEarnings = _sysP.distributionEarnings.add(msg.value);
}
function _computePayMoney(uint256 _ticketCount, address _addr) private view returns (bool){
uint256 _initMoney = 0.01 ether;
uint256 _eachMoney = 0.0001 ether;
uint256 _payMoney = (spaceshipPrice.mul(_ticketCount)).add(addSpaceshipPrice.mul((_ticketCount.sub(1))));
_payMoney = _payMoney.sub((_eachMoney.mul(_ticketCount)));
uint256 _tmpPid = addressMPid[_addr];
Player memory _p = players[_tmpPid.sub(1)];
if (_p.earnings >= (_initMoney.mul(_ticketCount)) && _p.earnings >= _payMoney) {
return true;
}
return false;
}
function checkTicket(uint256 _ticketCount, uint256 _money) private view returns (bool){
uint256 _initMoney = 0.01 ether;
uint256 _eachMoney = 0.0001 ether;
uint256 _payMoney = (spaceshipPrice.mul(_ticketCount)).add(addSpaceshipPrice.mul((_ticketCount.sub(1))));
_payMoney = _payMoney.sub((_eachMoney.mul(_ticketCount)));
if (_money >= (_initMoney.mul(_ticketCount)) && _money >= _payMoney) {
return true;
}
return false;
}
function checkNewPlayer(address _player) private {
if (addressMPid[_player] == 0) {
uint256 playerArrayIndex = players.push(Player(_player, "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
addressMPid[_player] = playerArrayIndex;
pidXAddress[playerArrayIndex] = _player;
playerCount = players.length;
}
}
function addTicket(uint256 _ticketCount, uint256 _spaceshipNo, uint256 _pid) private {
spaceshipPrice = spaceshipPrice.add(addSpaceshipPrice.mul(_ticketCount));
totalTicketCount = totalTicketCount.add(_ticketCount);
Player storage _p = players[_pid.sub(1)];
_p.ticketCount = _p.ticketCount.add(_ticketCount);
if (_spaceshipNo == 0) {
_p.dlTicketCount = _p.dlTicketCount.add(_ticketCount);
Spaceship storage _s = spaceships[0];
_s.ticketCount = _s.ticketCount.add(_ticketCount);
_s.speed = _s.speed.add(_ticketCount.mul(_s.addSpeed));
}
if (_spaceshipNo == 1) {
_p.xzTicketCount = _p.xzTicketCount.add(_ticketCount);
Spaceship storage _s1 = spaceships[1];
_s1.ticketCount = _s1.ticketCount.add(_ticketCount);
_s1.speed = _s1.speed.add(_ticketCount.mul(_s1.addSpeed));
}
if (_spaceshipNo == 2) {
_p.jcTicketCount = _p.jcTicketCount.add(_ticketCount);
Spaceship storage _s2 = spaceships[2];
_s2.ticketCount = _s2.ticketCount.add(_ticketCount);
_s2.speed = _s2.speed.add(_ticketCount.mul(_s2.addSpeed));
}
}
function _payTicketByEarnings(uint256 _ticketCount, address _addr) private returns (uint256){
uint256 _tmpPid = addressMPid[_addr];
Player storage _p = players[_tmpPid.sub(1)];
uint256 _tmpMoney = spaceshipPrice.mul(_ticketCount);
uint256 _tmpMoney2 = addSpaceshipPrice.mul(_ticketCount.sub(1));
uint256 _returnMoney = _tmpMoney.add(_tmpMoney2);
_p.earnings = _p.earnings.sub(_returnMoney);
return _returnMoney;
}
function buyTicketByEarnings(uint256 _ticketCount, uint256 _spaceshipNo, string _name) external {
require(now < lotteryTime);
require(_spaceshipNo == 0 || _spaceshipNo == 1 || _spaceshipNo == 2);
require(addressMPid[msg.sender] != 0);
require(_computePayMoney(_ticketCount, msg.sender));
updateTime();
uint256 _money = _payTicketByEarnings(_ticketCount, msg.sender);
totalEarnings = totalEarnings.add(_money);
Player storage _p = players[addressMPid[msg.sender].sub(1)];
if (_p.parentId == 0 && nameXPid[_name] != 0) {
_p.parentId = nameXPid[_name];
}
luckyPayerId = addressMPid[msg.sender];
addTicket(_ticketCount, _spaceshipNo, addressMPid[msg.sender]);
addSpaceshipMoney(_money.div(100).mul(5));
Player storage _player = players[0];
uint256 _SysMoney = _money.div(100).mul(3);
_player.earnings = _player.earnings.add(_SysMoney);
_player.dividendEarnings = _player.dividendEarnings.add(_SysMoney);
uint256 _distributionMoney = _money.div(100).mul(10);
if (_p.parentId == 0) {
_player.earnings = _player.earnings.add(_distributionMoney);
_player.distributionEarnings = _player.distributionEarnings.add(_distributionMoney);
} else {
Player storage _player_ = players[_p.parentId.sub(1)];
_player_.earnings = _player_.earnings.add(_distributionMoney);
_player_.distributionEarnings = _player_.distributionEarnings.add(_distributionMoney);
}
if (_ticketCount > maxTotalTicket) {
maxTotalTicket = _ticketCount;
maxAirDropAddress = msg.sender;
}
uint256 _airDropMoney = _money.div(100).mul(2);
airdropPrizePool = airdropPrizePool.add(_airDropMoney);
if (airdropPrizePool >= 1 ether) {
Player storage _playerAirdrop = players[addressMPid[maxAirDropAddress].sub(1)];
_playerAirdrop.earnings = _playerAirdrop.earnings.add(airdropPrizePool);
_playerAirdrop.dividendEarnings = _playerAirdrop.dividendEarnings.add(airdropPrizePool);
airdropPrizePool = 0;
}
uint256 _remainderMoney = _cMoney(_money, _SysMoney, _distributionMoney, _airDropMoney);
updateGameMoney(_remainderMoney, _spaceshipNo, _ticketCount, addressMPid[msg.sender].sub(1));
}
function _cMoney(uint256 _money, uint256 _SysMoney, uint256 _distributionMoney, uint256 _airDropMoney)
private pure returns (uint256){
uint256 _czSpaceshipMoney = _money.div(100).mul(5).mul(3);
return _money.sub(_czSpaceshipMoney).sub(_SysMoney).
sub(_distributionMoney).sub(_airDropMoney);
}
function updateTime() private {
if (totalTicketCount < 50000) {
lotteryTime = now + 12 hours;
} else {
lotteryTime = now + 1 hours;
}
}
function buyTicket(uint256 _ticketCount, uint256 _spaceshipNo, string _name) external payable {
require(now < lotteryTime);
require(_spaceshipNo == 0 || _spaceshipNo == 1 || _spaceshipNo == 2);
require(checkTicket(_ticketCount, msg.value));
checkNewPlayer(msg.sender);
updateTime();
totalEarnings = totalEarnings.add(msg.value);
Player storage _p = players[addressMPid[msg.sender].sub(1)];
if (_p.parentId == 0 && nameXPid[_name] != 0) {
_p.parentId = nameXPid[_name];
}
luckyPayerId = addressMPid[msg.sender];
addTicket(_ticketCount, _spaceshipNo, addressMPid[msg.sender]);
addSpaceshipMoney(msg.value.div(100).mul(5));
Player storage _player = players[0];
uint256 _SysMoney = msg.value.div(100).mul(3);
_player.earnings = _player.earnings.add(_SysMoney);
_player.dividendEarnings = _player.dividendEarnings.add(_SysMoney);
uint256 _distributionMoney = msg.value.div(100).mul(10);
if (_p.parentId == 0) {
_player.earnings = _player.earnings.add(_distributionMoney);
_player.distributionEarnings = _player.distributionEarnings.add(_distributionMoney);
} else {
Player storage _player_ = players[_p.parentId.sub(1)];
_player_.earnings = _player_.earnings.add(_distributionMoney);
_player_.distributionEarnings = _player_.distributionEarnings.add(_distributionMoney);
}
if (_ticketCount > maxTotalTicket) {
maxTotalTicket = _ticketCount;
maxAirDropAddress = msg.sender;
}
uint256 _airDropMoney = msg.value.div(100).mul(2);
airdropPrizePool = airdropPrizePool.add(_airDropMoney);
if (airdropPrizePool >= 1 ether) {
Player storage _playerAirdrop = players[addressMPid[maxAirDropAddress].sub(1)];
_playerAirdrop.earnings = _playerAirdrop.earnings.add(airdropPrizePool);
_playerAirdrop.dividendEarnings = _playerAirdrop.dividendEarnings.add(airdropPrizePool);
airdropPrizePool = 0;
}
uint256 _remainderMoney = msg.value.sub((msg.value.div(100).mul(5)).mul(3)).sub(_SysMoney).
sub(_distributionMoney).sub(_airDropMoney);
updateGameMoney(_remainderMoney, _spaceshipNo, _ticketCount, addressMPid[msg.sender].sub(1));
}
function getFhMoney(uint256 _spaceshipNo, uint256 _money, uint256 _ticketCount, uint256 _targetNo) private view returns (uint256){
Spaceship memory _fc = spaceships[_spaceshipNo];
if (_spaceshipNo == _targetNo) {
uint256 _Ticket = _fc.ticketCount.sub(_ticketCount);
if (_Ticket == 0) {
return 0;
}
return _money.div(_Ticket);
} else {
if (_fc.ticketCount == 0) {
return 0;
}
return _money.div(_fc.ticketCount);
}
}
function updateGameMoney(uint256 _money, uint256 _spaceshipNo, uint256 _ticketCount, uint256 _arrayPid) private {
uint256 _lastMoney = addMoonPrizePool(_money, _spaceshipNo);
uint256 _dlMoney = _lastMoney.div(100).mul(53);
uint256 _xzMoney = _lastMoney.div(100).mul(33);
uint256 _jcMoney = _lastMoney.sub(_dlMoney).sub(_xzMoney);
uint256 _dlFMoney = getFhMoney(0, _dlMoney, _ticketCount, _spaceshipNo);
uint256 _xzFMoney = getFhMoney(1, _xzMoney, _ticketCount, _spaceshipNo);
uint256 _jcFMoney = getFhMoney(2, _jcMoney, _ticketCount, _spaceshipNo);
_fhMoney(_dlFMoney, _xzFMoney, _jcFMoney, _arrayPid, _spaceshipNo, _ticketCount);
}
function _fhMoney(uint256 _dlFMoney, uint256 _xzFMoney, uint256 _jcFMoney, uint256 arrayPid, uint256 _spaceshipNo, uint256 _ticketCount) private {
for (uint i = 0; i < players.length; i++) {
Player storage _tmpP = players[i];
uint256 _totalMoney = 0;
if (arrayPid != i) {
_totalMoney = _totalMoney.add(_tmpP.dlTicketCount.mul(_dlFMoney));
_totalMoney = _totalMoney.add(_tmpP.xzTicketCount.mul(_xzFMoney));
_totalMoney = _totalMoney.add(_tmpP.jcTicketCount.mul(_jcFMoney));
} else {
if (_spaceshipNo == 0) {
_totalMoney = _totalMoney.add((_tmpP.dlTicketCount.sub(_ticketCount)).mul(_dlFMoney));
} else {
_totalMoney = _totalMoney.add(_tmpP.dlTicketCount.mul(_dlFMoney));
}
if (_spaceshipNo == 1) {
_totalMoney = _totalMoney.add((_tmpP.xzTicketCount.sub(_ticketCount)).mul(_xzFMoney));
} else {
_totalMoney = _totalMoney.add(_tmpP.xzTicketCount.mul(_xzFMoney));
}
if (_spaceshipNo == 2) {
_totalMoney = _totalMoney.add((_tmpP.jcTicketCount.sub(_ticketCount)).mul(_jcFMoney));
} else {
_totalMoney = _totalMoney.add(_tmpP.jcTicketCount.mul(_jcFMoney));
}
}
_tmpP.earnings = _tmpP.earnings.add(_totalMoney);
_tmpP.dividendEarnings = _tmpP.dividendEarnings.add(_totalMoney);
}
}
function addMoonPrizePool(uint256 _money, uint256 _spaceshipNo) private returns (uint){
uint256 _tmpMoney;
if (_spaceshipNo == 0) {
_tmpMoney = _money.div(100).mul(80);
totalDividendEarnings = totalDividendEarnings.add((_money.sub(_tmpMoney)));
}
if (_spaceshipNo == 1) {
_tmpMoney = _money.div(100).mul(50);
totalDividendEarnings = totalDividendEarnings.add((_money.sub(_tmpMoney)));
}
if (_spaceshipNo == 2) {
_tmpMoney = _money.div(100).mul(20);
totalDividendEarnings = totalDividendEarnings.add((_money.sub(_tmpMoney)));
}
moonPrizePool = moonPrizePool.add(_tmpMoney);
return _money.sub(_tmpMoney);
}
function addSpaceshipMoney(uint256 _money) internal {
Spaceship storage _spaceship0 = spaceships[0];
uint256 _pid0 = addressMPid[_spaceship0.captain];
Player storage _player0 = players[_pid0.sub(1)];
_player0.earnings = _player0.earnings.add(_money);
_player0.dividendEarnings = _player0.dividendEarnings.add(_money);
Spaceship storage _spaceship1 = spaceships[1];
uint256 _pid1 = addressMPid[_spaceship1.captain];
Player storage _player1 = players[_pid1.sub(1)];
_player1.earnings = _player1.earnings.add(_money);
_player1.dividendEarnings = _player1.dividendEarnings.add(_money);
Spaceship storage _spaceship2 = spaceships[2];
uint256 _pid2 = addressMPid[_spaceship2.captain];
Player storage _player2 = players[_pid2.sub(1)];
_player2.earnings = _player2.earnings.add(_money);
_player2.dividendEarnings = _player2.dividendEarnings.add(_money);
}
function getPlayerInfo(address _playerAddress) public view returns (
address _addr,
string _name,
uint256 _earnings,
uint256 _ticketCount,
uint256 _dividendEarnings,
uint256 _distributionEarnings,
uint256 _dlTicketCount,
uint256 _xzTicketCount,
uint256 _jcTicketCount
){
uint256 _pid = addressMPid[_playerAddress];
Player storage _player = players[_pid.sub(1)];
_addr = _player.addr;
_name = _player.name;
_earnings = _player.earnings;
_ticketCount = _player.ticketCount;
_dividendEarnings = _player.dividendEarnings;
_distributionEarnings = _player.distributionEarnings;
_dlTicketCount = _player.dlTicketCount;
_xzTicketCount = _player.xzTicketCount;
_jcTicketCount = _player.jcTicketCount;
}
function addSystemUserEarnings(uint256 _money) private {
Player storage _player = players[0];
_player.earnings = _player.earnings.add(_money);
}
function withdraw() public {
require(addressMPid[msg.sender] != 0);
Player storage _player = players[addressMPid[msg.sender].sub(1)];
_player.addr.transfer(_player.earnings);
_player.withdrawalAmount = _player.withdrawalAmount.add(_player.earnings);
_player.earnings = 0;
_player.distributionEarnings = 0;
_player.dividendEarnings = 0;
}
function makeMoney() public {
require(now > lotteryTime);
moonPrizePool = moonPrizePool.add(airdropPrizePool);
uint256 _pMoney = moonPrizePool.div(2);
Player storage _luckyPayer = players[luckyPayerId.sub(1)];
_luckyPayer.earnings = _luckyPayer.earnings.add(_pMoney);
uint256 _nextMoonPrizePool = moonPrizePool.div(100).mul(2);
uint256 _luckyCaptainMoney = moonPrizePool.div(100).mul(5);
uint256 _luckyCrewMoney = moonPrizePool.sub(_nextMoonPrizePool).sub(_luckyCaptainMoney).sub(_pMoney);
uint256 _no1Spaceship = getFastestSpaceship();
Spaceship storage _s = spaceships[_no1Spaceship];
uint256 _pid = addressMPid[_s.captain];
Player storage _pPayer = players[_pid.sub(1)];
_pPayer.earnings = _pPayer.earnings.add(_luckyCaptainMoney);
uint256 _eachMoney = _getLuckySpaceshipMoney(_no1Spaceship, _luckyCrewMoney);
for (uint i = 0; i < players.length; i++) {
Player storage _tmpP = players[i];
if (_no1Spaceship == 0) {
_tmpP.earnings = _tmpP.earnings.add(_tmpP.dlTicketCount.mul(_eachMoney));
_tmpP.dividendEarnings = _tmpP.dividendEarnings.add(_tmpP.dlTicketCount.mul(_eachMoney));
}
if (_no1Spaceship == 1) {
_tmpP.earnings = _tmpP.earnings.add(_tmpP.xzTicketCount.mul(_eachMoney));
_tmpP.dividendEarnings = _tmpP.dividendEarnings.add(_tmpP.xzTicketCount.mul(_eachMoney));
}
if (_no1Spaceship == 2) {
_tmpP.earnings = _tmpP.earnings.add(_tmpP.jcTicketCount.mul(_eachMoney));
_tmpP.dividendEarnings = _tmpP.dividendEarnings.add(_tmpP.jcTicketCount.mul(_eachMoney));
}
_tmpP.dlTicketCount = 0;
_tmpP.xzTicketCount = 0;
_tmpP.jcTicketCount = 0;
_tmpP.ticketCount = 0;
}
_initSpaceship();
totalTicketCount = 0;
airdropPrizePool = 0;
moonPrizePool = _nextMoonPrizePool;
lotteryTime = now + 12 hours;
spaceshipPrice = 0.01 ether;
maxAirDropAddress = pidXAddress[1];
maxTotalTicket = 0;
round = round.add(1);
luckyPayerId = 1;
}
function _initSpaceship() private {
for (uint i = 0; i < spaceships.length; i++) {
Spaceship storage _s = spaceships[i];
_s.captain = pidXAddress[1];
_s.ticketCount = 0;
_s.spaceshipPrice = 15 ether;
_s.speed = 100000;
}
}
function _getLuckySpaceshipMoney(uint256 _spaceshipId, uint256 _luckyMoney) private view returns (uint256){
Spaceship memory _s = spaceships[_spaceshipId];
uint256 _eachLuckyMoney = _luckyMoney.div(_s.ticketCount);
return _eachLuckyMoney;
}
function getFastestSpaceship() private view returns (uint256){
Spaceship memory _dlSpaceship = spaceships[0];
Spaceship memory _xzSpaceship = spaceships[1];
Spaceship memory _jcSpaceship = spaceships[2];
uint256 _maxSpeed;
if (_jcSpaceship.speed >= _xzSpaceship.speed) {
if (_jcSpaceship.speed >= _dlSpaceship.speed) {
_maxSpeed = 2;
} else {
_maxSpeed = 0;
}
} else {
if (_xzSpaceship.speed >= _dlSpaceship.speed) {
_maxSpeed = 1;
} else {
_maxSpeed = 0;
}
}
return _maxSpeed;
}
function getGameInfo() public view returns (
uint256 _totalTicketCount,
uint256 _airdropPrizePool,
uint256 _moonPrizePool,
uint256 _lotteryTime,
uint256 _nowTime,
uint256 _spaceshipPrice,
uint256 _round,
uint256 _totalEarnings,
uint256 _totalDividendEarnings
){
_totalTicketCount = totalTicketCount;
_airdropPrizePool = airdropPrizePool;
_moonPrizePool = moonPrizePool;
_lotteryTime = lotteryTime;
_nowTime = now;
_spaceshipPrice = spaceshipPrice;
_round = round;
_totalEarnings = totalEarnings;
_totalDividendEarnings = totalDividendEarnings;
}
function _updateSpaceshipPrice(uint256 _spaceshipId) internal {
spaceships[_spaceshipId].spaceshipPrice = spaceships[_spaceshipId].spaceshipPrice.add(
spaceships[_spaceshipId].spaceshipPrice.mul(3).div(10));
}
function campaignCaptain(uint _spaceshipId) external payable {
require(now < lotteryTime);
require(msg.value == spaceships[_spaceshipId].spaceshipPrice);
if (addressMPid[msg.sender] == 0) {
uint256 playerArrayIndex = players.push(Player(msg.sender, "", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0));
addressMPid[msg.sender] = playerArrayIndex;
pidXAddress[playerArrayIndex] = msg.sender;
playerCount = players.length;
}
spaceships[_spaceshipId].captain.transfer(msg.value);
spaceships[_spaceshipId].captain = msg.sender;
_updateSpaceshipPrice(_spaceshipId);
}
}
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;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29376000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xb01D9801bED31Ba24F285d225744bC4F54745942;
}
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 TransferRecipient {
function tokenFallback(address _from, uint256 _value, bytes _extraData) public returns(bool);
}
interface ApprovalRecipient {
function approvalFallback(address _from, uint256 _value, bytes _extraData) public returns(bool);
}
contract ERCToken {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
function allowance(address _owner,address _spender) public view returns(uint256);
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);
}
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 MyToken is ERCToken {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals=18;
mapping (address => mapping (address => uint256)) internal allowed;
function MyToken (
string tokenName,
string tokenSymbol,
uint256 initSupply
) public {
totalSupply = initSupply * 10 ** 18;
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function greet() view public returns (string) {
return 'hello';
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousbalanceOf = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] =balanceOf[_to].add(_value);
Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousbalanceOf);
}
function transfer(address _to, uint256 _value) public returns (bool success){
_transfer(msg.sender, _to, _value);
return true;
}
function transferAndCall(address _to, uint256 _value, bytes _data)
public
returns (bool success) {
_transfer(msg.sender,_to, _value);
if(_isContract(_to))
{
TransferRecipient spender = TransferRecipient(_to);
if(!spender.tokenFallback(msg.sender, _value, _data))
{
revert();
}
}
return true;
}
function _isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender]= allowed[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function allowance(address _owner,address _spender) public view returns(uint256){
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
allowed[msg.sender][_spender] = _value;
if(_isContract(_spender)){
ApprovalRecipient spender = ApprovalRecipient(_spender);
if(!spender.approvalFallback(msg.sender, _value, _extraData)){
revert();
}
}
Approval(msg.sender, _spender, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract RogChainToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "ROG";
name = "RogChain Token";
decimals = 18;
_totalSupply = 29000000000000000000000000000;
balances[0x3e1E002DBBAc628a0c44C21578137a3cE17e9927] = _totalSupply;
emit Transfer(address(0), 0x3e1E002DBBAc628a0c44C21578137a3cE17e9927, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^0.4.19;
interface UNetworkToken {
function transfer(address _to, uint256 _value) public;
}
contract AirDrop {
UNetworkToken UUU;
address public owner;
address[] public recipients = [0x0aF9d2fee427dDb222F1770585F5681969Fdc673, 0xaD41A9B2BAF0671312ff74bC9C4E4447Cc2D3b10, 0x503Fa70B5365978cc6D1784F78983bBe6F041F43, 0xBBf442191aB5213de67Dd4026560c9940F349A6B, 0x3cfbCF1A945Ed6FBf14b701C4524620b29CaF92D, 0xC21395D0ed740961d700B9665687826761f8F0E4, 0xa5851819a8689dbe652347af7772792b2c88bb28, 0xA34A8Ce83B19a89e3a8b3703424451f6bD203b17, 0x716C08e41B99cDd2Aab4bd45ADf20e40b70eaa4c, 0x3B8a44473199C577B591A19ECa42E3c5709A7082, 0xAEDBa642E4F4B2DADBd710D48e21Ac8Ca71ace9c, 0xAca3eD76Dc39d81D0965f2f345E1fd81A0aD5EA8, 0x4d8028cCeeCFdD6bE01b9453B45aC532A4cA3b89, 0x82EDC5a564eB0270381e7f0a5b5e49Eeb8E7408d, 0xf4bf47BfB25937C5BACD84D60791e105bdf1863a, 0xbfaaf37cf26fdd8f5d0af25783023ef65271c541, 0x84F748c6f3514794E1A2FF74Cb6FcB01482a4A08, 0x77ab8a655C6CF540471140EFD0EaaBaE78C132a0, 0xf0b62c2987a5abe5b122d5c1cbe8cc4db3e75fce, 0x2D3c3210188f40cE421E765C8Cb42B9C2d50dAcB, 0x1b1844af2d1a25ac0fe66c82161f505fca26fdd1, 0x6d15061a61E3d0E984410b9e6442422bb4Af237c, 0x5e39CdEdB4AFE732EC89760187bf3Bfe3679Fb7F, 0x1A7E1864DAcF2bB69efd88000245092c6D9FA0f7, 0x2357ee9647e47e47610ff75378ac0543404ec15e, 0x81D723361d4F3e648F2c9c479d88DC6dEBF4fA5f, 0xc1F064Cbb8001da72F8E823D8865f6ec8BAd6e3A];
uint256[] public values = [20000, 20000, 10000, 20000, 20000, 20000, 10000, 10000, 10000, 10000, 10000, 20000, 50000, 50000, 50000, 20000, 50000, 20000, 50000, 10000, 20000, 20000, 20000, 20000, 10000, 10000, 10000];
function AirDrop() public {
require(values.length == recipients.length);
UUU = UNetworkToken(0x3543638eD4a9006E4840B105944271Bcea15605D);
owner = msg.sender;
}
function drop() public {
require(msg.sender == owner);
for (uint256 i = 0; i < recipients.length; i++) {
UUU.transfer(recipients[i], values[i] * 10 ** 18);
}
}
function refund() public {
require (msg.sender == owner);
UUU.transfer(owner, 100000 * 10**18);
}
} | 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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
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(address(this).balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
payee.transfer(payment);
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract CryptoEngineerInterface {
uint256 public prizePool = 0;
function calculateCurrentVirus(address ) public pure returns(uint256 ) {}
function subVirus(address , uint256 ) public {}
function claimPrizePool(address , uint256 ) public {}
function fallback() public payable {}
}
interface CryptoMiningWarInterface {
function addCrystal( address , uint256 ) external;
function subCrystal( address , uint256 ) external;
}
contract CryptoBossWannaCry is PullPayment{
bool init = false;
address public administrator;
uint256 public bossRoundNumber;
uint256 private randNonce;
uint256 constant public BOSS_HP_DEFAULT = 100000;
uint256 public HALF_TIME_ATK_BOSS = 0;
uint256 constant public VIRUS_MINING_PERIOD = 86400;
uint256 public BOSS_DEF_DEFFAULT = 0;
CryptoEngineerInterface public EngineerContract;
CryptoMiningWarInterface public MiningwarContract;
mapping(address => PlayerData) public players;
mapping(uint256 => BossData) public bossData;
struct PlayerData {
uint256 currentBossRoundNumber;
uint256 lastBossRoundNumber;
uint256 win;
uint256 share;
uint256 dame;
uint256 nextTimeAtk;
}
struct BossData {
uint256 bossRoundNumber;
uint256 bossHp;
uint256 def;
uint256 prizePool;
address playerLastAtk;
uint256 totalDame;
bool ended;
}
event eventAttackBoss(
uint256 bossRoundNumber,
address playerAtk,
uint256 virusAtk,
uint256 dame,
uint256 timeAtk,
bool isLastHit,
uint256 crystalsReward
);
event eventEndAtkBoss(
uint256 bossRoundNumber,
address playerWin,
uint256 ethBonus
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
constructor() public {
administrator = msg.sender;
EngineerContract = CryptoEngineerInterface(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
MiningwarContract = CryptoMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function setupMiniGame( uint256 , uint256 ) public
{
}
function upgrade(address addr) public
{
require(msg.sender == administrator);
selfdestruct(addr);
}
function startGame() public isAdministrator
{
require(init == false);
init = true;
bossData[bossRoundNumber].ended = true;
startNewBoss();
}
function setDefenceBoss(uint256 _value) public isAdministrator
{
BOSS_DEF_DEFFAULT = _value;
}
function setHalfTimeAtkBoss(uint256 _value) public isAdministrator
{
HALF_TIME_ATK_BOSS = _value;
}
function startNewBoss() private
{
require(bossData[bossRoundNumber].ended == true);
bossRoundNumber = bossRoundNumber + 1;
uint256 bossHp = BOSS_HP_DEFAULT * bossRoundNumber;
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
EngineerContract.claimPrizePool(address(this), prizePool);
bossData[bossRoundNumber] = BossData(bossRoundNumber, bossHp, BOSS_DEF_DEFFAULT, prizePool, 0x0, 0, false);
}
function endAtkBoss() private
{
require(bossData[bossRoundNumber].ended == false);
require(bossData[bossRoundNumber].totalDame >= bossData[bossRoundNumber].bossHp);
BossData storage b = bossData[bossRoundNumber];
b.ended = true;
uint256 ethBonus = SafeMath.div( SafeMath.mul(b.prizePool, 5), 100 );
if (b.playerLastAtk != 0x0) {
PlayerData storage p = players[b.playerLastAtk];
p.win = p.win + ethBonus;
}
emit eventEndAtkBoss(bossRoundNumber, b.playerLastAtk, ethBonus);
startNewBoss();
}
function atkBoss(uint256 _value) public disableContract
{
require(bossData[bossRoundNumber].ended == false);
require(bossData[bossRoundNumber].totalDame < bossData[bossRoundNumber].bossHp);
require(players[msg.sender].nextTimeAtk <= now);
uint256 currentVirus = getEngineerCurrentVirus(msg.sender);
if (_value > currentVirus) { revert(); }
EngineerContract.subVirus(msg.sender, _value);
uint256 rate = 50 + randomNumber(msg.sender, 100);
uint256 atk = SafeMath.div(SafeMath.mul(_value, rate), 100);
updateShareETH(msg.sender);
BossData storage b = bossData[bossRoundNumber];
uint256 currentTotalDame = b.totalDame;
uint256 dame = 0;
if (atk > b.def) {
dame = SafeMath.sub(atk, b.def);
}
b.totalDame = SafeMath.min(SafeMath.add(currentTotalDame, dame), b.bossHp);
b.playerLastAtk = msg.sender;
dame = SafeMath.sub(b.totalDame, currentTotalDame);
uint256 crystalsBonus = SafeMath.div(SafeMath.mul(dame, 5), 100);
MiningwarContract.addCrystal(msg.sender, crystalsBonus);
PlayerData storage p = players[msg.sender];
p.nextTimeAtk = now + HALF_TIME_ATK_BOSS;
if (p.currentBossRoundNumber == bossRoundNumber) {
p.dame = SafeMath.add(p.dame, dame);
} else {
p.currentBossRoundNumber = bossRoundNumber;
p.dame = dame;
}
bool isLastHit;
if (b.totalDame >= b.bossHp) {
isLastHit = true;
endAtkBoss();
}
emit eventAttackBoss(b.bossRoundNumber, msg.sender, _value, dame, now, isLastHit, crystalsBonus);
}
function updateShareETH(address _addr) private
{
PlayerData storage p = players[_addr];
if (
bossData[p.currentBossRoundNumber].ended == true &&
p.lastBossRoundNumber < p.currentBossRoundNumber
) {
p.share = SafeMath.add(p.share, calculateShareETH(msg.sender, p.currentBossRoundNumber));
p.lastBossRoundNumber = p.currentBossRoundNumber;
}
}
function calculateShareETH(address _addr, uint256 _bossRoundNumber) public view returns(uint256 _share)
{
PlayerData memory p = players[_addr];
BossData memory b = bossData[_bossRoundNumber];
if (
p.lastBossRoundNumber >= p.currentBossRoundNumber &&
p.currentBossRoundNumber != 0
) {
_share = 0;
} else {
_share = SafeMath.div(SafeMath.mul(SafeMath.mul(b.prizePool, 95), p.dame), SafeMath.mul(b.totalDame, 100));
}
if (b.ended == false) {
_share = 0;
}
}
function withdrawReward() public disableContract
{
updateShareETH(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 reward = SafeMath.add(p.share, p.win);
msg.sender.send(reward);
p.win = 0;
p.share = 0;
}
function devFee(uint256 _amount) private pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(_amount, 5), 100);
}
function randomNumber(address _addr, uint256 _maxNumber) private returns(uint256)
{
randNonce = randNonce + 1;
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function getEngineerPrizePool() private view returns(uint256 _prizePool)
{
_prizePool = EngineerContract.prizePool();
}
function getEngineerCurrentVirus(address _addr) private view returns(uint256 _currentVirus)
{
_currentVirus = EngineerContract.calculateCurrentVirus(_addr);
_currentVirus = SafeMath.div(_currentVirus, VIRUS_MINING_PERIOD);
}
} | 0 |
pragma solidity ^0.4.24;
contract PCKevents {
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 PCPAmount,
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 PCPAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
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 modularKey is PCKevents {}
contract PlayCoinKey is modularKey {
using SafeMath for *;
using NameFilter for string;
using PCKKeysCalcLong for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x14229878e85e57FF4109dc27bb2EfB5EA8067E6E);
string constant public name = "PlayCoin Key";
string constant public symbol = "PCK";
uint256 private rndExtra_ = 2 minutes;
uint256 private rndGap_ = 15 minutes;
uint256 constant private rndInit_ = 24 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 constant private rndMin_ = 10 minutes;
uint256 public reduceMul_ = 3;
uint256 public reduceDiv_ = 2;
uint256 public rndReduceThreshold_ = 10e18;
bool public closed_ = false;
address private admin = msg.sender;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => PCKdatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => PCKdatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => PCKdatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => PCKdatasets.TeamFee) public fees_;
mapping (uint256 => PCKdatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = PCKdatasets.TeamFee(30,6);
fees_[1] = PCKdatasets.TeamFee(43,0);
fees_[2] = PCKdatasets.TeamFee(56,10);
fees_[3] = PCKdatasets.TeamFee(43,8);
potSplit_[0] = PCKdatasets.PotSplit(15,10);
potSplit_[1] = PCKdatasets.PotSplit(25,0);
potSplit_[2] = PCKdatasets.PotSplit(20,20);
potSplit_[3] = PCKdatasets.PotSplit(30,10);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isRoundActivated() {
require(round_[rID_].ended == false, "the round is finished");
_;
}
modifier isHuman() {
require(msg.sender == tx.origin, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
modifier onlyAdmins() {
require(msg.sender == admin, "onlyAdmins failed - msg.sender is not an admin");
_;
}
function kill () onlyAdmins() public {
require(round_[rID_].ended == true && closed_ == true, "the round is active or not close");
selfdestruct(admin);
}
function getRoundStatus() isActivated() public view returns(uint256, bool){
return (rID_, round_[rID_].ended);
}
function setThreshold(uint256 _threshold, uint256 _mul, uint256 _div) onlyAdmins() public {
require(_threshold > 0, "threshold must greater 0");
require(_mul > 0, "mul must greater 0");
require(_div > 0, "div must greater 0");
rndReduceThreshold_ = _threshold;
reduceMul_ = _mul;
reduceDiv_ = _div;
}
function setEnforce(bool _closed) onlyAdmins() public returns(bool, uint256, bool) {
closed_ = _closed;
if( !closed_ && round_[rID_].ended == true && activated_ == true ){
nextRound();
}
else if( closed_ && round_[rID_].ended == false && activated_ == true ){
round_[rID_].end = now - 1;
}
return (closed_, rID_, now > round_[rID_].end);
}
function()
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
PCKdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
PCKdatasets.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)
{
PCKdatasets.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 PCKevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit PCKevents.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 PCKevents.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 PCKevents.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 PCKevents.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, PCKdatasets.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_);
if( !closed_ ){
nextRound();
}
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit PCKevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, PCKdatasets.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_);
if( !closed_ ) {
nextRound();
}
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit PCKevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, PCKdatasets.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, _eth);
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(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.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, PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function nextRound() private {
rID_++;
round_[rID_].strt = now;
round_[rID_].end = now.add(rndInit_).add(rndGap_);
}
function endRound(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com.add(_p3d.sub(_p3d / 2)));
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_res = _res.add(_p3d / 2);
_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_.PCPAmount = _p3d;
_eventData_.newPot = _res;
_rID++;
round_[_rID].ended = false;
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, uint256 _eth)
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);
uint256 _newEndTime;
if (_newTime < (rndMax_).add(_now))
_newEndTime = _newTime;
else
_newEndTime = rndMax_.add(_now);
if ( _eth >= rndReduceThreshold_ ) {
uint256 reduce = ((((_keys) / (1000000000000000000))).mul(rndInc_ * reduceMul_) / reduceDiv_);
if( _newEndTime > reduce && _now + rndMin_ + reduce < _newEndTime){
_newEndTime = (_newEndTime).sub(reduce);
}
else if ( _newEndTime > reduce ){
_newEndTime = _now + rndMin_;
}
}
round_[_rID].end = _newEndTime;
}
function getReduce(uint256 _rID, uint256 _eth) public view returns(uint256,uint256){
uint256 _keys = calcKeysReceived(_rID, _eth);
if ( _eth >= rndReduceThreshold_ ) {
return ( ((((_keys) / (1000000000000000000))).mul(rndInc_ * reduceMul_) / reduceDiv_), (((_keys) / (1000000000000000000)).mul(rndInc_)) );
} else {
return (0, (((_keys) / (1000000000000000000)).mul(rndInc_)) );
}
}
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, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(admin).call.value(_com)()) {
_p3d = _com;
_com = 0;
}
uint256 _long = _eth / 100;
potSwap(_long);
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit PCKevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
admin.transfer(_p3d.sub(_p3d / 2));
round_[_rID].pot = round_[_rID].pot.add(_p3d / 2);
_eventData_.PCPAmount = _p3d.add(_eventData_.PCPAmount);
}
return(_eventData_);
}
function potSwap(uint256 _pot) private {
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(_pot);
emit PCKevents.onPotSwapDeposit(_rID, _pot);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit PCKevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate() public {
require(
msg.sender == admin,
"only team just can activate"
);
require(activated_ == false, "PCK already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library PCKdatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 PCPAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library PCKKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PCKExtSettingInterface {
function getFastGap() external view returns(uint256);
function getLongGap() external view returns(uint256);
function getFastExtra() external view returns(uint256);
function getLongExtra() external view returns(uint256);
}
interface PlayCoinGodInterface {
function deposit() external payable;
}
interface ProForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value)public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)public constant returns (uint256);
function transferFrom(address from, address to, uint256 value)public returns (bool);
function approve(address spender, uint256 value)public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
emit Pause();
return true;
}
function unpause()public onlyOwner whenPaused returns (bool) {
paused = false;
emit Unpause();
return true;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value)public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BIMGToken is StandardToken, Pausable {
string public constant name = "BIMG";
string public constant symbol = "BIMG";
uint256 public constant decimals = 18;
struct LockToken{
uint256 amount;
uint32 time;
}
struct LockTokenSet{
LockToken[] lockList;
}
mapping ( address => LockTokenSet ) addressTimeLock;
mapping ( address => bool ) lockAdminList;
event TransferWithLockEvt(address indexed from, address indexed to, uint256 value,uint32 lockTime );
constructor() public {
totalSupply = 10 * (10 ** 8) * (10 ** 18);
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[msg.sender].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)public whenNotPaused returns (bool) {
assert ( balances[_from].sub( getLockAmount( msg.sender ) ) >= _value );
return super.transferFrom(_from, _to, _value);
}
function getLockAmount( address myaddress ) public view returns ( uint256 lockSum ) {
uint256 lockAmount = 0;
for( uint32 i = 0; i < addressTimeLock[myaddress].lockList.length; i ++ ){
if( addressTimeLock[myaddress].lockList[i].time > now ){
lockAmount += addressTimeLock[myaddress].lockList[i].amount;
}
}
return lockAmount;
}
function getLockListLen( address myaddress ) public view returns ( uint256 lockAmount ){
return addressTimeLock[myaddress].lockList.length;
}
function getLockByIdx( address myaddress,uint32 idx ) public view returns ( uint256 lockAmount, uint32 lockTime ){
if( idx >= addressTimeLock[myaddress].lockList.length ){
return (0,0);
}
lockAmount = addressTimeLock[myaddress].lockList[idx].amount;
lockTime = addressTimeLock[myaddress].lockList[idx].time;
return ( lockAmount,lockTime );
}
function transferWithLock( address _to, uint256 _value,uint32 _lockTime )public whenNotPaused {
assert( lockAdminList[msg.sender] == true );
assert( _lockTime > now );
transfer( _to, _value );
bool needNewLock = true;
for( uint32 i = 0 ; i< addressTimeLock[_to].lockList.length; i ++ ){
if( addressTimeLock[_to].lockList[i].time < now ){
addressTimeLock[_to].lockList[i].time = _lockTime;
addressTimeLock[_to].lockList[i].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime );
needNewLock = false;
break;
}
}
if( needNewLock == true ){
addressTimeLock[_to].lockList.length ++ ;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].time = _lockTime;
addressTimeLock[_to].lockList[(addressTimeLock[_to].lockList.length-1)].amount = _value;
emit TransferWithLockEvt( msg.sender,_to,_value,_lockTime);
}
}
function setLockAdmin(address _to,bool canUse)public onlyOwner{
assert( lockAdminList[_to] != canUse );
lockAdminList[_to] = canUse;
}
function canUseLock() public view returns (bool){
return lockAdminList[msg.sender];
}
} | 1 |
pragma solidity ^0.4.17;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = 0x0567cB7c5A688401Aab87093058754E096C4d37E;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner,_newOwner);
owner = _newOwner;
}
}
contract BlupassToken {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract BlupassICO is Owned {
using SafeMath for uint256;
uint256 public totalRaised;
uint256 public totalDistributed;
uint256 public RATE;
BlupassToken public BLU;
bool public isStopped = false;
mapping(address => bool) whitelist;
event LogWhiteListed(address _addr);
event LogBlackListed(address _addr);
event LogFundingReceived(address _addr, uint _amount, uint _currentTotal);
event LogBeneficiaryPaid(address _beneficiaryAddress);
event LogFundingSuccessful(uint _totalRaised);
event LogFunderInitialized(address _creator);
event LogContributorsPayout(address _addr, uint _amount);
modifier onlyWhenRunning {
require(!isStopped);
_;
}
modifier onlyifWhiteListed {
require(whitelist[msg.sender]);
_;
}
function BlupassICO (BlupassToken _addressOfToken) public {
require(_addressOfToken != address(0));
RATE = 4000;
BLU = BlupassToken(_addressOfToken);
emit LogFunderInitialized(owner);
}
function() public payable {
contribute();
}
function contribute() onlyWhenRunning onlyifWhiteListed public payable {
require(msg.value >= 1 ether);
uint256 tokenBought;
uint256 bonus;
totalRaised = totalRaised.add(msg.value);
tokenBought = msg.value.mul(RATE);
if (msg.value >= 5 ether && msg.value <= 9 ether) {
bonus = (tokenBought.mul(20)).div(100);
tokenBought = tokenBought.add(bonus);
}
if (msg.value >= 10 ether) {
bonus = (tokenBought.mul(40)).div(100);
tokenBought = tokenBought.add(bonus);
}
require(BLU.balanceOf(this) >= tokenBought);
totalDistributed = totalDistributed.add(tokenBought);
BLU.transfer(msg.sender,tokenBought);
owner.transfer(msg.value);
emit LogContributorsPayout(msg.sender,tokenBought);
emit LogBeneficiaryPaid(owner);
emit LogFundingReceived(msg.sender, msg.value, totalRaised);
}
function addToWhiteList(address _userAddress) onlyOwner public returns(bool) {
require(_userAddress != address(0));
if (!whitelist[_userAddress]) {
whitelist[_userAddress] = true;
emit LogWhiteListed(_userAddress);
return true;
} else {
return false;
}
}
function removeFromWhiteList(address _userAddress) onlyOwner public returns(bool) {
require(_userAddress != address(0));
if(whitelist[_userAddress]) {
whitelist[_userAddress] = false;
emit LogBlackListed(_userAddress);
return true;
} else {
return false;
}
}
function checkIfWhiteListed(address _userAddress) view public returns(bool) {
return whitelist[_userAddress];
}
function stopICO() onlyOwner public {
isStopped = true;
}
function resumeICO() onlyOwner public {
isStopped = false;
}
function claimTokens() onlyOwner public {
uint256 remainder = BLU.balanceOf(this);
BLU.transfer(owner,remainder);
}
} | 0 |
pragma solidity ^0.4.25;
contract CSportsConstants {
uint16 public MAX_MARKETING_TOKENS = 2500;
uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney;
uint256 public COMMISSIONER_AUCTION_DURATION = 14 days;
uint32 constant WEEK_SECS = 1 weeks;
}
contract CSportsAuth is CSportsConstants {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
address public commissionerAddress;
bool public paused = false;
bool public isDevelopment = true;
modifier onlyUnderDevelopment() {
require(isDevelopment == true);
_;
}
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCommissioner() {
require(msg.sender == commissionerAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress ||
msg.sender == commissionerAddress
);
_;
}
modifier notContract() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
_;
}
function setProduction() public onlyCEO onlyUnderDevelopment {
isDevelopment = false;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function setCommissioner(address _newCommissioner) public onlyCEO {
require(_newCommissioner != address(0));
commissionerAddress = _newCommissioner;
}
function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO {
require(_ceo != address(0));
require(_cfo != address(0));
require(_coo != address(0));
require(_commish != address(0));
ceoAddress = _ceo;
cfoAddress = _cfo;
cooAddress = _coo;
commissionerAddress = _commish;
}
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(address(this).balance);
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
interface CSportsMinter {
function isMinter() external pure returns (bool);
function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) external;
}
contract CSportsRosterPlayer {
struct RealWorldPlayer {
uint128 md5Token;
uint128 prevCommissionerSalePrice;
uint64 lastMintedTime;
uint32 mintedCount;
bool hasActiveCommissionerAuction;
bool mintingEnabled;
string metadata;
}
}
contract CSportsLeagueRoster is CSportsAuth, CSportsRosterPlayer {
CSportsMinter public minterContract;
RealWorldPlayer[] public realWorldPlayers;
mapping (uint128 => uint32) public md5TokenToRosterIndex;
modifier onlyCoreContract() {
require(msg.sender == address(minterContract));
_;
}
constructor() public {
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
commissionerAddress = msg.sender;
}
function isLeagueRosterContract() public pure returns (bool) {
return true;
}
function realWorldPlayerFromIndex(uint128 idx) public view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled) {
RealWorldPlayer memory _rwp;
_rwp = realWorldPlayers[idx];
md5Token = _rwp.md5Token;
prevCommissionerSalePrice = _rwp.prevCommissionerSalePrice;
lastMintedTime = _rwp.lastMintedTime;
mintedCount = _rwp.mintedCount;
hasActiveCommissionerAuction = _rwp.hasActiveCommissionerAuction;
mintingEnabled = _rwp.mintingEnabled;
}
function setCoreContractAddress(address _address) public onlyCEO {
CSportsMinter candidateContract = CSportsMinter(_address);
require(candidateContract.isMinter());
minterContract = candidateContract;
}
function playerCount() public view returns (uint32 count) {
return uint32(realWorldPlayers.length);
}
function addAndMintPlayers(uint128[] _md5Tokens, bool[] _mintingEnabled, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public onlyCommissioner {
addRealWorldPlayers(_md5Tokens, _mintingEnabled);
minterContract.mintPlayers(_md5Tokens, _startPrice, _endPrice, _duration);
}
function addRealWorldPlayers(uint128[] _md5Tokens, bool[] _mintingEnabled) public onlyCommissioner {
if (_md5Tokens.length != _mintingEnabled.length) {
revert();
}
for (uint32 i = 0; i < _md5Tokens.length; i++) {
if ( (realWorldPlayers.length == 0) ||
((md5TokenToRosterIndex[_md5Tokens[i]] == 0) && (realWorldPlayers[0].md5Token != _md5Tokens[i])) ) {
RealWorldPlayer memory _realWorldPlayer = RealWorldPlayer({
md5Token: _md5Tokens[i],
prevCommissionerSalePrice: 0,
lastMintedTime: 0,
mintedCount: 0,
hasActiveCommissionerAuction: false,
mintingEnabled: _mintingEnabled[i],
metadata: ""
});
uint256 _rosterIndex = realWorldPlayers.push(_realWorldPlayer) - 1;
require(_rosterIndex < 4294967295);
md5TokenToRosterIndex[_md5Tokens[i]] = uint32(_rosterIndex);
}
}
}
function setMetadata(uint128 _md5Token, string _metadata) public onlyCommissioner {
uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token];
if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) {
realWorldPlayers[_rosterIndex].metadata = _metadata;
}
}
function getMetadata(uint128 _md5Token) public view returns (string metadata) {
uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token];
if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) {
metadata = realWorldPlayers[_rosterIndex].metadata;
} else {
metadata = "";
}
}
function removeRealWorldPlayer(uint128 _md5Token) public onlyCommissioner onlyUnderDevelopment {
for (uint32 i = 0; i < uint32(realWorldPlayers.length); i++) {
RealWorldPlayer memory player = realWorldPlayers[i];
if (player.md5Token == _md5Token) {
uint32 stopAt = uint32(realWorldPlayers.length - 1);
for (uint32 j = i; j < stopAt; j++){
realWorldPlayers[j] = realWorldPlayers[j+1];
md5TokenToRosterIndex[realWorldPlayers[j].md5Token] = j;
}
delete realWorldPlayers[realWorldPlayers.length-1];
realWorldPlayers.length--;
break;
}
}
}
function hasOpenCommissionerAuction(uint128 _md5Token) public view onlyCommissioner returns (bool) {
uint128 _rosterIndex = this.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
revert();
} else {
return realWorldPlayers[_rosterIndex].hasActiveCommissionerAuction;
}
}
function getRealWorldPlayerRosterIndex(uint128 _md5Token) public view returns (uint128) {
uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token];
if (_rosterIndex == 0) {
if ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token)) {
return uint128(0);
}
} else {
return uint128(_rosterIndex);
}
return uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
function enableRealWorldPlayerMinting(uint128[] _md5Tokens, bool[] _mintingEnabled) public onlyCommissioner {
if (_md5Tokens.length != _mintingEnabled.length) {
revert();
}
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint32 _rosterIndex = md5TokenToRosterIndex[_md5Tokens[i]];
if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Tokens[i]))) {
realWorldPlayers[_rosterIndex].mintingEnabled = _mintingEnabled[i];
} else {
revert();
}
}
}
function isRealWorldPlayerMintingEnabled(uint128 _md5Token) public view returns (bool) {
uint32 _rosterIndex = md5TokenToRosterIndex[_md5Token];
if ((_rosterIndex > 0) || ((realWorldPlayers.length > 0) && (realWorldPlayers[0].md5Token == _md5Token))) {
return realWorldPlayers[_rosterIndex].mintingEnabled;
} else {
revert();
}
}
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCoreContract {
require(_rosterIndex < realWorldPlayers.length);
RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex];
_realWorldPlayer.prevCommissionerSalePrice = _prevCommissionerSalePrice;
_realWorldPlayer.lastMintedTime = _lastMintedTime;
_realWorldPlayer.mintedCount = _mintedCount;
_realWorldPlayer.hasActiveCommissionerAuction = _hasActiveCommissionerAuction;
_realWorldPlayer.mintingEnabled = _mintingEnabled;
}
function setHasCommissionerAuction(uint32 _rosterIndex) public onlyCoreContract {
require(_rosterIndex < realWorldPlayers.length);
RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex];
require(!_realWorldPlayer.hasActiveCommissionerAuction);
_realWorldPlayer.hasActiveCommissionerAuction = true;
}
function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) public onlyCoreContract {
require(_rosterIndex < realWorldPlayers.length);
RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex];
require(_realWorldPlayer.hasActiveCommissionerAuction);
if (_realWorldPlayer.prevCommissionerSalePrice == 0) {
_realWorldPlayer.prevCommissionerSalePrice = _price;
} else {
_realWorldPlayer.prevCommissionerSalePrice = (_realWorldPlayer.prevCommissionerSalePrice + _price)/2;
}
_realWorldPlayer.hasActiveCommissionerAuction = false;
if (_realWorldPlayer.mintingEnabled) {
uint128[] memory _md5Tokens = new uint128[](1);
_md5Tokens[0] = _realWorldPlayer.md5Token;
minterContract.mintPlayers(_md5Tokens, 0, 0, 0);
}
}
function commissionerAuctionCancelled(uint32 _rosterIndex) public view onlyCoreContract {
require(_rosterIndex < realWorldPlayers.length);
RealWorldPlayer storage _realWorldPlayer = realWorldPlayers[_rosterIndex];
require(_realWorldPlayer.hasActiveCommissionerAuction);
}
} | 0 |
pragma solidity ^0.4.18;
contract Utils {
function Utils() public {
}
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IOwned {
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
function Owned() public {
owner = msg.sender;
}
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract IERC20Token {
function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is IERC20Token, Utils {
string public standard = 'Token 0.1';
string public name = '';
string public symbol = '';
uint8 public decimals = 0;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function ERC20Token(string _name, string _symbol, uint8 _decimals) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0);
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddress(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
contract TokenHolder is ITokenHolder, Owned, Utils {
function TokenHolder() public {
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract SmartToken is ISmartToken, Owned, ERC20Token, TokenHolder {
string public version = '0.3';
bool public transfersEnabled = true;
event NewSmartToken(address _token);
event Issuance(uint256 _amount);
event Destruction(uint256 _amount);
function SmartToken(string _name, string _symbol, uint8 _decimals)
public
ERC20Token(_name, _symbol, _decimals)
{
NewSmartToken(address(this));
}
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
Issuance(_amount);
Transfer(this, _to, _amount);
}
function destroy(address _from, uint256 _amount) public {
require(msg.sender == _from || msg.sender == owner);
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
Transfer(_from, this, _amount);
Destruction(_amount);
}
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
return true;
}
} | 1 |
pragma solidity ^0.4.17;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract SafeBasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SafeStandardToken is ERC20, SafeBasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract SCToken is SafeStandardToken{
string public constant name = "SC Token";
string public constant symbol = "SC";
uint256 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1800000000 * (10 ** uint256(decimals));
function SCToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30240000
;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x10AAadC6c39783776fa6c40F95a816578f42827A ;
}
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 = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xa5ca09A4d59aE6a8e2Ab3b83E1294D1D4e00787d ;
}
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 = 28512000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x527BBEB7A709BC7B506725B89680486DB5f4C5fD;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function 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(_a >= _b);
return _a - _b;
}
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function setOwner(address _owner) onlyOwner public {
owner = _owner;
}
}
interface ERC20Token {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function decimals() external view returns (uint8 _decimals);
function totalSupply() external view returns (uint256 _totalSupply);
function balanceOf(address _owner) external view returns (uint256 _balance);
function transfer(address _to, uint256 _value) external returns (bool _success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool _success);
function approve(address _spender, uint256 _value) external returns (bool _success);
function allowance(address _owner, address _spender) external view returns (uint256 _remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract FinPro is Ownable {
using SafeMath for uint256;
string private constant name = "FinPro";
string private constant version = "v0.96";
uint256[] private fplowerlim;
uint256[] private fplocktime;
uint256[] private fpinterest;
uint256 private fpcount;
ERC20Token private token;
struct investedData {
uint256 fpnum;
uint256 buytime;
uint256 unlocktime;
uint256 value;
bool withdrawn;
}
mapping (address => uint256) private investedAmount;
mapping (address => mapping (uint256 => investedData)) private investorVault;
address[] public admins;
mapping (address => bool) public isAdmin;
mapping (address => mapping (uint256 => mapping (address => mapping (address => bool)))) public adminWithdraw;
mapping (address => mapping (uint256 => mapping (address => bool))) public adminTokenWithdraw;
event FPBought(address _buyer, uint256 _amount, uint256 _investednum,
uint256 _fpnum, uint256 _buytime, uint256 _unlocktime, uint256 _interestrate);
event FPWithdrawn(address _investor, uint256 _amount, uint256 _investednum, uint256 _fpnum);
event FPWithdrawnByAdmins(address indexed _addr, uint256 _amount, address indexed _investor, uint256 _investednum, uint256 _fpnum);
event TokenWithdrawnByAdmins(address indexed _addr, uint256 _amount);
event WrongTokenEmptied(address indexed _token, address indexed _addr, uint256 _amount);
event WrongEtherEmptied(address indexed _addr, uint256 _amount);
constructor (address _tokenAddress, uint256[] _fplowerlim, uint256[] _fplocktime, uint256[] _fpinterest, address[] _admins) public {
require(_fplowerlim.length == _fplocktime.length && _fplocktime.length == _fpinterest.length && _fpinterest.length > 0);
fplowerlim = _fplowerlim;
fplocktime = _fplocktime;
fpinterest = _fpinterest;
fpcount = fplowerlim.length;
token = ERC20Token(_tokenAddress);
admins = _admins;
for (uint256 i = 0; i < admins.length; i++) {
isAdmin[admins[i]] = true;
}
}
modifier onlyAdmin() {
require(isAdmin[msg.sender]);
_;
}
function tokenInfo() public view returns (address _tokenAddress, uint8 _decimals,
string _name, string _symbol, uint256 _tokenBalance) {
return (address(token), token.decimals(), token.name(), token.symbol(), token.balanceOf(address(this)));
}
function showFPCount() public view returns (uint256) {
return fplowerlim.length;
}
function showFPLowerlim() public view returns (uint256[]) {
return fplowerlim;
}
function showFPLocktime() public view returns (uint256[]) {
return fplocktime;
}
function showFPInterest() public view returns (uint256[]) {
return fpinterest;
}
function showFPInfoAll() public view returns (uint256[] _fplowerlim, uint256[] _fplocktime, uint256[] _fpinterest) {
return (fplowerlim, fplocktime, fpinterest);
}
function showInvestedNum(address _addr) public view returns (uint256) {
return investedAmount[_addr];
}
function showInvestorVault(address _addr, uint256 _investednum) public view
returns (uint256 _fpnum, uint256 _buytime, uint256 _unlocktime, uint256 _value, bool _withdrawn, bool _withdrawable) {
require(_investednum > 0 && investedAmount[_addr] >= _investednum);
return (investorVault[_addr][_investednum].fpnum, investorVault[_addr][_investednum].buytime,
investorVault[_addr][_investednum].unlocktime, investorVault[_addr][_investednum].value,
investorVault[_addr][_investednum].withdrawn,
(now > investorVault[_addr][_investednum].unlocktime && !investorVault[_addr][_investednum].withdrawn));
}
function showInvestorVaultFull(address _addr) external view
returns (uint256[] _fpnum, uint256[] _buytime, uint256[] _unlocktime, uint256[] _value,
uint256[] _interestrate, bool[] _withdrawn, bool[] _withdrawable) {
require(investedAmount[_addr] > 0);
_fpnum = new uint256[](investedAmount[_addr]);
_buytime = new uint256[](investedAmount[_addr]);
_unlocktime = new uint256[](investedAmount[_addr]);
_value = new uint256[](investedAmount[_addr]);
_interestrate = new uint256[](investedAmount[_addr]);
_withdrawn = new bool[](investedAmount[_addr]);
_withdrawable = new bool[](investedAmount[_addr]);
for(uint256 i = 0; i < investedAmount[_addr]; i++) {
(_fpnum[i], _buytime[i], _unlocktime[i], _value[i], _withdrawn[i], _withdrawable[i]) = showInvestorVault(_addr, i + 1);
_interestrate[i] = fpinterest[_fpnum[i]];
}
return (_fpnum, _buytime, _unlocktime, _value, _interestrate, _withdrawn, _withdrawable);
}
function buyfp(uint256 _fpnum, uint256 _amount) public {
require(_fpnum < fpcount);
require(_amount >= fplowerlim[_fpnum]);
require(token.transferFrom(msg.sender, address(this), _amount));
investedAmount[msg.sender]++;
investorVault[msg.sender][investedAmount[msg.sender]] = investedData({fpnum: _fpnum, buytime: now,
unlocktime: now.add(fplocktime[_fpnum]), value: _amount, withdrawn: false});
emit FPBought(msg.sender, _amount, investedAmount[msg.sender], _fpnum, now, now.add(fplocktime[_fpnum]), fpinterest[_fpnum]);
}
function withdraw(uint256 _investednum) public {
require(_investednum > 0 && investedAmount[msg.sender] >= _investednum);
require(!investorVault[msg.sender][_investednum].withdrawn);
require(now > investorVault[msg.sender][_investednum].unlocktime);
require(token.balanceOf(address(this)) >= investorVault[msg.sender][_investednum].value);
require(token.transfer(msg.sender, investorVault[msg.sender][_investednum].value));
investorVault[msg.sender][_investednum].withdrawn = true;
emit FPWithdrawn(msg.sender, investorVault[msg.sender][_investednum].value,
_investednum, investorVault[msg.sender][_investednum].fpnum);
}
function withdrawByAdmin(address _investor, uint256 _investednum, address _target) onlyAdmin public {
require(_investednum > 0 && investedAmount[_investor] >= _investednum);
require(!investorVault[_investor][_investednum].withdrawn);
require(token.balanceOf(address(this)) >= investorVault[_investor][_investednum].value);
adminWithdraw[_investor][_investednum][_target][msg.sender] = true;
for (uint256 i = 0; i < admins.length; i++) {
if (!adminWithdraw[_investor][_investednum][_target][admins[i]]) {
return;
}
}
require(token.transfer(_target, investorVault[_investor][_investednum].value));
investorVault[_investor][_investednum].withdrawn = true;
emit FPWithdrawnByAdmins(_target, investorVault[_investor][_investednum].value, _investor,
_investednum, investorVault[_investor][_investednum].fpnum);
}
function withdrawTokenByAdmin(address _target, uint256 _amount) onlyAdmin public {
adminTokenWithdraw[_target][_amount][msg.sender] = true;
uint256 i;
for (i = 0; i < admins.length; i++) {
if (!adminTokenWithdraw[_target][_amount][admins[i]]) {
return;
}
}
for (i = 0; i < admins.length; i++) {
adminTokenWithdraw[_target][_amount][admins[i]] = false;
}
require(token.transfer(_target, _amount));
emit TokenWithdrawnByAdmins(_target, _amount);
}
function () public payable {
revert();
}
function emptyWrongToken(address _addr) onlyOwner public {
require(_addr != address(token));
ERC20Token wrongToken = ERC20Token(_addr);
uint256 amount = wrongToken.balanceOf(address(this));
require(amount > 0);
require(wrongToken.transfer(msg.sender, amount));
emit WrongTokenEmptied(_addr, msg.sender, amount);
}
function emptyWrongEther() onlyOwner public {
uint256 amount = address(this).balance;
require(amount > 0);
msg.sender.transfer(amount);
emit WrongEtherEmptied(msg.sender, amount);
}
} | 0 |
pragma solidity ^0.4.23;
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 BitBoscoin is StandardToken {
string public constant name = "BitBoscoin";
string public constant symbol = "BOSS";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 30000000 * (10 ** uint256(decimals));
function BitBoscoin() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 |
pragma solidity ^0.4.4;
contract Ownable {
address owner;
address ownerMoney;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ownerMoney = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferMoney(address _add) public onlyOwner {
if (_add != address(0)) {
ownerMoney = _add;
}
}
function transferOwner(address _add) public onlyOwner {
if (_add != address(0)) {
owner = _add;
}
}
function getOwnerMoney() public view onlyOwner returns(address) {
return ownerMoney;
}
}
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
constructor() public {
addAddressToWhitelist(msg.sender);
}
function addAddressToWhitelist(address addr) public onlyOwner returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
function getInWhitelist(address addr) public view returns(bool) {
return whitelist[addr];
}
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint 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 PublicInterface {
function transferFrom(address _from, address _to, uint32 _tokenId) public returns (bool);
function ownerOf(uint32 _tokenId) public view returns (address owner);
function isUIntPublic() public view returns(bool);
function getRabbitMother( uint32 mother) public view returns(uint32[5]);
function getRabbitMotherSumm(uint32 mother) public view returns(uint count);
}
contract Market is Whitelist {
using SafeMath for uint256;
event StopMarket(uint32 bunnyId);
event StartMarket(uint32 bunnyId, uint money, uint timeStart, uint stepTimeSale);
event BunnyBuy(uint32 bunnyId, uint money);
event Tournament(address who, uint bank, uint timeLeft, uint timeRange);
event AddBank(uint bankMoney, uint countInvestor, address lastOwner, uint addTime, uint stepTime);
event MotherMoney(uint32 motherId, uint32 bunnyId, uint money);
bool public pause = false;
uint stepTimeBank = 50*60;
uint stepTimeSale = (stepTimeBank/10)+stepTimeBank;
uint minPrice = 0.001 ether;
uint reallyPrice = 0.001 ether;
uint rangePrice = 2;
uint minTimeBank = 300;
uint coefficientTimeStep = 5;
uint public commission = 5;
uint public commission_mom = 5;
uint public percentBank = 10;
uint added_to_the_bank = 0;
uint marketCount = 0;
uint numberOfWins = 0;
uint getMoneyCount = 0;
string public advertising = "Your advertisement here!";
uint sec = 1;
uint lastmoney = 0;
uint totalClosedBID = 0;
mapping (uint32 => uint) public bunnyCost;
mapping (uint32 => uint) public timeCost;
address public lastOwner;
uint bankMoney;
uint lastSaleTime;
address public pubAddress;
PublicInterface publicContract;
function getProperty() public view
returns(
uint tmp_stepTimeBank,
uint tmp_stepTimeSale,
uint tmp_minPrice,
uint tmp_reallyPrice,
uint tmp_added_to_the_bank,
uint tmp_marketCount,
uint tmp_numberOfWins,
uint tmp_getMoneyCount,
uint tmp_lastmoney,
uint tmp_totalClosedBID,
uint tmp_bankMoney,
uint tmp_lastSaleTime
)
{
tmp_stepTimeBank = stepTimeBank;
tmp_stepTimeSale = stepTimeSale;
tmp_minPrice = minPrice;
tmp_reallyPrice = reallyPrice;
tmp_added_to_the_bank = added_to_the_bank;
tmp_marketCount = marketCount;
tmp_numberOfWins = numberOfWins;
tmp_getMoneyCount = getMoneyCount;
tmp_lastmoney = lastmoney;
tmp_totalClosedBID = totalClosedBID;
tmp_bankMoney = bankMoney;
tmp_lastSaleTime = lastSaleTime;
}
constructor() public {
transferContract(0x434f0DCF2fE5Cb51d888850e7C77C4551725F2Ff);
}
function setRangePrice(uint _rangePrice) public onlyWhitelisted {
require(_rangePrice > 0);
rangePrice = _rangePrice;
}
function setMinTimeBank(uint _minTimeBank) public onlyWhitelisted {
require(_minTimeBank > 0);
minTimeBank = _minTimeBank;
}
function setCoefficientTimeStep(uint _coefficientTimeStep) public onlyWhitelisted {
require(_coefficientTimeStep > 0);
coefficientTimeStep = _coefficientTimeStep;
}
function setPercentCommission(uint _commission) public onlyWhitelisted {
require(_commission > 0);
commission = _commission;
}
function setPercentBank(uint _percentBank) public onlyWhitelisted {
require(_percentBank > 0);
percentBank = _percentBank;
}
function setMinPrice(uint _minPrice) public onlyWhitelisted {
require(_minPrice > (10**15));
minPrice = _minPrice;
}
function setStepTime(uint _stepTimeBank) public onlyWhitelisted {
require(_stepTimeBank > 0);
stepTimeBank = _stepTimeBank;
stepTimeSale = _stepTimeBank+1;
}
function transferContract(address _pubAddress) public onlyWhitelisted {
require(_pubAddress != address(0));
pubAddress = _pubAddress;
publicContract = PublicInterface(_pubAddress);
}
function setPause() public onlyWhitelisted {
pause = !pause;
}
function isPauseSave() public view returns(bool){
return !pause;
}
function currentPrice(uint32 _bunnyid) public view returns(uint) {
uint money = bunnyCost[_bunnyid];
if (money > 0) {
uint percOne = money.div(100);
uint commissionMoney = percOne.mul(commission);
money = money.add(commissionMoney);
uint commissionMom = percOne.mul(commission_mom);
money = money.add(commissionMom);
uint percBank = percOne.mul(percentBank);
money = money.add(percBank);
return money;
}
}
function startMarket(uint32 _bunnyId, uint _money) public returns (uint) {
require(checkContract());
require(isPauseSave());
require(_money >= reallyPrice);
require(publicContract.ownerOf(_bunnyId) == msg.sender);
bunnyCost[_bunnyId] = _money;
timeCost[_bunnyId] = block.timestamp;
emit StartMarket(_bunnyId, currentPrice(_bunnyId), block.timestamp, stepTimeSale);
return marketCount++;
}
function stopMarket(uint32 _bunnyId) public returns(uint) {
require(checkContract());
require(isPauseSave());
require(publicContract.ownerOf(_bunnyId) == msg.sender);
bunnyCost[_bunnyId] = 0;
emit StopMarket(_bunnyId);
return marketCount--;
}
function changeReallyPrice() internal {
if (added_to_the_bank > 0 && rangePrice > 0) {
uint tmp = added_to_the_bank.div(rangePrice);
reallyPrice = tmp * (10**15)+reallyPrice;
uint tmpTime = added_to_the_bank.div(coefficientTimeStep);
if (tmpTime <= minTimeBank) {
stepTimeBank = minTimeBank;
} else {
stepTimeBank = tmpTime;
}
}
}
function timeBunny(uint32 _bunnyId) public view returns(bool can, uint timeleft) {
uint _tmp = timeCost[_bunnyId].add(stepTimeSale);
if (timeCost[_bunnyId] > 0 && block.timestamp >= _tmp) {
can = true;
timeleft = 0;
} else {
can = false;
_tmp = _tmp.sub(block.timestamp);
if (_tmp > 0) {
timeleft = _tmp;
} else {
timeleft = 0;
}
}
}
function transferFromBunny(uint32 _bunnyId) public {
require(checkContract());
publicContract.transferFrom(publicContract.ownerOf(_bunnyId), msg.sender, _bunnyId);
}
function buyBunny(uint32 _bunnyId) public payable {
require(isPauseSave());
require(checkContract());
require(publicContract.ownerOf(_bunnyId) != msg.sender);
lastmoney = currentPrice(_bunnyId);
require(msg.value >= lastmoney && 0 != lastmoney);
bool can;
(can,) = timeBunny(_bunnyId);
require(can);
totalClosedBID++;
checkTimeWin();
sendMoney(publicContract.ownerOf(_bunnyId), lastmoney);
publicContract.transferFrom(publicContract.ownerOf(_bunnyId), msg.sender, _bunnyId);
sendMoneyMother(_bunnyId);
stopMarket(_bunnyId);
changeReallyPrice();
lastOwner = msg.sender;
lastSaleTime = block.timestamp;
emit BunnyBuy(_bunnyId, lastmoney);
}
function sendMoneyMother(uint32 _bunnyId) internal {
if (bunnyCost[_bunnyId] > 0) {
uint procentOne = (bunnyCost[_bunnyId].div(100));
uint32[5] memory mother;
mother = publicContract.getRabbitMother(_bunnyId);
uint motherCount = publicContract.getRabbitMotherSumm(_bunnyId);
if (motherCount > 0) {
uint motherMoney = (procentOne*commission_mom).div(motherCount);
for (uint m = 0; m < 5; m++) {
if (mother[m] != 0) {
publicContract.ownerOf(mother[m]).transfer(motherMoney);
emit MotherMoney(mother[m], _bunnyId, motherMoney);
}
}
}
}
}
function sendMoney(address _to, uint256 _money) internal {
if (_money > 0) {
uint procentOne = (_money/100);
_to.transfer(procentOne * (100-(commission+percentBank+commission_mom)));
addBank(procentOne*percentBank);
ownerMoney.transfer(procentOne*commission);
}
}
function checkTimeWin() internal {
if (lastSaleTime + stepTimeBank < block.timestamp) {
win();
}
lastSaleTime = block.timestamp;
}
function win() internal {
if (address(this).balance > 0 && address(this).balance >= bankMoney && lastOwner != address(0)) {
advertising = "";
added_to_the_bank = 0;
reallyPrice = minPrice;
lastOwner.transfer(bankMoney);
numberOfWins = numberOfWins.add(1);
emit Tournament (lastOwner, bankMoney, lastSaleTime, block.timestamp);
bankMoney = 0;
}
}
function addBank(uint _money) internal {
bankMoney = bankMoney.add(_money);
added_to_the_bank = added_to_the_bank.add(1);
emit AddBank(bankMoney, added_to_the_bank, lastOwner, block.timestamp, stepTimeBank);
}
function ownerOf(uint32 _bunnyId) public view returns(address) {
return publicContract.ownerOf(_bunnyId);
}
function checkContract() public view returns(bool) {
return publicContract.isUIntPublic();
}
function buyAdvert(string _text) public payable {
require(msg.value > (reallyPrice*2));
require(checkContract());
advertising = _text;
addBank(msg.value);
}
function noAdvert() public onlyWhitelisted {
advertising = "";
}
function getMoney(uint _value) public onlyOwner {
require(address(this).balance >= _value);
ownerMoney.transfer(_value);
getMoneyCount = getMoneyCount.add(_value);
}
} | 0 |
pragma solidity ^0.4.3;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Sender not authorised.");
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public 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 ERC677 is ERC20 {
function transferAndCall(address to, uint value, bytes data) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
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;
}
}
library itmap {
struct entry {
uint keyIndex;
uint value;
}
struct itmap {
mapping(uint => entry) data;
uint[] keys;
}
function insert(itmap storage self, uint key, uint value) internal returns (bool replaced) {
entry storage e = self.data[key];
e.value = value;
if (e.keyIndex > 0) {
return true;
} else {
e.keyIndex = ++self.keys.length;
self.keys[e.keyIndex - 1] = key;
return false;
}
}
function remove(itmap storage self, uint key) internal returns (bool success) {
entry storage e = self.data[key];
if (e.keyIndex == 0)
return false;
if (e.keyIndex < self.keys.length) {
self.data[self.keys[self.keys.length - 1]].keyIndex = e.keyIndex;
self.keys[e.keyIndex - 1] = self.keys[self.keys.length - 1];
self.keys.length -= 1;
delete self.data[key];
return true;
}
}
function contains(itmap storage self, uint key) internal view returns (bool exists) {
return self.data[key].keyIndex > 0;
}
function size(itmap storage self) internal view returns (uint) {
return self.keys.length;
}
function get(itmap storage self, uint key) internal view returns (uint) {
return self.data[key].value;
}
function getKey(itmap storage self, uint idx) internal view returns (uint) {
return self.keys[idx];
}
}
contract PoolOwners is Ownable {
using SafeMath for uint256;
using itmap for itmap.itmap;
struct Owner {
uint256 key;
uint256 percentage;
uint256 shareTokens;
mapping(address => uint256) balance;
}
mapping(address => Owner) public owners;
struct Distribution {
address token;
uint256 amount;
uint256 owners;
uint256 claimed;
mapping(address => bool) claimedAddresses;
}
mapping(uint256 => Distribution) public distributions;
mapping(address => uint256) public tokenBalance;
mapping(address => uint256) public totalReturned;
mapping(address => bool) private whitelist;
itmap.itmap ownerMap;
uint256 public totalContributed = 0;
uint256 public totalOwners = 0;
uint256 public totalDistributions = 0;
bool public distributionActive = false;
uint256 public distributionMinimum = 20 ether;
uint256 public precisionMinimum = 0.04 ether;
bool public locked = false;
address public wallet;
bool private contributionStarted = false;
uint256 private valuation = 4000 ether;
uint256 private hardCap = 996.96 ether;
event Contribution(address indexed sender, uint256 share, uint256 amount);
event ClaimedTokens(address indexed owner, address indexed token, uint256 amount, uint256 claimedStakers, uint256 distributionId);
event TokenDistributionActive(address indexed token, uint256 amount, uint256 distributionId, uint256 amountOfOwners);
event TokenWithdrawal(address indexed token, address indexed owner, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner, uint256 amount);
event TokenDistributionComplete(address indexed token, uint256 amountOfOwners);
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
function() public payable {
require(contributionStarted, "Contribution phase hasn't started");
require(whitelist[msg.sender], "You are not whitelisted");
contribute(msg.sender, msg.value);
wallet.transfer(msg.value);
}
function setContribution(address _sender, uint256 _amount) public onlyOwner() { contribute(_sender, _amount); }
function contribute(address _sender, uint256 _amount) private {
require(!locked, "Crowdsale period over, contribution is locked");
require(!distributionActive, "Cannot contribute when distribution is active");
require(_amount >= precisionMinimum, "Amount needs to be above the minimum contribution");
require(hardCap >= _amount, "Your contribution is greater than the hard cap");
require(_amount % precisionMinimum == 0, "Your amount isn't divisible by the minimum precision");
require(hardCap >= totalContributed.add(_amount), "Your contribution would cause the total to exceed the hardcap");
totalContributed = totalContributed.add(_amount);
uint256 share = percent(_amount, valuation, 5);
Owner storage o = owners[_sender];
if (o.percentage != 0) {
o.shareTokens = o.shareTokens.add(_amount);
o.percentage = o.percentage.add(share);
} else {
require(ownerMap.insert(totalOwners, uint(_sender)) == false);
o.key = totalOwners;
totalOwners += 1;
o.shareTokens = _amount;
o.percentage = share;
}
if (!whitelist[msg.sender]) {
whitelist[msg.sender] = true;
}
emit Contribution(_sender, share, _amount);
}
function whitelistWallet(address _owner) external onlyOwner() {
require(!locked, "Can't whitelist when the contract is locked");
require(_owner != address(0), "Empty address");
whitelist[_owner] = true;
}
function startContribution() external onlyOwner() {
require(!contributionStarted, "Contribution has started");
contributionStarted = true;
}
function setOwnerShare(address _owner, uint256 _value) public onlyOwner() {
require(!locked, "Can't manually set shares, it's locked");
require(!distributionActive, "Cannot set owners share when distribution is active");
Owner storage o = owners[_owner];
if (o.shareTokens == 0) {
whitelist[_owner] = true;
ownerMap.insert(totalOwners, uint(_owner));
totalOwners += 1;
}
o.shareTokens = _value;
o.percentage = percent(_value, valuation, 5);
}
function sendOwnership(address _receiver, uint256 _amount) public onlyWhitelisted() {
Owner storage o = owners[msg.sender];
Owner storage r = owners[_receiver];
require(o.shareTokens > 0, "You don't have any ownership");
require(o.shareTokens >= _amount, "The amount exceeds what you have");
require(!distributionActive, "Distribution cannot be active when sending ownership");
require(_amount % precisionMinimum == 0, "Your amount isn't divisible by the minimum precision amount");
o.shareTokens = o.shareTokens.sub(_amount);
if (o.shareTokens == 0) {
o.percentage = 0;
require(ownerMap.remove(o.key) == true);
} else {
o.percentage = percent(o.shareTokens, valuation, 5);
}
if (r.shareTokens == 0) {
whitelist[_receiver] = true;
require(ownerMap.insert(totalOwners, uint(_receiver)) == false);
totalOwners += 1;
}
r.shareTokens = r.shareTokens.add(_amount);
r.percentage = r.percentage.add(percent(_amount, valuation, 5));
emit OwnershipTransferred(msg.sender, _receiver, _amount);
}
function lockShares() public onlyOwner() {
require(!locked, "Shares already locked");
locked = true;
}
function distributeTokens(address _token) public onlyWhitelisted() {
require(!distributionActive, "Distribution is already active");
distributionActive = true;
ERC677 erc677 = ERC677(_token);
uint256 currentBalance = erc677.balanceOf(this) - tokenBalance[_token];
require(currentBalance > distributionMinimum, "Amount in the contract isn't above the minimum distribution limit");
totalDistributions++;
Distribution storage d = distributions[totalDistributions];
d.owners = ownerMap.size();
d.amount = currentBalance;
d.token = _token;
d.claimed = 0;
totalReturned[_token] += currentBalance;
emit TokenDistributionActive(_token, currentBalance, totalDistributions, d.owners);
}
function claimTokens(address _owner) public {
Owner storage o = owners[_owner];
Distribution storage d = distributions[totalDistributions];
require(o.shareTokens > 0, "You need to have a share to claim tokens");
require(distributionActive, "Distribution isn't active");
require(!d.claimedAddresses[_owner], "Tokens already claimed for this address");
address token = d.token;
uint256 tokenAmount = d.amount.mul(o.percentage).div(100000);
o.balance[token] = o.balance[token].add(tokenAmount);
tokenBalance[token] = tokenBalance[token].add(tokenAmount);
d.claimed++;
d.claimedAddresses[_owner] = true;
emit ClaimedTokens(_owner, token, tokenAmount, d.claimed, totalDistributions);
if (d.claimed == d.owners) {
distributionActive = false;
emit TokenDistributionComplete(token, totalOwners);
}
}
function withdrawTokens(address _token, uint256 _amount) public {
require(_amount > 0, "You have requested for 0 tokens to be withdrawn");
Owner storage o = owners[msg.sender];
Distribution storage d = distributions[totalDistributions];
if (distributionActive && !d.claimedAddresses[msg.sender]) {
claimTokens(msg.sender);
}
require(o.balance[_token] >= _amount, "Amount requested is higher than your balance");
o.balance[_token] = o.balance[_token].sub(_amount);
tokenBalance[_token] = tokenBalance[_token].sub(_amount);
ERC677 erc677 = ERC677(_token);
require(erc677.transfer(msg.sender, _amount) == true);
emit TokenWithdrawal(_token, msg.sender, _amount);
}
function setDistributionMinimum(uint256 _minimum) public onlyOwner() {
distributionMinimum = _minimum;
}
function setEthWallet(address _wallet) public onlyOwner() {
wallet = _wallet;
}
function isWhitelisted(address _owner) public view returns (bool) {
return whitelist[_owner];
}
function getOwnerBalance(address _token) public view returns (uint256) {
Owner storage o = owners[msg.sender];
return o.balance[_token];
}
function getOwner(address _owner) public view returns (uint256, uint256, uint256) {
Owner storage o = owners[_owner];
return (o.key, o.shareTokens, o.percentage);
}
function getCurrentOwners() public view returns (uint) {
return ownerMap.size();
}
function getOwnerAddress(uint _key) public view returns (address) {
return address(ownerMap.get(_key));
}
function hasClaimed(address _owner, uint256 _dId) public view returns (bool) {
Distribution storage d = distributions[_dId];
return d.claimedAddresses[_owner];
}
function percent(uint numerator, uint denominator, uint precision) private 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 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 ReentrancyGuard {
uint256 private _guardCounter;
constructor() internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
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 CanReclaimToken is Ownable {
function reclaimToken(IERC20 token) external onlyOwner {
if (address(token) == address(0)) {
owner().transfer(address(this).balance);
return;
}
uint256 balance = token.balanceOf(this);
token.transfer(owner(), balance);
}
}
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 ServiceRole {
using Roles for Roles.Role;
event ServiceAdded(address indexed account);
event ServiceRemoved(address indexed account);
Roles.Role private services;
constructor() internal {
_addService(msg.sender);
}
modifier onlyService() {
require(isService(msg.sender));
_;
}
function isService(address account) public view returns (bool) {
return services.has(account);
}
function renounceService() public {
_removeService(msg.sender);
}
function _addService(address account) internal {
services.add(account);
emit ServiceAdded(account);
}
function _removeService(address account) internal {
services.remove(account);
emit ServiceRemoved(account);
}
}
interface HEROES {
function getLevel(uint256 tokenId) external view returns (uint256);
function getGenes(uint256 tokenId) external view returns (uint256);
function getRace(uint256 tokenId) external view returns (uint256);
function lock(uint256 tokenId, uint256 lockedTo, bool onlyFreeze) external returns (bool);
function unlock(uint256 tokenId) external returns (bool);
function ownerOf(uint256 tokenId) external view returns (address);
function addWin(uint256 tokenId, uint winsCount, uint levelUp) external returns (bool);
function addLoss(uint256 tokenId, uint256 lossesCount, uint levelDown) external returns (bool);
}
interface CHR {
function burn(address _from, uint256 _amount) external returns (bool);
}
contract Fights is Ownable, ServiceRole, ReentrancyGuard, CanReclaimToken {
using SafeMath for uint256;
event SetFightInterval(uint startsFrom, uint pastFightsCount, uint fightsInterval, uint fightPeriod, uint applicationPeriod, uint betsPeriod);
event EnterArena(uint tokenId, uint fightId, uint startsAt, uint level, uint enemyRace);
event ChangeEnemy(uint tokenId, uint fightId, uint enemyRace);
event LeaveArena(uint tokenId, uint fightId, Result result, uint level);
event StartFight(uint fightId, uint startAt);
event RemoveFight(uint fightId);
event FightResult(uint fightId, uint[] races, uint[] values);
event FinishFight(uint fightId, uint startedAt, uint finishedAt, uint startCheckedAt, uint finishCheckedAt);
HEROES public heroes;
CHR public coin;
enum Result {QUAIL, WIN, LOSS, DRAW}
struct Fighter {
uint index;
bool exists;
uint race;
uint level;
uint enemyRace;
bool finished;
}
struct Race {
uint index;
bool exists;
uint count;
uint enemyCount;
uint levelSum;
mapping(uint => uint) levelCount;
int32 result;
}
struct Fight {
uint startedAt;
uint finishedAt;
uint startCheckedAt;
uint finishCheckedAt;
mapping(uint => uint) arena;
mapping(uint => Fighter) fighters;
uint fightersCount;
mapping(uint => Race) races;
mapping(uint => uint) raceList;
uint raceCount;
}
uint[] public fightsList;
mapping(uint => uint[]) public characterFights;
mapping(uint => Fight) fights;
struct FightInterval {
uint fightsInterval;
uint startsFrom;
uint fightsCount;
uint betsPeriod;
uint applicationPeriod;
uint fightPeriod;
}
FightInterval[] public intervalHistory;
uint public constant FightEpoch = 1542240000;
uint public minBetsLevel = 5;
bool public allowEnterDuringBets = true;
modifier onlyOwnerOf(uint256 _tokenId) {
require(heroes.ownerOf(_tokenId) == msg.sender);
_;
}
constructor(HEROES _heroes, CHR _coin) public {
require(address(_heroes) != address(0));
require(address(_coin) != address(0));
heroes = _heroes;
coin = _coin;
intervalHistory.push(FightInterval({
fightPeriod: 5 * 60 * 60,
startsFrom : FightEpoch,
fightsCount : 0,
fightsInterval : 12 * 60 * 60,
betsPeriod : 2 * 60 * 60,
applicationPeriod : 11 * 60 * 60
}));
}
function() external payable {
require(msg.value > 0);
address(heroes).transfer(msg.value);
}
function addService(address account) public onlyOwner {
_addService(account);
}
function removeService(address account) public onlyOwner {
_removeService(account);
}
function setFightInterval(uint _fightsInterval, uint _applicationPeriod, uint _betsPeriod, uint _fightPeriod) external onlyOwner {
FightInterval memory i = _getFightIntervalAt(now);
uint intervalsCount = (now - i.startsFrom) / i.fightsInterval + 1;
FightInterval memory ni = FightInterval({
fightsInterval : _fightsInterval,
startsFrom : i.startsFrom + i.fightsInterval * intervalsCount,
fightsCount : intervalsCount + i.fightsCount,
applicationPeriod : _applicationPeriod,
betsPeriod : _betsPeriod,
fightPeriod : _fightPeriod
});
intervalHistory.push(ni);
emit SetFightInterval(ni.startsFrom, ni.fightsCount, _fightsInterval, _fightPeriod, _applicationPeriod, _betsPeriod);
}
function setParameters(uint _minBetsLevel, bool _allowEnterDuringBets) external onlyOwner {
minBetsLevel = _minBetsLevel;
allowEnterDuringBets = _allowEnterDuringBets;
}
function enterArena(uint _tokenId, uint _enemyRace) public onlyOwnerOf(_tokenId) {
require(isAllowed(_tokenId));
uint intervalId = _getFightIntervalIdAt(now);
FightInterval memory i = intervalHistory[intervalId];
uint nextStartsAt = _getFightStartsAt(intervalId, 1);
require(now >= nextStartsAt - i.applicationPeriod);
require(now < nextStartsAt - (allowEnterDuringBets ? 0 : i.betsPeriod));
uint nextFightId = getFightId(intervalId, 1);
Fight storage f = fights[nextFightId];
require(!f.fighters[_tokenId].exists);
uint level = heroes.getLevel(_tokenId);
uint race = heroes.getRace(_tokenId);
require(race != _enemyRace);
if (f.startedAt == 0) {
f.startedAt = nextStartsAt;
fightsList.push(nextFightId);
emit StartFight(nextFightId, nextStartsAt);
}
f.fighters[_tokenId] = Fighter({
exists : true,
finished : false,
index : f.fightersCount,
race : race,
enemyRace : _enemyRace,
level: level
});
f.arena[f.fightersCount++] = _tokenId;
characterFights[_tokenId].push(nextFightId);
Race storage r = f.races[race];
if (!r.exists) {
r.exists = true;
r.index = f.raceCount;
f.raceList[f.raceCount++] = race;
}
r.count++;
if (level >= minBetsLevel) {
if (r.levelCount[level] == 0) {
r.levelSum = r.levelSum.add(level);
}
r.levelCount[level]++;
}
Race storage er = f.races[_enemyRace];
if (!er.exists) {
er.exists = true;
er.index = f.raceCount;
f.raceList[f.raceCount++] = _enemyRace;
}
er.enemyCount++;
require(heroes.lock(_tokenId, nextStartsAt + i.fightPeriod, false));
emit EnterArena(_tokenId, nextFightId, nextStartsAt, level, _enemyRace);
}
function changeEnemy(uint _tokenId, uint _enemyRace) public onlyOwnerOf(_tokenId) {
uint fightId = characterLastFightId(_tokenId);
require(fightId != 0);
Fight storage f = fights[fightId];
Fighter storage fr = f.fighters[_tokenId];
require(fr.exists);
require(!fr.finished);
require(fr.enemyRace != _enemyRace);
FightInterval memory i = _getFightIntervalAt(f.startedAt);
require(now >= f.startedAt - i.applicationPeriod && now < f.startedAt - i.betsPeriod && f.finishedAt != 0);
fr.enemyRace = _enemyRace;
Race storage er_old = f.races[fr.enemyRace];
er_old.enemyCount--;
if (er_old.count == 0 && er_old.enemyCount == 0) {
f.races[f.raceList[--f.raceCount]].index = er_old.index;
f.raceList[er_old.index] = f.raceList[f.raceCount];
delete f.arena[f.raceCount];
delete f.races[fr.enemyRace];
}
Race storage er_new = f.races[_enemyRace];
if (!er_new.exists) {
er_new.index = f.raceCount;
f.raceList[f.raceCount++] = _enemyRace;
}
er_new.enemyCount++;
emit ChangeEnemy(_tokenId, fightId, _enemyRace);
}
function reenterArena(uint _tokenId, uint _enemyRace, bool _useCoin) public onlyOwnerOf(_tokenId) {
uint fightId = characterLastFightId(_tokenId);
require(fightId != 0);
Fight storage f = fights[fightId];
Fighter storage fr = f.fighters[_tokenId];
require(fr.exists);
require(!fr.finished);
require(f.finishedAt != 0 && now > f.finishedAt);
Result result = Result.QUAIL;
if (f.races[f.fighters[_tokenId].race].result > f.races[f.fighters[_tokenId].enemyRace].result) {
result = Result.WIN;
heroes.addWin(_tokenId, 1, 1);
} else if (f.races[f.fighters[_tokenId].race].result < f.races[f.fighters[_tokenId].enemyRace].result) {
result = Result.LOSS;
if (_useCoin) {
require(coin.burn(heroes.ownerOf(_tokenId), 1));
heroes.addLoss(_tokenId, 1, 0);
} else {
heroes.addLoss(_tokenId, 1, 1);
}
} else {
}
fr.finished = true;
emit LeaveArena(_tokenId, fightId, result, fr.level);
enterArena(_tokenId, _enemyRace);
}
function leaveArena(uint _tokenId, bool _useCoin) public onlyOwnerOf(_tokenId) {
uint fightId = characterLastFightId(_tokenId);
require(fightId != 0);
Fight storage f = fights[fightId];
Fighter storage fr = f.fighters[_tokenId];
require(fr.exists);
require(!fr.finished);
FightInterval memory i = _getFightIntervalAt(f.startedAt);
require(now < f.startedAt - i.betsPeriod || (f.finishedAt != 0 && now > f.finishedAt));
Result result = Result.QUAIL;
if (f.finishedAt == 0) {
Race storage r = f.races[fr.race];
if (fr.level >= minBetsLevel) {
r.levelCount[fr.level]--;
if (r.levelCount[fr.level] == 0) {
r.levelSum = r.levelSum.sub(fr.level);
}
}
r.count--;
Race storage er = f.races[fr.enemyRace];
er.enemyCount--;
if (r.count == 0 && r.enemyCount == 0) {
f.races[f.raceList[--f.raceCount]].index = r.index;
f.raceList[r.index] = f.raceList[f.raceCount];
delete f.arena[f.raceCount];
delete f.races[fr.race];
}
if (er.count == 0 && er.enemyCount == 0) {
f.races[f.raceList[--f.raceCount]].index = er.index;
f.raceList[er.index] = f.raceList[f.raceCount];
delete f.arena[f.raceCount];
delete f.races[fr.enemyRace];
}
f.fighters[f.arena[--f.fightersCount]].index = fr.index;
f.arena[fr.index] = f.arena[f.fightersCount];
delete f.arena[f.fightersCount];
delete f.fighters[_tokenId];
delete characterFights[_tokenId][characterFights[_tokenId].length--];
if (f.fightersCount == 0) {
delete fights[fightId];
emit RemoveFight(fightId);
}
} else {
if (f.races[f.fighters[_tokenId].race].result > f.races[f.fighters[_tokenId].enemyRace].result) {
result = Result.WIN;
heroes.addWin(_tokenId, 1, 1);
} else if (f.races[f.fighters[_tokenId].race].result < f.races[f.fighters[_tokenId].enemyRace].result) {
result = Result.LOSS;
if (_useCoin) {
require(coin.burn(heroes.ownerOf(_tokenId), 1));
heroes.addLoss(_tokenId, 1, 0);
} else {
heroes.addLoss(_tokenId, 1, 1);
}
} else {
result = Result.DRAW;
}
fr.finished = true;
}
require(heroes.unlock(_tokenId));
emit LeaveArena(_tokenId, fightId, result, fr.level);
}
function fightsCount() public view returns (uint) {
return fightsList.length;
}
function getCurrentFightId() public view returns (uint) {
return getFightId(_getFightIntervalIdAt(now), 0);
}
function getNextFightId() public view returns (uint) {
return getFightId(_getFightIntervalIdAt(now), 1);
}
function getFightId(uint intervalId, uint nextShift) internal view returns (uint) {
FightInterval memory i = intervalHistory[intervalId];
return (now - i.startsFrom) / i.fightsInterval + i.fightsCount + nextShift;
}
function characterFightsCount(uint _tokenId) public view returns (uint) {
return characterFights[_tokenId].length;
}
function characterLastFightId(uint _tokenId) public view returns (uint) {
return characterFights[_tokenId].length > 0 ? characterFights[_tokenId][characterFights[_tokenId].length - 1] : 0;
}
function characterLastFight(uint _tokenId) public view returns (
uint index,
uint race,
uint level,
uint enemyRace,
bool finished
) {
return getFightFighter(characterLastFightId(_tokenId), _tokenId);
}
function getFightFighter(uint _fightId, uint _tokenId) public view returns (
uint index,
uint race,
uint level,
uint enemyRace,
bool finished
) {
Fighter memory fr = fights[_fightId].fighters[_tokenId];
return (fr.index, fr.race, fr.level, fr.enemyRace, fr.finished);
}
function getFightArenaFighter(uint _fightId, uint _fighterIndex) public view returns (
uint tokenId,
uint race,
uint level,
uint enemyRace,
bool finished
) {
uint _tokenId = fights[_fightId].arena[_fighterIndex];
Fighter memory fr = fights[_fightId].fighters[_tokenId];
return (_tokenId, fr.race, fr.level, fr.enemyRace, fr.finished);
}
function getFightRaces(uint _fightId) public view returns(uint[]) {
Fight storage f = fights[_fightId];
if (f.startedAt == 0) return;
uint[] memory r = new uint[](f.raceCount);
for(uint i; i < f.raceCount; i++) {
r[i] = f.raceList[i];
}
return r;
}
function getFightRace(uint _fightId, uint _race) external view returns (
uint index,
uint count,
uint enemyCount,
int32 result
){
Race memory r = fights[_fightId].races[_race];
return (r.index, r.count, r.enemyCount, r.result);
}
function getFightRaceLevelStat(uint _fightId, uint _race, uint _level) external view returns (
uint levelCount,
uint levelSum
){
Race storage r = fights[_fightId].races[_race];
return (r.levelCount[_level], r.levelSum);
}
function getFightResult(uint _fightId, uint _tokenId) public view returns (Result) {
Fight storage f = fights[_fightId];
Fighter storage fr = f.fighters[_tokenId];
if (!fr.exists) {
return Result.QUAIL;
}
return f.races[fr.race].result > f.races[fr.enemyRace].result ? Result.WIN : f.races[fr.race].result < f.races[fr.enemyRace].result ? Result.LOSS : Result.DRAW;
}
function isAllowed(uint tokenId) public view returns (bool) {
uint fightId = characterLastFightId(tokenId);
return fightId == 0 ? true : fights[fightId].fighters[tokenId].finished;
}
function getCurrentFight() public view returns (
uint256 fightId,
uint256 startedAt,
uint256 finishedAt,
uint256 startCheckedAt,
uint256 finishCheckedAt,
uint256 fightersCount,
uint256 raceCount
) {
fightId = getCurrentFightId();
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, fightersCount, raceCount) = getFight(fightId);
}
function getNextFight() public view returns (
uint256 fightId,
uint256 startedAt,
uint256 finishedAt,
uint256 startCheckedAt,
uint256 finishCheckedAt,
uint256 fightersCount,
uint256 raceCount
) {
fightId = getNextFightId();
(startedAt, finishedAt, startCheckedAt, finishCheckedAt, fightersCount, raceCount) = getFight(fightId);
}
function getFight(uint _fightId) public view returns (
uint256 startedAt,
uint256 finishedAt,
uint256 startCheckedAt,
uint256 finishCheckedAt,
uint256 fightersCount,
uint256 raceCount
) {
Fight memory f = fights[_fightId];
return (f.startedAt, f.finishedAt, f.startCheckedAt, f.finishCheckedAt, f.fightersCount, f.raceCount);
}
function getNextFightInterval() external view returns (
uint fightId,
uint currentTime,
uint applicationStartAt,
uint betsStartAt,
uint fightStartAt,
uint fightFinishAt
) {
uint intervalId = _getFightIntervalIdAt(now);
fightId = getFightId(intervalId, 1);
(currentTime, applicationStartAt, betsStartAt, fightStartAt, fightFinishAt) = _getFightInterval(intervalId, 1);
}
function getCurrentFightInterval() external view returns (
uint fightId,
uint currentTime,
uint applicationStartAt,
uint betsStartAt,
uint fightStartAt,
uint fightFinishAt
) {
uint intervalId = _getFightIntervalIdAt(now);
fightId = getFightId(intervalId, 0);
(currentTime, applicationStartAt, betsStartAt, fightStartAt, fightFinishAt) = _getFightInterval(intervalId, 0);
}
function _getFightInterval(uint intervalId, uint nextShift) internal view returns (
uint currentTime,
uint applicationStartAt,
uint betsStartAt,
uint fightStartAt,
uint fightFinishAt
) {
fightStartAt = _getFightStartsAt(intervalId, nextShift);
FightInterval memory i = intervalHistory[intervalId];
currentTime = now;
applicationStartAt = fightStartAt - i.applicationPeriod;
betsStartAt = fightStartAt - i.betsPeriod;
fightFinishAt = fightStartAt + i.fightPeriod;
}
function _getFightStartsAt(uint intervalId, uint nextShift) internal view returns (uint) {
FightInterval memory i = intervalHistory[intervalId];
uint intervalsCount = (now - i.startsFrom) / i.fightsInterval + nextShift;
return i.startsFrom + i.fightsInterval * intervalsCount;
}
function getCurrentIntervals() external view returns (
uint fightsInterval,
uint fightPeriod,
uint applicationPeriod,
uint betsPeriod
) {
FightInterval memory i = _getFightIntervalAt(now);
fightsInterval = i.fightsInterval;
fightPeriod = i.fightPeriod;
applicationPeriod = i.applicationPeriod;
betsPeriod = i.betsPeriod;
}
function _getFightIntervalAt(uint _time) internal view returns (FightInterval memory) {
return intervalHistory[_getFightIntervalIdAt(_time)];
}
function _getFightIntervalIdAt(uint _time) internal view returns (uint) {
require(intervalHistory.length>0);
if (_time >= intervalHistory[intervalHistory.length - 1].startsFrom)
return intervalHistory.length - 1;
if (_time < intervalHistory[0].startsFrom) return 0;
uint min = 0;
uint max = intervalHistory.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (intervalHistory[mid].startsFrom <= _time) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
function setFightResult(uint fightId, uint count, uint[] packedRaces, uint[] packedResults) public onlyService {
require(packedRaces.length == packedResults.length);
require(packedRaces.length * 8 >= count);
Fight storage f = fights[fightId];
require(f.startedAt != 0 && f.finishedAt == 0);
for (uint i = 0; i < count; i++) {
f.races[_upack(packedRaces[i / 8], i % 8)].result = int32(_upack(packedResults[i / 8], i % 8));
}
emit FightResult(fightId, packedRaces, packedResults);
}
function finishFight(uint fightId, uint startCheckedAt, uint finishCheckedAt) public onlyService {
Fight storage f = fights[fightId];
require(f.startedAt != 0 && f.finishedAt == 0);
FightInterval memory i = _getFightIntervalAt(f.startedAt);
require(now >= f.startedAt + i.fightPeriod);
f.finishedAt = now;
f.startCheckedAt = startCheckedAt;
f.finishCheckedAt = finishCheckedAt;
emit FinishFight(fightId, f.startedAt, f.finishedAt, startCheckedAt, finishCheckedAt);
}
function _upack(uint _v, uint _n) internal pure returns (uint) {
return (_v >> (32 * _n)) & 0xFFFFFFFF;
}
function _puck(uint _v, uint _n, uint _x) internal pure returns (uint) {
return _v & ~(0xFFFFFFFF << (32 * _n)) | ((_x & 0xFFFFFFFF) << (32 * _n));
}
} | 0 |
pragma solidity ^0.4.18;
interface token {
function transfer(address receiver, uint amount) external;
}
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract CandyContract is owned{
token public tokenReward;
uint public totalCandyNo;
address public collectorAddress;
mapping(address => uint256) public balanceOf;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
constructor(
address addressOfTokenUsedAsReward,
address collector
) public {
totalCandyNo = 1e8;
tokenReward = token(addressOfTokenUsedAsReward);
collectorAddress = collector;
}
function () payable public {
require(totalCandyNo > 0);
uint amount = getCurrentCandyAmount();
require(amount > 0);
require(balanceOf[msg.sender] == 0);
totalCandyNo -= amount;
balanceOf[msg.sender] = amount;
tokenReward.transfer(msg.sender, amount * 1e18);
emit FundTransfer(msg.sender, amount, true);
}
function getCurrentCandyAmount() private view returns (uint amount){
if (totalCandyNo >= 7.5e7){
return 2000;
}else if (totalCandyNo >= 5e7){
return 1500;
}else if (totalCandyNo >= 2.5e7){
return 1000;
}else if (totalCandyNo >= 500){
return 500;
}else{
return 0;
}
}
function collectBack() onlyOwner public{
require(totalCandyNo > 0);
require(collectorAddress != 0x0);
tokenReward.transfer(collectorAddress, totalCandyNo * 1e18);
totalCandyNo = 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 = 29462400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x7eb5D4de6214820AEBE3FB5c6c3BC847095E138b;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.19;
interface UNetworkToken {
function transfer (address receiver, uint amount) public;
function balanceOf(address _owner) returns (uint256 balance);
}
contract AirDrop {
UNetworkToken UUU;
address owner;
uint256[] values = [1000, 1000, 1000, 1000, 1000, 1000, 1000, 2000, 1000, 1000, 1000, 1000, 2000, 1000, 3000, 1000, 1000, 1000, 1000, 1500, 1500, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1500, 1000, 1000, 1000, 1000, 1000, 1000, 1500, 1000, 1000, 1000, 1500, 1000, 1500, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 2000];
address[] recipients = [0x256E14111324C466e3c4083e2e0c15f2A4160564, 0x54B478834E0420A638e80a1227B5eE6Fc0eBD826, 0x502bDbCdD80e72AaFBdE0f596370F2140609d9fE, 0xB62204E21F716E92C58aa89824fB776a43E86EF0, 0xcafe613b80d89c28b2234ba5f67a8768168e69b0, 0xB1cde3C0bbC7AB5d5358c49951724D9173382Ce0, 0xcbdcB14D4963a045d6517A89AaB07a097230C9BC, 0x1Af41a96BbaF348c3Ca582B65193aB4d9108a22B, 0xB536f4a39601f8Aa1181788dE9E6512b6bF84b2D, 0x9c218aDEC066746e50480b16511E6fACA27887Ec, 0x77ab8a655C6CF540471140EFD0EaaBaE78C132a0, 0x131F640ea83A514FE0Fb23629dfd9322AdAd3A46, 0x685d9638f22b552E1f9fe4e1325970Fc07E52993, 0xc0724eA6D70FB600D0231646976CA80104a18002, 0xF29e2B524Fd1F5BE1A41DcAb9333Ed27567904c1, 0x44300D827d506869cE8eb4bd3D6de148149Cf612, 0x107888B0EF5e020bfD4fE4C96717E4d1c456e779, 0xb5cd3e657c6902938134824De1eAaf254EBd379B, 0x511e81B9D6c360FB6ECbD923f66aAd7c34cDFFB9, 0xBD751330817016c82090e9dFCA58E2A5adC8C58D, 0xcb700331ec50b8deDb4A8C7e0a35ea09f90462E0, 0x399C25e7eE10e52f8e653a6DC7D86CE1913ABF52, 0x84eb0A60C6e5B487680A5BEfD1662D799a8f85B2, 0x1e656cF38a135fF035095E4019B87301577ADa2f, 0x3D00301Ed8B7284dbA8f1364B16aC5eBF670da96, 0x143d9CF6c8a2985c6C9466FBC90e5fE4021eB179, 0x776B909e33de14a21792eB1a9bbE9Dd01B0b8FAa, 0xDeA5467F9Ce1Efa822eF9Cac7Bb57C7340B9c2eB, 0x770E071e6A2Fd30C5AC8Ee3C5355760b30744435, 0x4EB8aCf669F07c06052fd17fE969DE7CBF598B22, 0x4F4193e1469b5dCb8391db87cA479Eb6F2C68F81, 0xDf6B3912a8D10DAfa13187C0D594002cB0f38a0e, 0x487ce9681CDE8e4291eAd6884F0E5CCfAE367Bc9, 0xd638CfF60126683a655DDa9E56ee794d8Dc33FAa, 0x4a033a1Fa7D620D698F12EEE65627687c00B4C3b, 0xF2faAf764a1242f9A3aEF4B16c51a94866e72736, 0x9584b1C7FAC855E4Ce124AF0E2f91DAbce475C46, 0xd6A884870456aE7d67dc886468c5C689abCDd1C1, 0x50f81d6d5dc9553fdfce7ad1abc7844a92ede147, 0x1965B5AA812535F8A272D8BaeE6B289c11E9ac73, 0xc52ffD6dccb1815517cc82B4Ff875d74d66C8fbd, 0xD735d7B9d9820Ae1877E3B103b989d81a354a853, 0xFF6e05C50916347384552EE5423E5646b0FB8Ca3, 0xF3C8fcFF6BD85Fb30e3e3043CdbC595aF3BAb20B, 0xc72a630eAA53f6E02fa98C6Ec0196192af8567c1, 0xC61fFe6156735FB81e4F21e086f131e2358192B0, 0x4E0d21509F98d6e7449CD169343A52ABA69d1B7D, 0xf802c6fc68Bc4C66E40BE21DDc5263E137d76b24, 0x417f80ba6c20e9c8dd4f5d82f5cd3e2ca6b899e2, 0xe2bFE3A2fdAE437D482ccA8CB26e4714864800AF, 0xB10f8Cd03dD737a5DeBe99c2deCC383DC2003f9A, 0xb9de7F205C8735E2bcdAf897639CC01e5Ed9fe31, 0xB1cde3C0bbC7AB5d5358c49951724D9173382Ce0, 0x1a095e6aca660de37c2c074763c53e31779f6d03];
function AirDrop() public {
UUU = UNetworkToken(0x3543638ed4a9006e4840b105944271bcea15605d);
owner = msg.sender;
require(values.length == recipients.length);
}
function drop() public {
for (uint256 i = 0; i < recipients.length; i++) {
UUU.transfer(recipients[i], values[i] * 10 ** 18);
}
}
function refund() public {
UUU.transfer(owner, UUU.balanceOf(this));
}
} | 1 |
pragma solidity ^0.4.13;
contract StaffUtil {
Staff public staffContract;
constructor (Staff _staffContract) public {
require(msg.sender == _staffContract.owner());
staffContract = _staffContract;
}
modifier onlyOwner() {
require(msg.sender == staffContract.owner());
_;
}
modifier onlyOwnerOrStaff() {
require(msg.sender == staffContract.owner() || staffContract.isStaff(msg.sender));
_;
}
}
contract Crowdsale is StaffUtil {
using SafeMath for uint256;
Token tokenContract;
PromoCodes promoCodesContract;
DiscountPhases discountPhasesContract;
DiscountStructs discountStructsContract;
address ethFundsWallet;
uint256 referralBonusPercent;
uint256 startDate;
uint256 crowdsaleStartDate;
uint256 endDate;
uint256 tokenDecimals;
uint256 tokenRate;
uint256 tokensForSaleCap;
uint256 minPurchaseInWei;
uint256 maxInvestorContributionInWei;
bool paused;
bool finalized;
uint256 weiRaised;
uint256 soldTokens;
uint256 bonusTokens;
uint256 sentTokens;
uint256 claimedSoldTokens;
uint256 claimedBonusTokens;
uint256 claimedSentTokens;
uint256 purchasedTokensClaimDate;
uint256 bonusTokensClaimDate;
mapping(address => Investor) public investors;
enum InvestorStatus {UNDEFINED, WHITELISTED, BLOCKED}
struct Investor {
InvestorStatus status;
uint256 contributionInWei;
uint256 purchasedTokens;
uint256 bonusTokens;
uint256 referralTokens;
uint256 receivedTokens;
TokensPurchase[] tokensPurchases;
bool isBlockpass;
}
struct TokensPurchase {
uint256 value;
uint256 amount;
uint256 bonus;
address referrer;
uint256 referrerSentAmount;
}
event InvestorWhitelisted(address indexed investor, uint timestamp, address byStaff);
event InvestorBlocked(address indexed investor, uint timestamp, address byStaff);
event TokensPurchased(
address indexed investor,
uint indexed purchaseId,
uint256 value,
uint256 purchasedAmount,
uint256 promoCodeAmount,
uint256 discountPhaseAmount,
uint256 discountStructAmount,
address indexed referrer,
uint256 referrerSentAmount,
uint timestamp
);
event TokensPurchaseRefunded(
address indexed investor,
uint indexed purchaseId,
uint256 value,
uint256 amount,
uint256 bonus,
uint timestamp,
address byStaff
);
event Paused(uint timestamp, address byStaff);
event Resumed(uint timestamp, address byStaff);
event Finalized(uint timestamp, address byStaff);
event TokensSent(address indexed investor, uint256 amount, uint timestamp, address byStaff);
event PurchasedTokensClaimLocked(uint date, uint timestamp, address byStaff);
event PurchasedTokensClaimUnlocked(uint timestamp, address byStaff);
event BonusTokensClaimLocked(uint date, uint timestamp, address byStaff);
event BonusTokensClaimUnlocked(uint timestamp, address byStaff);
event CrowdsaleStartDateUpdated(uint date, uint timestamp, address byStaff);
event EndDateUpdated(uint date, uint timestamp, address byStaff);
event MinPurchaseChanged(uint256 minPurchaseInWei, uint timestamp, address byStaff);
event MaxInvestorContributionChanged(uint256 maxInvestorContributionInWei, uint timestamp, address byStaff);
event TokenRateChanged(uint newRate, uint timestamp, address byStaff);
event TokensClaimed(
address indexed investor,
uint256 purchased,
uint256 bonus,
uint256 referral,
uint256 received,
uint timestamp,
address byStaff
);
event TokensBurned(uint256 amount, uint timestamp, address byStaff);
constructor (
uint256[11] uint256Args,
address[5] addressArgs
) StaffUtil(Staff(addressArgs[4])) public {
startDate = uint256Args[0];
crowdsaleStartDate = uint256Args[1];
endDate = uint256Args[2];
tokenDecimals = uint256Args[3];
tokenRate = uint256Args[4];
tokensForSaleCap = uint256Args[5];
minPurchaseInWei = uint256Args[6];
maxInvestorContributionInWei = uint256Args[7];
purchasedTokensClaimDate = uint256Args[8];
bonusTokensClaimDate = uint256Args[9];
referralBonusPercent = uint256Args[10];
ethFundsWallet = addressArgs[0];
promoCodesContract = PromoCodes(addressArgs[1]);
discountPhasesContract = DiscountPhases(addressArgs[2]);
discountStructsContract = DiscountStructs(addressArgs[3]);
require(startDate < crowdsaleStartDate);
require(crowdsaleStartDate < endDate);
require(tokenRate > 0);
require(tokenRate > 0);
require(tokensForSaleCap > 0);
require(minPurchaseInWei <= maxInvestorContributionInWei);
require(ethFundsWallet != address(0));
}
function getState() external view returns (bool[2] boolArgs, uint256[18] uint256Args, address[6] addressArgs) {
boolArgs[0] = paused;
boolArgs[1] = finalized;
uint256Args[0] = weiRaised;
uint256Args[1] = soldTokens;
uint256Args[2] = bonusTokens;
uint256Args[3] = sentTokens;
uint256Args[4] = claimedSoldTokens;
uint256Args[5] = claimedBonusTokens;
uint256Args[6] = claimedSentTokens;
uint256Args[7] = purchasedTokensClaimDate;
uint256Args[8] = bonusTokensClaimDate;
uint256Args[9] = startDate;
uint256Args[10] = crowdsaleStartDate;
uint256Args[11] = endDate;
uint256Args[12] = tokenRate;
uint256Args[13] = tokenDecimals;
uint256Args[14] = minPurchaseInWei;
uint256Args[15] = maxInvestorContributionInWei;
uint256Args[16] = referralBonusPercent;
uint256Args[17] = getTokensForSaleCap();
addressArgs[0] = staffContract;
addressArgs[1] = ethFundsWallet;
addressArgs[2] = promoCodesContract;
addressArgs[3] = discountPhasesContract;
addressArgs[4] = discountStructsContract;
addressArgs[5] = tokenContract;
}
function fitsTokensForSaleCap(uint256 _amount) public view returns (bool) {
return getDistributedTokens().add(_amount) <= getTokensForSaleCap();
}
function getTokensForSaleCap() public view returns (uint256) {
if (tokenContract != address(0)) {
return tokenContract.balanceOf(this);
}
return tokensForSaleCap;
}
function getDistributedTokens() public view returns (uint256) {
return soldTokens.sub(claimedSoldTokens).add(bonusTokens.sub(claimedBonusTokens)).add(sentTokens.sub(claimedSentTokens));
}
function setTokenContract(Token token) external onlyOwner {
require(tokenContract == address(0));
require(token != address(0));
tokenContract = token;
}
function getInvestorClaimedTokens(address _investor) external view returns (uint256) {
if (tokenContract != address(0)) {
return tokenContract.balanceOf(_investor);
}
return 0;
}
function isBlockpassInvestor(address _investor) external constant returns (bool) {
return investors[_investor].status == InvestorStatus.WHITELISTED && investors[_investor].isBlockpass;
}
function whitelistInvestor(address _investor, bool _isBlockpass) external onlyOwnerOrStaff {
require(_investor != address(0));
require(investors[_investor].status != InvestorStatus.WHITELISTED);
investors[_investor].status = InvestorStatus.WHITELISTED;
investors[_investor].isBlockpass = _isBlockpass;
emit InvestorWhitelisted(_investor, now, msg.sender);
}
function bulkWhitelistInvestor(address[] _investors) external onlyOwnerOrStaff {
for (uint256 i = 0; i < _investors.length; i++) {
if (_investors[i] != address(0) && investors[_investors[i]].status != InvestorStatus.WHITELISTED) {
investors[_investors[i]].status = InvestorStatus.WHITELISTED;
emit InvestorWhitelisted(_investors[i], now, msg.sender);
}
}
}
function blockInvestor(address _investor) external onlyOwnerOrStaff {
require(_investor != address(0));
require(investors[_investor].status != InvestorStatus.BLOCKED);
investors[_investor].status = InvestorStatus.BLOCKED;
emit InvestorBlocked(_investor, now, msg.sender);
}
function lockPurchasedTokensClaim(uint256 _date) external onlyOwner {
require(_date > now);
purchasedTokensClaimDate = _date;
emit PurchasedTokensClaimLocked(_date, now, msg.sender);
}
function unlockPurchasedTokensClaim() external onlyOwner {
purchasedTokensClaimDate = now;
emit PurchasedTokensClaimUnlocked(now, msg.sender);
}
function lockBonusTokensClaim(uint256 _date) external onlyOwner {
require(_date > now);
bonusTokensClaimDate = _date;
emit BonusTokensClaimLocked(_date, now, msg.sender);
}
function unlockBonusTokensClaim() external onlyOwner {
bonusTokensClaimDate = now;
emit BonusTokensClaimUnlocked(now, msg.sender);
}
function setCrowdsaleStartDate(uint256 _date) external onlyOwner {
crowdsaleStartDate = _date;
emit CrowdsaleStartDateUpdated(_date, now, msg.sender);
}
function setEndDate(uint256 _date) external onlyOwner {
endDate = _date;
emit EndDateUpdated(_date, now, msg.sender);
}
function setMinPurchaseInWei(uint256 _minPurchaseInWei) external onlyOwner {
minPurchaseInWei = _minPurchaseInWei;
emit MinPurchaseChanged(_minPurchaseInWei, now, msg.sender);
}
function setMaxInvestorContributionInWei(uint256 _maxInvestorContributionInWei) external onlyOwner {
require(minPurchaseInWei <= _maxInvestorContributionInWei);
maxInvestorContributionInWei = _maxInvestorContributionInWei;
emit MaxInvestorContributionChanged(_maxInvestorContributionInWei, now, msg.sender);
}
function changeTokenRate(uint256 _tokenRate) external onlyOwner {
require(_tokenRate > 0);
tokenRate = _tokenRate;
emit TokenRateChanged(_tokenRate, now, msg.sender);
}
function buyTokens(bytes32 _promoCode, address _referrer) external payable {
require(!finalized);
require(!paused);
require(startDate < now);
require(investors[msg.sender].status == InvestorStatus.WHITELISTED);
require(msg.value > 0);
require(msg.value >= minPurchaseInWei);
require(investors[msg.sender].contributionInWei.add(msg.value) <= maxInvestorContributionInWei);
uint256 purchasedAmount;
if (tokenDecimals > 18) {
purchasedAmount = msg.value.mul(tokenRate).mul(10 ** (tokenDecimals - 18));
} else if (tokenDecimals < 18) {
purchasedAmount = msg.value.mul(tokenRate).div(10 ** (18 - tokenDecimals));
} else {
purchasedAmount = msg.value.mul(tokenRate);
}
uint256 promoCodeBonusAmount = promoCodesContract.applyBonusAmount(msg.sender, purchasedAmount, _promoCode);
uint256 discountPhaseBonusAmount = discountPhasesContract.calculateBonusAmount(purchasedAmount);
uint256 discountStructBonusAmount = discountStructsContract.getBonus(msg.sender, purchasedAmount, msg.value);
uint256 bonusAmount = promoCodeBonusAmount.add(discountPhaseBonusAmount).add(discountStructBonusAmount);
uint256 referrerBonusAmount;
address referrerAddr;
if (
_referrer != address(0)
&& msg.sender != _referrer
&& investors[_referrer].status == InvestorStatus.WHITELISTED
) {
referrerBonusAmount = purchasedAmount * referralBonusPercent / 100;
referrerAddr = _referrer;
}
require(fitsTokensForSaleCap(purchasedAmount.add(bonusAmount).add(referrerBonusAmount)));
weiRaised = weiRaised.add(msg.value);
soldTokens = soldTokens.add(purchasedAmount);
bonusTokens = bonusTokens.add(bonusAmount).add(referrerBonusAmount);
investors[referrerAddr].referralTokens = investors[referrerAddr].referralTokens.add(referrerBonusAmount);
investors[msg.sender].purchasedTokens = investors[msg.sender].purchasedTokens.add(purchasedAmount);
investors[msg.sender].bonusTokens = investors[msg.sender].bonusTokens.add(bonusAmount);
investors[msg.sender].contributionInWei = investors[msg.sender].contributionInWei.add(msg.value);
uint tokensPurchasesLength = investors[msg.sender].tokensPurchases.push(TokensPurchase({
value : msg.value,
amount : purchasedAmount,
bonus : bonusAmount,
referrer : referrerAddr,
referrerSentAmount : referrerBonusAmount
})
);
emit TokensPurchased(
msg.sender,
tokensPurchasesLength - 1,
msg.value,
purchasedAmount,
promoCodeBonusAmount,
discountPhaseBonusAmount,
discountStructBonusAmount,
referrerAddr,
referrerBonusAmount,
now
);
ethFundsWallet.transfer(msg.value);
}
function sendTokens(address _investor, uint256 _amount) external onlyOwner {
require(investors[_investor].status == InvestorStatus.WHITELISTED);
require(_amount > 0);
require(fitsTokensForSaleCap(_amount));
sentTokens = sentTokens.add(_amount);
investors[_investor].receivedTokens = investors[_investor].receivedTokens.add(_amount);
emit TokensSent(
_investor,
_amount,
now,
msg.sender
);
}
function burnUnsoldTokens() external onlyOwner {
require(tokenContract != address(0));
require(finalized);
uint256 tokensToBurn = tokenContract.balanceOf(this).sub(getDistributedTokens());
require(tokensToBurn > 0);
tokenContract.burn(tokensToBurn);
emit TokensBurned(tokensToBurn, now, msg.sender);
}
function claimTokens() external {
require(tokenContract != address(0));
require(!paused);
require(investors[msg.sender].status == InvestorStatus.WHITELISTED);
uint256 clPurchasedTokens;
uint256 clReceivedTokens;
uint256 clBonusTokens_;
uint256 clRefTokens;
require(purchasedTokensClaimDate < now || bonusTokensClaimDate < now);
{
uint256 purchasedTokens = investors[msg.sender].purchasedTokens;
uint256 receivedTokens = investors[msg.sender].receivedTokens;
if (purchasedTokensClaimDate < now && (purchasedTokens > 0 || receivedTokens > 0)) {
investors[msg.sender].contributionInWei = 0;
investors[msg.sender].purchasedTokens = 0;
investors[msg.sender].receivedTokens = 0;
claimedSoldTokens = claimedSoldTokens.add(purchasedTokens);
claimedSentTokens = claimedSentTokens.add(receivedTokens);
delete (investors[msg.sender].tokensPurchases);
clPurchasedTokens = purchasedTokens;
clReceivedTokens = receivedTokens;
tokenContract.transfer(msg.sender, purchasedTokens.add(receivedTokens));
}
}
{
uint256 bonusTokens_ = investors[msg.sender].bonusTokens;
uint256 refTokens = investors[msg.sender].referralTokens;
if (bonusTokensClaimDate < now && (bonusTokens_ > 0 || refTokens > 0)) {
investors[msg.sender].bonusTokens = 0;
investors[msg.sender].referralTokens = 0;
claimedBonusTokens = claimedBonusTokens.add(bonusTokens_).add(refTokens);
clBonusTokens_ = bonusTokens_;
clRefTokens = refTokens;
tokenContract.transfer(msg.sender, bonusTokens_.add(refTokens));
}
}
require(clPurchasedTokens > 0 || clBonusTokens_ > 0 || clRefTokens > 0 || clReceivedTokens > 0);
emit TokensClaimed(msg.sender, clPurchasedTokens, clBonusTokens_, clRefTokens, clReceivedTokens, now, msg.sender);
}
function refundTokensPurchase(address _investor, uint _purchaseId) external payable onlyOwner {
require(msg.value > 0);
require(investors[_investor].tokensPurchases[_purchaseId].value == msg.value);
_refundTokensPurchase(_investor, _purchaseId);
_investor.transfer(msg.value);
}
function refundAllInvestorTokensPurchases(address _investor) external payable onlyOwner {
require(msg.value > 0);
require(investors[_investor].contributionInWei == msg.value);
for (uint i = 0; i < investors[_investor].tokensPurchases.length; i++) {
if (investors[_investor].tokensPurchases[i].value == 0) {
continue;
}
_refundTokensPurchase(_investor, i);
}
_investor.transfer(msg.value);
}
function _refundTokensPurchase(address _investor, uint _purchaseId) private {
address referrer = investors[_investor].tokensPurchases[_purchaseId].referrer;
if (referrer != address(0)) {
uint256 sentAmount = investors[_investor].tokensPurchases[_purchaseId].referrerSentAmount;
investors[referrer].referralTokens = investors[referrer].referralTokens.sub(sentAmount);
bonusTokens = bonusTokens.sub(sentAmount);
}
uint256 purchaseValue = investors[_investor].tokensPurchases[_purchaseId].value;
investors[_investor].contributionInWei = investors[_investor].contributionInWei.sub(purchaseValue);
uint256 purchaseAmount = investors[_investor].tokensPurchases[_purchaseId].amount;
investors[_investor].purchasedTokens = investors[_investor].purchasedTokens.sub(purchaseAmount);
uint256 bonusAmount = investors[_investor].tokensPurchases[_purchaseId].bonus;
investors[_investor].bonusTokens = investors[_investor].bonusTokens.sub(bonusAmount);
weiRaised = weiRaised.sub(purchaseValue);
soldTokens = soldTokens.sub(purchaseAmount);
bonusTokens = bonusTokens.sub(bonusAmount);
delete (investors[_investor].tokensPurchases[_purchaseId]);
emit TokensPurchaseRefunded(_investor, _purchaseId, purchaseValue, purchaseAmount, bonusAmount, now, msg.sender);
}
function getInvestorTokensPurchasesLength(address _investor) public constant returns (uint) {
return investors[_investor].tokensPurchases.length;
}
function getInvestorTokensPurchase(
address _investor,
uint _purchaseId
) external constant returns (
uint256 value,
uint256 amount,
uint256 bonus,
address referrer,
uint256 referrerSentAmount
) {
value = investors[_investor].tokensPurchases[_purchaseId].value;
amount = investors[_investor].tokensPurchases[_purchaseId].amount;
bonus = investors[_investor].tokensPurchases[_purchaseId].bonus;
referrer = investors[_investor].tokensPurchases[_purchaseId].referrer;
referrerSentAmount = investors[_investor].tokensPurchases[_purchaseId].referrerSentAmount;
}
function pause() external onlyOwner {
require(!paused);
paused = true;
emit Paused(now, msg.sender);
}
function resume() external onlyOwner {
require(paused);
paused = false;
emit Resumed(now, msg.sender);
}
function finalize() external onlyOwner {
require(!finalized);
finalized = true;
emit Finalized(now, msg.sender);
}
}
contract DiscountPhases is StaffUtil {
event DiscountPhaseAdded(uint index, string name, uint8 percent, uint fromDate, uint toDate, uint timestamp, address byStaff);
event DiscountPhaseRemoved(uint index, uint timestamp, address byStaff);
struct DiscountPhase {
uint8 percent;
uint fromDate;
uint toDate;
}
DiscountPhase[] public discountPhases;
constructor(Staff _staffContract) StaffUtil(_staffContract) public {
}
function calculateBonusAmount(uint256 _purchasedAmount) public constant returns (uint256) {
for (uint i = 0; i < discountPhases.length; i++) {
if (now >= discountPhases[i].fromDate && now <= discountPhases[i].toDate) {
return _purchasedAmount * discountPhases[i].percent / 100;
}
}
}
function addDiscountPhase(string _name, uint8 _percent, uint _fromDate, uint _toDate) public onlyOwnerOrStaff {
require(bytes(_name).length > 0);
require(_percent > 0);
if (now > _fromDate) {
_fromDate = now;
}
require(_fromDate < _toDate);
for (uint i = 0; i < discountPhases.length; i++) {
require(_fromDate > discountPhases[i].toDate || _toDate < discountPhases[i].fromDate);
}
uint index = discountPhases.push(DiscountPhase({percent : _percent, fromDate : _fromDate, toDate : _toDate})) - 1;
emit DiscountPhaseAdded(index, _name, _percent, _fromDate, _toDate, now, msg.sender);
}
function removeDiscountPhase(uint _index) public onlyOwnerOrStaff {
require(now < discountPhases[_index].toDate);
delete discountPhases[_index];
emit DiscountPhaseRemoved(_index, now, msg.sender);
}
}
contract DiscountStructs is StaffUtil {
using SafeMath for uint256;
address public crowdsale;
event DiscountStructAdded(
uint index,
bytes32 name,
uint256 tokens,
uint[2] dates,
uint256[] fromWei,
uint256[] toWei,
uint256[] percent,
uint timestamp,
address byStaff
);
event DiscountStructRemoved(
uint index,
uint timestamp,
address byStaff
);
event DiscountStructUsed(
uint index,
uint step,
address investor,
uint256 tokens,
uint timestamp
);
struct DiscountStruct {
uint256 availableTokens;
uint256 distributedTokens;
uint fromDate;
uint toDate;
}
struct DiscountStep {
uint256 fromWei;
uint256 toWei;
uint256 percent;
}
DiscountStruct[] public discountStructs;
mapping(uint => DiscountStep[]) public discountSteps;
constructor(Staff _staffContract) StaffUtil(_staffContract) public {
}
modifier onlyCrowdsale() {
require(msg.sender == crowdsale);
_;
}
function setCrowdsale(Crowdsale _crowdsale) external onlyOwner {
require(crowdsale == address(0));
require(_crowdsale.staffContract() == staffContract);
crowdsale = _crowdsale;
}
function getBonus(address _investor, uint256 _purchasedAmount, uint256 _purchasedValue) public onlyCrowdsale returns (uint256) {
for (uint i = 0; i < discountStructs.length; i++) {
if (now >= discountStructs[i].fromDate && now <= discountStructs[i].toDate) {
if (discountStructs[i].distributedTokens >= discountStructs[i].availableTokens) {
return;
}
for (uint j = 0; j < discountSteps[i].length; j++) {
if (_purchasedValue >= discountSteps[i][j].fromWei
&& (_purchasedValue < discountSteps[i][j].toWei || discountSteps[i][j].toWei == 0)) {
uint256 bonus = _purchasedAmount * discountSteps[i][j].percent / 100;
if (discountStructs[i].distributedTokens.add(bonus) > discountStructs[i].availableTokens) {
return;
}
discountStructs[i].distributedTokens = discountStructs[i].distributedTokens.add(bonus);
emit DiscountStructUsed(i, j, _investor, bonus, now);
return bonus;
}
}
return;
}
}
}
function calculateBonus(uint256 _purchasedAmount, uint256 _purchasedValue) public constant returns (uint256) {
for (uint i = 0; i < discountStructs.length; i++) {
if (now >= discountStructs[i].fromDate && now <= discountStructs[i].toDate) {
if (discountStructs[i].distributedTokens >= discountStructs[i].availableTokens) {
return;
}
for (uint j = 0; j < discountSteps[i].length; j++) {
if (_purchasedValue >= discountSteps[i][j].fromWei
&& (_purchasedValue < discountSteps[i][j].toWei || discountSteps[i][j].toWei == 0)) {
uint256 bonus = _purchasedAmount * discountSteps[i][j].percent / 100;
if (discountStructs[i].distributedTokens.add(bonus) > discountStructs[i].availableTokens) {
return;
}
return bonus;
}
}
return;
}
}
}
function addDiscountStruct(bytes32 _name, uint256 _tokens, uint[2] _dates, uint256[] _fromWei, uint256[] _toWei, uint256[] _percent) external onlyOwnerOrStaff {
require(_name.length > 0);
require(_tokens > 0);
require(_dates[0] < _dates[1]);
require(_fromWei.length > 0 && _fromWei.length == _toWei.length && _fromWei.length == _percent.length);
for (uint j = 0; j < discountStructs.length; j++) {
require(_dates[0] > discountStructs[j].fromDate || _dates[1] < discountStructs[j].toDate);
}
DiscountStruct memory ds = DiscountStruct(_tokens, 0, _dates[0], _dates[1]);
uint index = discountStructs.push(ds) - 1;
for (uint i = 0; i < _fromWei.length; i++) {
require(_fromWei[i] > 0 || _toWei[i] > 0);
require(_percent[i] > 0);
discountSteps[index].push(DiscountStep(_fromWei[i], _toWei[i], _percent[i]));
}
emit DiscountStructAdded(index, _name, _tokens, _dates, _fromWei, _toWei, _percent, now, msg.sender);
}
function removeDiscountStruct(uint _index) public onlyOwnerOrStaff {
require(now < discountStructs[_index].toDate);
delete discountStructs[_index];
delete discountSteps[_index];
emit DiscountStructRemoved(_index, now, msg.sender);
}
}
contract PromoCodes is StaffUtil {
address public crowdsale;
event PromoCodeAdded(bytes32 indexed code, string name, uint8 percent, uint256 maxUses, uint timestamp, address byStaff);
event PromoCodeRemoved(bytes32 indexed code, uint timestamp, address byStaff);
event PromoCodeUsed(bytes32 indexed code, address investor, uint timestamp);
struct PromoCode {
uint8 percent;
uint256 uses;
uint256 maxUses;
mapping(address => bool) investors;
}
mapping(bytes32 => PromoCode) public promoCodes;
constructor(Staff _staffContract) StaffUtil(_staffContract) public {
}
modifier onlyCrowdsale() {
require(msg.sender == crowdsale);
_;
}
function setCrowdsale(Crowdsale _crowdsale) external onlyOwner {
require(crowdsale == address(0));
require(_crowdsale.staffContract() == staffContract);
crowdsale = _crowdsale;
}
function applyBonusAmount(address _investor, uint256 _purchasedAmount, bytes32 _promoCode) public onlyCrowdsale returns (uint256) {
if (promoCodes[_promoCode].percent == 0
|| promoCodes[_promoCode].investors[_investor]
|| promoCodes[_promoCode].uses == promoCodes[_promoCode].maxUses) {
return 0;
}
promoCodes[_promoCode].investors[_investor] = true;
promoCodes[_promoCode].uses = promoCodes[_promoCode].uses + 1;
emit PromoCodeUsed(_promoCode, _investor, now);
return _purchasedAmount * promoCodes[_promoCode].percent / 100;
}
function calculateBonusAmount(address _investor, uint256 _purchasedAmount, bytes32 _promoCode) public constant returns (uint256) {
if (promoCodes[_promoCode].percent == 0
|| promoCodes[_promoCode].investors[_investor]
|| promoCodes[_promoCode].uses == promoCodes[_promoCode].maxUses) {
return 0;
}
return _purchasedAmount * promoCodes[_promoCode].percent / 100;
}
function addPromoCode(string _name, bytes32 _code, uint256 _maxUses, uint8 _percent) public onlyOwnerOrStaff {
require(bytes(_name).length > 0);
require(_code[0] != 0);
require(_percent > 0);
require(_maxUses > 0);
require(promoCodes[_code].percent == 0);
promoCodes[_code].percent = _percent;
promoCodes[_code].maxUses = _maxUses;
emit PromoCodeAdded(_code, _name, _percent, _maxUses, now, msg.sender);
}
function removePromoCode(bytes32 _code) public onlyOwnerOrStaff {
delete promoCodes[_code];
emit PromoCodeRemoved(_code, now, msg.sender);
}
}
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 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 Staff is Ownable, RBAC {
string public constant ROLE_STAFF = "staff";
function addStaff(address _staff) public onlyOwner {
addRole(_staff, ROLE_STAFF);
}
function removeStaff(address _staff) public onlyOwner {
removeRole(_staff, ROLE_STAFF);
}
function isStaff(address _staff) view public returns (bool) {
return hasRole(_staff, ROLE_STAFF);
}
}
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 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 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 Token is BurnableToken {
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29635200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x24ef504309240f94f915c96a2deDC7887096299B;
}
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.10;
interface ERC20 {
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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 ArpachainToken is ERC20 {
using SafeMath for uint;
string internal _name;
string internal _symbol;
uint8 public decimals = 6;
uint256 internal _totalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor() public {
_symbol = "OCT";
_name = "OC Test";
_totalSupply = 10 * 1000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value > 0);
require(balances[_to] + _value > balances[_to]);
uint256 previousBalances = balances[_from] + balances[_to];
balances[_from] = SafeMath.sub(balances[_from], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
emit Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool) {
_transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
_transfer(_from, _to, _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _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] = SafeMath.add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function increaseTotalSupply(uint256 _addedValue) public returns (bool) {
_totalSupply = SafeMath.add(_totalSupply, _addedValue);
balances[msg.sender] = SafeMath.add(balances[msg.sender], _addedValue);
emit Transfer(address(0), msg.sender, _addedValue);
return true;
}
} | 1 |
pragma solidity ^0.4.18;
contract ShrimpFarmer{
function buyEggs() public payable;
}
contract AdPotato{
address ceoAddress;
ShrimpFarmer fundsTarget;
Advertisement[] ads;
uint256 NUM_ADS=10;
uint256 BASE_PRICE=0.005 ether;
uint256 PERCENT_TAXED=30;
event BoughtAd(address sender, uint256 amount);
modifier onlyCLevel() {
require(
msg.sender == ceoAddress
);
_;
}
function AdPotato() public{
ceoAddress=msg.sender;
initialize(0x58AFF91f5b48245Bd83deeB2C7d31875f68b3f0D);
}
struct Advertisement{
string text;
string url;
address owner;
uint256 startingLevel;
uint256 startingTime;
uint256 halfLife;
}
function initialize(address fund) public onlyCLevel{
fundsTarget=ShrimpFarmer(fund);
for(uint i=0;i<NUM_ADS;i++){
ads.push(Advertisement({text:"Your Text Here",url:"",owner:ceoAddress,startingLevel:0,startingTime:now,halfLife:12 hours}));
}
}
function buyAd(uint256 index,string text,string url) public payable{
require(ads.length>index);
require(msg.sender==tx.origin);
Advertisement storage toBuy=ads[index];
uint256 currentLevel=getCurrentLevel(toBuy.startingLevel,toBuy.startingTime,toBuy.halfLife);
uint256 currentPrice=getCurrentPrice(currentLevel);
require(msg.value>=currentPrice);
uint256 purchaseExcess = SafeMath.sub(msg.value, currentPrice);
toBuy.text=text;
toBuy.url=url;
toBuy.startingLevel=currentLevel+1;
toBuy.startingTime=now;
fundsTarget.buyEggs.value(SafeMath.div(SafeMath.mul(currentPrice,PERCENT_TAXED),100))();
toBuy.owner.transfer(SafeMath.div(SafeMath.mul(currentPrice,100-PERCENT_TAXED),100));
toBuy.owner=msg.sender;
msg.sender.transfer(purchaseExcess);
emit BoughtAd(msg.sender,purchaseExcess);
}
function getAdText(uint256 index)public view returns(string){
return ads[index].text;
}
function getAdUrl(uint256 index)public view returns(string){
return ads[index].url;
}
function getAdOwner(uint256 index) public view returns(address){
return ads[index].owner;
}
function getAdPrice(uint256 index) public view returns(uint256){
Advertisement ad=ads[index];
return getCurrentPrice(getCurrentLevel(ad.startingLevel,ad.startingTime,ad.halfLife));
}
function getCurrentPrice(uint256 currentLevel) public view returns(uint256){
return BASE_PRICE*2**currentLevel;
}
function getCurrentLevel(uint256 startingLevel,uint256 startingTime,uint256 halfLife)public view returns(uint256){
uint256 timePassed=SafeMath.sub(now,startingTime);
uint256 levelsPassed=SafeMath.div(timePassed,halfLife);
if(startingLevel<levelsPassed){
return 0;
}
return SafeMath.sub(startingLevel,levelsPassed);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 0 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
contract ZTRToken{
function transfer(address _to, uint val);
}
contract ZTRTokenSale
{
using SafeMath for uint;
mapping (address => uint) public balanceOf;
mapping (address => uint) public ethBalance;
address public owner;
address ZTRTokenContract;
uint public fundingGoal;
uint public fundingMax;
uint public amountRaised;
uint public start;
uint public duration;
uint public deadline;
uint public unlockTime;
uint public ZTR_ETH_initial_price;
uint public ZTR_ETH_extra_price;
uint public remaining;
modifier admin { if (msg.sender == owner) _; }
modifier afterUnlock { if(now>unlockTime) _;}
modifier afterDeadline { if(now>deadline) _;}
function ZTRTokenSale()
{
owner = msg.sender;
ZTRTokenContract = 0x107bc486966eCdDAdb136463764a8Eb73337c4DF;
fundingGoal = 5000 ether;
fundingMax = 30000 ether;
start = 1517702401;
duration = 3 weeks;
deadline = start + duration;
unlockTime = deadline + 16 weeks;
ZTR_ETH_initial_price = 45000;
ZTR_ETH_extra_price = 23000;
remaining = 800000000000000000000000000;
}
function () payable public
{
require(now>start);
require(now<deadline);
require(amountRaised + msg.value < fundingMax);
uint purchase = msg.value;
ethBalance[msg.sender] = ethBalance[msg.sender].add(purchase);
if(amountRaised < fundingGoal)
{
purchase = purchase.mul(ZTR_ETH_initial_price);
amountRaised = amountRaised.add(msg.value);
balanceOf[msg.sender] = balanceOf[msg.sender].add(purchase);
remaining.sub(purchase);
}
else
{
purchase = purchase.mul(ZTR_ETH_extra_price);
amountRaised = amountRaised.add(msg.value);
balanceOf[msg.sender] = balanceOf[msg.sender].add(purchase);
remaining.sub(purchase);
}
}
function withdrawBeneficiary() public admin afterDeadline
{
ZTRToken t = ZTRToken(ZTRTokenContract);
t.transfer(msg.sender, remaining);
require(amountRaised >= fundingGoal);
owner.transfer(amountRaised);
}
function withdraw() afterDeadline
{
if(amountRaised < fundingGoal)
{
uint ethVal = ethBalance[msg.sender];
ethBalance[msg.sender] = 0;
msg.sender.transfer(ethVal);
}
else
{
uint tokenVal = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
ZTRToken t = ZTRToken(ZTRTokenContract);
t.transfer(msg.sender, tokenVal);
}
}
function setDeadline(uint ti) public admin
{
deadline = ti;
}
function setStart(uint ti) public admin
{
start = ti;
}
function suicide() public afterUnlock
{
selfdestruct(owner);
}
} | 1 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function () public payable {
revert();
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
function setSaleAgent(address newSaleAgnet) public {
require(msg.sender == saleAgent || msg.sender == owner);
saleAgent = newSaleAgnet;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require(msg.sender == saleAgent && !mintingFinished);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public returns (bool) {
require((msg.sender == saleAgent || msg.sender == owner) && !mintingFinished);
mintingFinished = true;
MintFinished();
return true;
}
}
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 VestarinToken is MintableToken {
string public constant name = "Vestarin";
string public constant symbol = "VST";
uint32 public constant decimals = 18;
mapping (address => uint) public locked;
function transfer(address _to, uint256 _value) public returns (bool) {
require(locked[msg.sender] < now);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(locked[_from] < now);
return super.transferFrom(_from, _to, _value);
}
function lock(address addr, uint periodInDays) public {
require(locked[addr] < now && (msg.sender == saleAgent || msg.sender == addr));
locked[addr] = now + periodInDays * 1 days;
}
}
contract StagedCrowdsale is Pausable {
using SafeMath for uint;
struct Stage {
uint hardcap;
uint price;
uint invested;
uint closed;
}
uint public start;
uint public period;
uint public totalHardcap;
uint public totalInvested;
Stage[] public stages;
function stagesCount() public constant returns(uint) {
return stages.length;
}
function setStart(uint newStart) public onlyOwner {
start = newStart;
}
function setPeriod(uint newPeriod) public onlyOwner {
period = newPeriod;
}
function addStage(uint hardcap, uint price) public onlyOwner {
require(hardcap > 0 && price > 0);
Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0);
stages.push(stage);
totalHardcap = totalHardcap.add(stage.hardcap);
}
function removeStage(uint8 number) public onlyOwner {
require(number >=0 && number < stages.length);
Stage storage stage = stages[number];
totalHardcap = totalHardcap.sub(stage.hardcap);
delete stages[number];
for (uint i = number; i < stages.length - 1; i++) {
stages[i] = stages[i+1];
}
stages.length--;
}
function changeStage(uint8 number, uint hardcap, uint price) public onlyOwner {
require(number >= 0 &&number < stages.length);
Stage storage stage = stages[number];
totalHardcap = totalHardcap.sub(stage.hardcap);
stage.hardcap = hardcap.mul(1 ether);
stage.price = price;
totalHardcap = totalHardcap.add(stage.hardcap);
}
function insertStage(uint8 numberAfter, uint hardcap, uint price) public onlyOwner {
require(numberAfter < stages.length);
Stage memory stage = Stage(hardcap.mul(1 ether), price, 0, 0);
totalHardcap = totalHardcap.add(stage.hardcap);
stages.length++;
for (uint i = stages.length - 2; i > numberAfter; i--) {
stages[i + 1] = stages[i];
}
stages[numberAfter + 1] = stage;
}
function clearStages() public onlyOwner {
for (uint i = 0; i < stages.length; i++) {
delete stages[i];
}
stages.length -= stages.length;
totalHardcap = 0;
}
function lastSaleDate() public constant returns(uint) {
return start + period * 1 days;
}
modifier saleIsOn() {
require(stages.length > 0 && now >= start && now < lastSaleDate());
_;
}
modifier isUnderHardcap() {
require(totalInvested <= totalHardcap);
_;
}
function currentStage() public saleIsOn isUnderHardcap constant returns(uint) {
for(uint i=0; i < stages.length; i++) {
if(stages[i].closed == 0) {
return i;
}
}
revert();
}
}
contract CommonSale is StagedCrowdsale {
address public masterWallet;
address public slaveWallet;
address public directMintAgent;
uint public slaveWalletPercent = 30;
uint public percentRate = 100;
uint public minPrice;
uint public totalTokensMinted;
bool public slaveWalletInitialized;
bool public slaveWalletPercentInitialized;
VestarinToken public token;
modifier onlyDirectMintAgentOrOwner() {
require(directMintAgent == msg.sender || owner == msg.sender);
_;
}
function setDirectMintAgent(address newDirectMintAgent) public onlyOwner {
directMintAgent = newDirectMintAgent;
}
function setMinPrice(uint newMinPrice) public onlyOwner {
minPrice = newMinPrice;
}
function setSlaveWalletPercent(uint newSlaveWalletPercent) public onlyOwner {
require(!slaveWalletPercentInitialized);
slaveWalletPercent = newSlaveWalletPercent;
slaveWalletPercentInitialized = true;
}
function setMasterWallet(address newMasterWallet) public onlyOwner {
masterWallet = newMasterWallet;
}
function setSlaveWallet(address newSlaveWallet) public onlyOwner {
require(!slaveWalletInitialized);
slaveWallet = newSlaveWallet;
slaveWalletInitialized = true;
}
function setToken(address newToken) public onlyOwner {
token = VestarinToken(newToken);
}
function directMint(address to, uint investedWei) public onlyDirectMintAgentOrOwner saleIsOn {
mintTokens(to, investedWei);
}
function createTokens() public whenNotPaused payable {
require(msg.value >= minPrice);
uint masterValue = msg.value.mul(percentRate.sub(slaveWalletPercent)).div(percentRate);
uint slaveValue = msg.value.sub(masterValue);
masterWallet.transfer(masterValue);
slaveWallet.transfer(slaveValue);
mintTokens(msg.sender, msg.value);
}
function mintTokens(address to, uint weiInvested) internal {
uint stageIndex = currentStage();
Stage storage stage = stages[stageIndex];
uint tokens = weiInvested.mul(stage.price);
token.mint(this, tokens);
token.transfer(to, tokens);
totalTokensMinted = totalTokensMinted.add(tokens);
totalInvested = totalInvested.add(weiInvested);
stage.invested = stage.invested.add(weiInvested);
if(stage.invested >= stage.hardcap) {
stage.closed = now;
}
}
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken, address to) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(to, alienToken.balanceOf(this));
}
}
contract Presale is CommonSale {
Mainsale public mainsale;
function setMainsale(address newMainsale) public onlyOwner {
mainsale = Mainsale(newMainsale);
}
function finishMinting() public whenNotPaused onlyOwner {
token.setSaleAgent(mainsale);
}
function() external payable {
createTokens();
}
}
contract Mainsale is CommonSale {
address public foundersTokensWallet;
address public bountyTokensWallet;
uint public foundersTokensPercent;
uint public bountyTokensPercent;
uint public lockPeriod;
function setLockPeriod(uint newLockPeriod) public onlyOwner {
lockPeriod = newLockPeriod;
}
function setFoundersTokensPercent(uint newFoundersTokensPercent) public onlyOwner {
foundersTokensPercent = newFoundersTokensPercent;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner {
bountyTokensPercent = newBountyTokensPercent;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) public onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner {
bountyTokensWallet = newBountyTokensWallet;
}
function finishMinting() public whenNotPaused onlyOwner {
uint summaryTokensPercent = bountyTokensPercent + foundersTokensPercent;
uint mintedTokens = token.totalSupply();
uint summaryFoundersTokens = mintedTokens.mul(summaryTokensPercent).div(percentRate.sub(summaryTokensPercent));
uint totalSupply = summaryFoundersTokens + mintedTokens;
uint foundersTokens = totalSupply.mul(foundersTokensPercent).div(percentRate);
uint bountyTokens = totalSupply.mul(bountyTokensPercent).div(percentRate);
token.mint(this, foundersTokens);
token.lock(foundersTokensWallet, lockPeriod * 1 days);
token.transfer(foundersTokensWallet, foundersTokens);
token.mint(this, bountyTokens);
token.transfer(bountyTokensWallet, bountyTokens);
totalTokensMinted = totalTokensMinted.add(foundersTokens).add(bountyTokens);
token.finishMinting();
}
}
contract TestConfigurator is Ownable {
VestarinToken public token;
Presale public presale;
Mainsale public mainsale;
function deploy() public onlyOwner {
owner = 0x445c94f566abF8E28739c474c572D356d03Ad999;
token = new VestarinToken();
presale = new Presale();
presale.setToken(token);
presale.addStage(5,300);
presale.setMasterWallet(0x055fa3f2DAc0b9Db661A4745965DDD65490d56A8);
presale.setSlaveWallet(0x055fa3f2DAc0b9Db661A4745965DDD65490d56A8);
presale.setSlaveWalletPercent(30);
presale.setStart(1510704000);
presale.setPeriod(1);
presale.setMinPrice(100000000000000000);
token.setSaleAgent(presale);
mainsale = new Mainsale();
mainsale.setToken(token);
mainsale.addStage(1,200);
mainsale.addStage(2,100);
mainsale.setMasterWallet(0x4d9014eF9C3CE5790A326775Bd9F609969d1BF4f);
mainsale.setSlaveWallet(0x4d9014eF9C3CE5790A326775Bd9F609969d1BF4f);
mainsale.setSlaveWalletPercent(30);
mainsale.setFoundersTokensWallet(0x59b398bBED1CC6c82b337B3Bd0ad7e4dCB7d4de3);
mainsale.setBountyTokensWallet(0x555635F2ea026ab65d7B44526539E0aB3874Ab24);
mainsale.setStart(1510790400);
mainsale.setPeriod(2);
mainsale.setLockPeriod(1);
mainsale.setMinPrice(100000000000000000);
mainsale.setFoundersTokensPercent(13);
mainsale.setBountyTokensPercent(5);
presale.setMainsale(mainsale);
token.transferOwnership(owner);
presale.transferOwnership(owner);
mainsale.transferOwnership(owner);
}
}
contract Configurator is Ownable {
VestarinToken public token;
Presale public presale;
Mainsale public mainsale;
function deploy() public onlyOwner {
owner = 0x95EA6A4ec9F80436854702e5F05d238f27166A03;
token = new VestarinToken();
presale = new Presale();
presale.setToken(token);
presale.addStage(5000,300);
presale.setMasterWallet(0x95EA6A4ec9F80436854702e5F05d238f27166A03);
presale.setSlaveWallet(0x070EcC35a3212D76ad443d529216a452eAA35E3D);
presale.setSlaveWalletPercent(30);
presale.setStart(1517317200);
presale.setPeriod(30);
presale.setMinPrice(100000000000000000);
token.setSaleAgent(presale);
mainsale = new Mainsale();
mainsale.setToken(token);
mainsale.addStage(5000,200);
mainsale.addStage(5000,180);
mainsale.addStage(10000,170);
mainsale.addStage(20000,160);
mainsale.addStage(20000,150);
mainsale.addStage(40000,130);
mainsale.setMasterWallet(0x95EA6A4ec9F80436854702e5F05d238f27166A03);
mainsale.setSlaveWallet(0x070EcC35a3212D76ad443d529216a452eAA35E3D);
mainsale.setSlaveWalletPercent(30);
mainsale.setFoundersTokensWallet(0x95EA6A4ec9F80436854702e5F05d238f27166A03);
mainsale.setBountyTokensWallet(0x95EA6A4ec9F80436854702e5F05d238f27166A03);
mainsale.setStart(1525352400);
mainsale.setPeriod(30);
mainsale.setLockPeriod(90);
mainsale.setMinPrice(100000000000000000);
mainsale.setFoundersTokensPercent(13);
mainsale.setBountyTokensPercent(5);
presale.setMainsale(mainsale);
token.transferOwnership(owner);
presale.transferOwnership(owner);
mainsale.transferOwnership(owner);
}
} | 0 |
pragma solidity ^0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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 CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract ChronosAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
function ChronosAccessControl() public {
cfoAddress = msg.sender;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
}
contract ChronosBase is ChronosAccessControl {
using SafeMath for uint256;
uint256[] public activeTimesFrom;
uint256[] public activeTimesTo;
bool public allowStart;
bool public gameStarted;
address public lastPlayer;
uint256 public lastWagerTimeoutTimestamp;
uint256 public timeout;
uint256 public nextTimeout;
uint256 public finalTimeout;
uint256 public nextFinalTimeout;
uint256 public numberOfWagersToFinalTimeout;
uint256 public nextNumberOfWagersToFinalTimeout;
uint256 public gameIndex = 0;
uint256 public wagerIndex = 0;
uint256 public nthWagerPrizeN = 3;
function canStart() public view returns (bool) {
uint256 timeOfWeek = (block.timestamp - 345600) % 604800;
uint256 windows = activeTimesFrom.length;
if (windows == 0) {
return true;
}
for (uint256 i = 0; i < windows; i++) {
if (timeOfWeek >= activeTimesFrom[i] && timeOfWeek <= activeTimesTo[i]) {
return true;
}
}
return false;
}
function calculateTimeout() public view returns(uint256) {
if (wagerIndex >= numberOfWagersToFinalTimeout || numberOfWagersToFinalTimeout == 0) {
return finalTimeout;
} else {
if (finalTimeout <= timeout) {
uint256 difference = timeout - finalTimeout;
uint256 decrease = difference.mul(wagerIndex).div(numberOfWagersToFinalTimeout);
return (timeout - decrease);
} else {
difference = finalTimeout - timeout;
uint256 increase = difference.mul(wagerIndex).div(numberOfWagersToFinalTimeout);
return (timeout + increase);
}
}
}
}
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 ChronosFinance is ChronosBase, PullPayment {
uint256 public feePercentage = 2500;
uint256 public nextPoolPercentage = 7500;
uint256 public price;
uint256 public nextPrice;
uint256 public prizePool;
uint256 public nextPrizePool;
uint256 public wagerPool;
function setFeePercentage(uint256 _feePercentage) external onlyCFO {
require(_feePercentage <= 4000);
feePercentage = _feePercentage;
}
function setNextPoolPercentage(uint256 _nextPoolPercentage) external onlyCFO {
nextPoolPercentage = _nextPoolPercentage;
}
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
function withdrawFreeBalance() external onlyCFO {
uint256 freeBalance = this.balance.sub(totalPayments).sub(prizePool).sub(wagerPool);
cfoAddress.transfer(freeBalance);
}
}
contract ChronosCore is ChronosFinance {
function ChronosCore(uint256 _price, uint256 _timeout, uint256 _finalTimeout, uint256 _numberOfWagersToFinalTimeout) public {
nextPrice = _price;
nextTimeout = _timeout;
nextFinalTimeout = _finalTimeout;
nextNumberOfWagersToFinalTimeout = _numberOfWagersToFinalTimeout;
NextGame(nextPrice, nextTimeout, nextFinalTimeout, nextNumberOfWagersToFinalTimeout);
}
event ActiveTimes(uint256[] from, uint256[] to);
event AllowStart(bool allowStart);
event NextGame(uint256 price, uint256 timeout, uint256 finalTimeout, uint256 numberOfWagersToFinalTimeout);
event Start(uint256 indexed gameIndex, address indexed starter, uint256 timestamp, uint256 price, uint256 timeout, uint256 finalTimeout, uint256 numberOfWagersToFinalTimeout);
event End(uint256 indexed gameIndex, uint256 wagerIndex, address indexed winner, uint256 timestamp, uint256 prize, uint256 nextPrizePool);
event Play(uint256 indexed gameIndex, uint256 indexed wagerIndex, address indexed player, uint256 timestamp, uint256 timeoutTimestamp, uint256 newPrizePool, uint256 nextPrizePool);
event SpiceUpPrizePool(uint256 indexed gameIndex, address indexed spicer, uint256 spiceAdded, string message, uint256 newPrizePool);
function play(uint256 _gameIndex, bool startNewGameIfIdle) external payable {
_processGameEnd();
if (!gameStarted) {
require(!paused);
if (allowStart) {
allowStart = false;
} else {
require(canStart());
}
require(startNewGameIfIdle);
price = nextPrice;
timeout = nextTimeout;
finalTimeout = nextFinalTimeout;
numberOfWagersToFinalTimeout = nextNumberOfWagersToFinalTimeout;
gameStarted = true;
Start(gameIndex, msg.sender, block.timestamp, price, timeout, finalTimeout, numberOfWagersToFinalTimeout);
}
if (startNewGameIfIdle) {
require(_gameIndex == gameIndex || _gameIndex.add(1) == gameIndex);
} else {
require(_gameIndex == gameIndex);
}
require(msg.value >= price);
uint256 fee = price.mul(feePercentage).div(100000);
uint256 nextPool = price.mul(nextPoolPercentage).div(100000);
uint256 wagerPoolPart;
if (wagerIndex % nthWagerPrizeN == nthWagerPrizeN - 1) {
uint256 wagerPrize = price.mul(2);
wagerPoolPart = wagerPrize.sub(wagerPool);
msg.sender.transfer(wagerPrize);
wagerPool = 0;
} else {
wagerPoolPart = price.mul(2).div(nthWagerPrizeN);
wagerPool = wagerPool.add(wagerPoolPart);
}
uint256 currentTimeout = calculateTimeout();
lastPlayer = msg.sender;
lastWagerTimeoutTimestamp = block.timestamp + currentTimeout;
prizePool = prizePool.add(price.sub(fee).sub(nextPool).sub(wagerPoolPart));
nextPrizePool = nextPrizePool.add(nextPool);
Play(gameIndex, wagerIndex, msg.sender, block.timestamp, lastWagerTimeoutTimestamp, prizePool, nextPrizePool);
wagerIndex++;
uint256 excess = msg.value - price;
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function spiceUp(uint256 _gameIndex, string message) external payable {
_processGameEnd();
require(_gameIndex == gameIndex);
require(gameStarted || !paused);
require(msg.value > 0);
prizePool = prizePool.add(msg.value);
SpiceUpPrizePool(gameIndex, msg.sender, msg.value, message, prizePool);
}
function setNextGame(uint256 _price, uint256 _timeout, uint256 _finalTimeout, uint256 _numberOfWagersToFinalTimeout) external onlyCFO {
nextPrice = _price;
nextTimeout = _timeout;
nextFinalTimeout = _finalTimeout;
nextNumberOfWagersToFinalTimeout = _numberOfWagersToFinalTimeout;
NextGame(nextPrice, nextTimeout, nextFinalTimeout, nextNumberOfWagersToFinalTimeout);
}
function endGame() external {
require(_processGameEnd());
}
function _processGameEnd() internal returns(bool) {
if (!gameStarted) {
return false;
}
if (block.timestamp <= lastWagerTimeoutTimestamp) {
return false;
}
uint256 prize = prizePool.add(wagerPool);
_sendFunds(lastPlayer, prize);
End(gameIndex, wagerIndex, lastPlayer, lastWagerTimeoutTimestamp, prize, nextPrizePool);
gameStarted = false;
lastPlayer = 0x0;
lastWagerTimeoutTimestamp = 0;
wagerIndex = 0;
wagerPool = 0;
prizePool = nextPrizePool;
nextPrizePool = 0;
gameIndex++;
return true;
}
function setActiveTimes(uint256[] _from, uint256[] _to) external onlyCFO {
require(_from.length == _to.length);
activeTimesFrom = _from;
activeTimesTo = _to;
ActiveTimes(_from, _to);
}
function setAllowStart(bool _allowStart) external onlyCFO {
allowStart = _allowStart;
AllowStart(_allowStart);
}
} | 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 BallotSB52 {
using SafeMath for uint;
uint public phiWon;
uint public neWon;
Superbowl52 bettingContract;
mapping (address => bool) voted;
mapping (address => uint) votes;
uint public constant votingPeriod = 7 days;
uint public votingStart;
uint public votingEnd;
uint public validResult;
bool public closed;
uint public totalVoters;
uint public threshold;
uint public votingReward;
mapping (address => uint) stake;
uint public majorityReward;
bool public tie;
mapping (address => bool) claimed;
function BallotSB52(uint th) public payable {
validResult = 0;
closed = false;
votingStart = now;
votingEnd = now + 7 days;
bettingContract = Superbowl52(msg.sender);
totalVoters = 0;
threshold = th;
tie = false;
votingReward = 0;
}
function voteResult(uint team) public payable {
require(votingStart <= now && votingEnd >= now);
require(voted[msg.sender] == false);
require(msg.value == 50 finney);
require(!closed);
if(team == 1) {
phiWon += 1;
}
else if (team == 2) {
neWon += 1;
} else revert();
voted[msg.sender] = true;
votes[msg.sender] = team;
totalVoters += 1;
stake[msg.sender] = msg.value;
}
function closeBallot() public returns (uint) {
require(!closed);
require(now > votingEnd);
if(phiWon.mul(100000).div(totalVoters) >= threshold) {
validResult = 1;
votingReward = bettingContract.getLosersOnePercent(2);
majorityReward = (neWon * 50 finney).add(votingReward).div(phiWon);
} else if (neWon.mul(100000).div(totalVoters) >= threshold) {
validResult = 2;
votingReward = bettingContract.getLosersOnePercent(3);
majorityReward = (phiWon * 50 finney).add(votingReward).div(neWon);
} else {
if (neWon.mul(100000).div(totalVoters) > 50000) majorityReward = (phiWon * 50 finney).div(neWon);
else if (phiWon.mul(100000).div(totalVoters) > 50000) majorityReward = (neWon * 50 finney).div(phiWon);
else {
tie = true;
majorityReward = 0;
}
validResult = 0;
}
closed = true;
return validResult;
}
function getReward(address voter) public {
require(closed);
require(voted[voter]);
require(claimed[voter] == false);
if(tie) {
voter.transfer(stake[voter]);
}
if(votes[voter] == validResult) {
voter.transfer(stake[voter] + majorityReward);
}
claimed[voter] = true;
}
function hasClaimed(address voter) public constant returns (bool) {
return claimed[voter];
}
function () public payable {}
}
contract Superbowl52 {
using SafeMath for uint;
uint public constant GAME_START_TIME = 1517787000;
bool public resultConfirmed = false;
address public owner;
mapping(address => betting) public bets;
uint public totalBets;
uint public philadelphiaBets;
uint public newEnglandBets;
uint public result;
uint public betters;
bool public votingOpen;
bool public withdrawalOpen;
uint public threshold;
uint public winningPot;
mapping(address => uint) public wins;
BallotSB52 public ballot;
struct betting {
uint philadelphiaBets;
uint newEnglandBets;
bool claimed;
}
function Superbowl52() public {
require(now<GAME_START_TIME);
owner = msg.sender;
result = 0;
votingOpen = false;
withdrawalOpen = false;
threshold = 90000;
winningPot = 0;
}
function bet(uint team) public payable {
require(team == 1 || team == 2);
require(now <= GAME_START_TIME);
require(msg.value > 0);
if(!hasBet(msg.sender)) betters += 1;
if(team == 1) {
bets[msg.sender].philadelphiaBets += msg.value;
philadelphiaBets += msg.value;
} else if (team == 2) {
bets[msg.sender].newEnglandBets += msg.value;
newEnglandBets += msg.value;
}
totalBets += msg.value;
}
function () public payable {
revert();
}
function getPhiladelphiaBets(address better) public constant returns (uint) {
return bets[better].philadelphiaBets;
}
function getNewEnglandBets(address better) public constant returns (uint) {
return bets[better].newEnglandBets;
}
function hasClaimed(address better) public constant returns (bool) {
return bets[better].claimed;
}
function startVoting() public {
require(msg.sender == owner);
require(votingOpen == false);
require(withdrawalOpen == false);
require(now >= GAME_START_TIME + 8 hours);
votingOpen = true;
ballot = new BallotSB52(threshold);
}
function hasBet(address better) public constant returns (bool) {
return (bets[better].philadelphiaBets + bets[better].newEnglandBets) > 0;
}
function endVoting() public {
require(votingOpen);
result = ballot.closeBallot();
if (result == 1 || result == 2) {
withdrawalOpen = true;
votingOpen = false;
} else {
threshold = threshold - 5000;
ballot = new BallotSB52(threshold);
}
if(result == 1) winningPot = totalBets.sub(newEnglandBets.div(100));
if(result == 2) winningPot = totalBets.sub(philadelphiaBets.div(100));
}
function getLosersOnePercent(uint loser) public returns (uint) {
require(votingOpen);
require(msg.sender == address(ballot));
if(loser==1) {
ballot.transfer(philadelphiaBets.div(100));
return philadelphiaBets.div(100);
}
else if (loser==2) {
ballot.transfer(newEnglandBets.div(100));
return newEnglandBets.div(100);
}
else {
return 0;
}
}
function getWinnings(address winner, uint donation) public {
require(donation<=100);
require(withdrawalOpen);
require(bets[winner].claimed == false);
uint winnings = 0;
if (result == 1) winnings = (getPhiladelphiaBets(winner).mul(winningPot)).div(philadelphiaBets);
else if (result == 2) winnings = (getNewEnglandBets(winner).mul(winningPot)).div(newEnglandBets);
else revert();
wins[winner] = winnings;
uint donated = winnings.mul(donation).div(100);
bets[winner].claimed = true;
winner.transfer(winnings-donated);
}
} | 0 |
pragma solidity ^0.4.25;
contract token {
function transfer(address receiver, uint256 amount) public;
function balanceOf(address _owner) public view returns (uint256 balance);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract GenjiCrowdsale is owned{
using SafeMath for uint256;
address public beneficiary;
uint256 public amountRaised;
uint256 public preSaleStartdate;
uint256 public preSaleDeadline;
uint256 public mainSaleStartdate;
uint256 public mainSaleDeadline;
uint256 public preSalePrice;
uint256 public price;
uint256 public fundTransferred;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool crowdsaleClosed = false;
constructor() public{
beneficiary = 0xBCEb3a1Ff8dF1eD574bdEeBf8c2feEf47351Ba42;
preSaleStartdate = 1563580800;
preSaleDeadline = 1564617599;
mainSaleStartdate = 1564617600;
mainSaleDeadline = 1567641599;
preSalePrice = 0.00002345 ether;
price = 0.0000335 ether;
tokenReward = token(0xb49b4d400D66AAa53ec07184A8C7c6C9c23374c9);
}
function () payable external {
require(!crowdsaleClosed);
uint256 bonus;
uint256 amount;
uint256 ethamount = msg.value;
balanceOf[msg.sender] = balanceOf[msg.sender].add(ethamount);
amountRaised = amountRaised.add(ethamount);
if(now >= preSaleStartdate && now <= preSaleDeadline){
amount = ethamount.div(preSalePrice);
bonus = amount * 50 / 100;
amount = amount.add(bonus);
}
else if(now >= mainSaleStartdate && now <= mainSaleStartdate + 1 weeks){
amount = ethamount.div(price);
bonus = amount * 40/100;
amount = amount.add(bonus);
}
else if(now >= mainSaleStartdate + 1 weeks && now <= mainSaleStartdate + 2 weeks){
amount = ethamount.div(price);
bonus = amount * 33/100;
amount = amount.add(bonus);
}
else if(now >= mainSaleStartdate + 2 weeks && now <= mainSaleStartdate + 3 weeks){
amount = ethamount.div(price);
bonus = amount * 25/100;
amount = amount.add(bonus);
}
else if(now >= mainSaleStartdate + 3 weeks && now <= mainSaleStartdate + 4 weeks){
amount = ethamount.div(price);
bonus = amount * 15/100;
amount = amount.add(bonus);
}
else {
amount = ethamount.div(price);
bonus = amount * 8/100;
amount = amount.add(bonus);
}
amount = amount.mul(1000000000000000000);
tokenReward.transfer(msg.sender, amount);
beneficiary.transfer(ethamount);
fundTransferred = fundTransferred.add(ethamount);
}
modifier afterDeadline() { if (now >= mainSaleDeadline) _; }
function endCrowdsale() public afterDeadline onlyOwner {
crowdsaleClosed = true;
}
function ChangepreSalePrice(uint256 _preSalePrice) public onlyOwner {
preSalePrice = _preSalePrice;
}
function ChangePrice(uint256 _price) public onlyOwner {
price = _price;
}
function ChangeBeneficiary(address _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
function ChangeDates(uint256 _preSaleStartdate, uint256 _preSaleDeadline, uint256 _mainSaleStartdate, uint256 _mainSaleDeadline) public onlyOwner {
if(_preSaleStartdate != 0){
preSaleStartdate = _preSaleStartdate;
}
if(_preSaleDeadline != 0){
preSaleDeadline = _preSaleDeadline;
}
if(_mainSaleStartdate != 0){
mainSaleStartdate = _mainSaleStartdate;
}
if(_mainSaleDeadline != 0){
mainSaleDeadline = _mainSaleDeadline;
}
if(crowdsaleClosed == true){
crowdsaleClosed = false;
}
}
function getTokensBack() public onlyOwner {
uint256 remaining = tokenReward.balanceOf(this);
tokenReward.transfer(beneficiary, remaining);
}
} | 0 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner,address indexed newOwner);
constructor() public { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ZapCoordinatorInterface is Ownable {
function addImmutableContract(string contractName, address newAddress) external;
function updateContract(string contractName, address newAddress) external;
function getContractName(uint index) public view returns (string);
function getContract(string contractName) public view returns (address);
function updateAllDependencies() external;
}
pragma solidity ^0.4.24;
contract Upgradable {
address coordinatorAddr;
ZapCoordinatorInterface coordinator;
constructor(address c) public{
coordinatorAddr = c;
coordinator = ZapCoordinatorInterface(c);
}
function updateDependencies() external coordinatorOnly {
_updateDependencies();
}
function _updateDependencies() internal;
modifier coordinatorOnly() {
require(msg.sender == coordinatorAddr, "Error: Coordinator Only Function");
_;
}
}
contract Destructible is Ownable {
function selfDestruct() public onlyOwner {
selfdestruct(owner);
}
}
contract Client1 {
function callback(uint256 id, string response1) external;
}
contract Client2 {
function callback(uint256 id, string response1, string response2) external;
}
contract Client3 {
function callback(uint256 id, string response1, string response2, string response3) external;
}
contract Client4 {
function callback(uint256 id, string response1, string response2, string response3, string response4) external;
}
contract ClientBytes32Array {
function callback(uint256 id, bytes32[] response) external;
}
contract ClientIntArray{
function callback(uint256 id, int[] response) external;
}
contract OnChainProvider {
function receive(uint256 id, string userQuery, bytes32 endpoint, bytes32[] endpointParams, bool onchainSubscriber) external;
}
contract BondageInterface {
function bond(address, bytes32, uint256) external returns(uint256);
function unbond(address, bytes32, uint256) external returns (uint256);
function delegateBond(address, address, bytes32, uint256) external returns(uint256);
function escrowDots(address, address, bytes32, uint256) external returns (bool);
function releaseDots(address, address, bytes32, uint256) external returns (bool);
function returnDots(address, address, bytes32, uint256) external returns (bool success);
function calcZapForDots(address, bytes32, uint256) external view returns (uint256);
function currentCostOfDot(address, bytes32, uint256) public view returns (uint256);
function getDotsIssued(address, bytes32) public view returns (uint256);
function getBoundDots(address, address, bytes32) public view returns (uint256);
function getZapBound(address, bytes32) public view returns (uint256);
function dotLimit( address, bytes32) public view returns (uint256);
}
interface DispatchInterface {
function query(address, string, bytes32, bytes32[]) external returns (uint256);
function respond1(uint256, string) external returns (bool);
function respond2(uint256, string, string) external returns (bool);
function respond3(uint256, string, string, string) external returns (bool);
function respond4(uint256, string, string, string, string) external returns (bool);
function respondBytes32Array(uint256, bytes32[]) external returns (bool);
function respondIntArray(uint256,int[] ) external returns (bool);
function cancelQuery(uint256) external;
function getProvider(uint256 id) public view returns (address);
function getSubscriber(uint256 id) public view returns (address);
function getEndpoint(uint256 id) public view returns (bytes32);
function getStatus(uint256 id) public view returns (uint256);
function getCancel(uint256 id) public view returns (uint256);
function getUserQuery(uint256 id) public view returns (string);
function getSubscriberOnchain(uint256 id) public view returns (bool);
}
contract DatabaseInterface is Ownable {
function setStorageContract(address _storageContract, bool _allowed) public;
function getBytes32(bytes32 key) external view returns(bytes32);
function setBytes32(bytes32 key, bytes32 value) external;
function getNumber(bytes32 key) external view returns(uint256);
function setNumber(bytes32 key, uint256 value) external;
function getBytes(bytes32 key) external view returns(bytes);
function setBytes(bytes32 key, bytes value) external;
function getString(bytes32 key) external view returns(string);
function setString(bytes32 key, string value) external;
function getBytesArray(bytes32 key) external view returns (bytes32[]);
function getBytesArrayIndex(bytes32 key, uint256 index) external view returns (bytes32);
function getBytesArrayLength(bytes32 key) external view returns (uint256);
function pushBytesArray(bytes32 key, bytes32 value) external;
function setBytesArrayIndex(bytes32 key, uint256 index, bytes32 value) external;
function setBytesArray(bytes32 key, bytes32[] value) external;
function getIntArray(bytes32 key) external view returns (int[]);
function getIntArrayIndex(bytes32 key, uint256 index) external view returns (int);
function getIntArrayLength(bytes32 key) external view returns (uint256);
function pushIntArray(bytes32 key, int value) external;
function setIntArrayIndex(bytes32 key, uint256 index, int value) external;
function setIntArray(bytes32 key, int[] value) external;
function getAddressArray(bytes32 key) external view returns (address[]);
function getAddressArrayIndex(bytes32 key, uint256 index) external view returns (address);
function getAddressArrayLength(bytes32 key) external view returns (uint256);
function pushAddressArray(bytes32 key, address value) external;
function setAddressArrayIndex(bytes32 key, uint256 index, address value) external;
function setAddressArray(bytes32 key, address[] value) external;
}
contract Dispatch is Destructible, DispatchInterface, Upgradable {
enum Status { Pending, Fulfilled, Canceled }
event Incoming(
uint256 indexed id,
address indexed provider,
address indexed subscriber,
string query,
bytes32 endpoint,
bytes32[] endpointParams,
bool onchainSubscriber
);
event FulfillQuery(
address indexed subscriber,
address indexed provider,
bytes32 indexed endpoint
);
event OffchainResponse(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
bytes32[] response
);
event OffchainResponseInt(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
int[] response
);
event OffchainResult1(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
string response1
);
event OffchainResult2(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
string response1,
string response2
);
event OffchainResult3(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
string response1,
string response2,
string response3
);
event OffchainResult4(
uint256 indexed id,
address indexed subscriber,
address indexed provider,
string response1,
string response2,
string response3,
string response4
);
event CanceledRequest(
uint256 indexed id,
address indexed subscriber,
address indexed provider
);
event RevertCancelation(
uint256 indexed id,
address indexed subscriber,
address indexed provider
);
BondageInterface public bondage;
address public bondageAddress;
DatabaseInterface public db;
constructor(address c) Upgradable(c) public {
}
function _updateDependencies() internal {
address databaseAddress = coordinator.getContract("DATABASE");
db = DatabaseInterface(databaseAddress);
bondageAddress = coordinator.getContract("BONDAGE");
bondage = BondageInterface(bondageAddress);
}
function query(
address provider,
string userQuery,
bytes32 endpoint,
bytes32[] endpointParams
)
external
returns (uint256 id)
{
uint256 dots = bondage.getBoundDots(msg.sender, provider, endpoint);
bool onchainProvider = isContract(provider);
bool onchainSubscriber = isContract(msg.sender);
if(dots >= 1) {
bondage.escrowDots(msg.sender, provider, endpoint, 1);
id = uint256(keccak256(abi.encodePacked(block.number, now, userQuery, msg.sender, provider)));
createQuery(id, provider, msg.sender, endpoint, userQuery, onchainSubscriber);
if(onchainProvider) {
OnChainProvider(provider).receive(id, userQuery, endpoint, endpointParams, onchainSubscriber);
} else{
emit Incoming(id, provider, msg.sender, userQuery, endpoint, endpointParams, onchainSubscriber);
}
} else {
revert("Subscriber does not have any dots.");
}
}
function fulfillQuery(uint256 id) private returns (bool) {
Status status = Status(getStatus(id));
require(status != Status.Fulfilled, "Error: Status already fulfilled");
address subscriber = getSubscriber(id);
address provider = getProvider(id);
bytes32 endpoint = getEndpoint(id);
if ( status == Status.Canceled ) {
uint256 canceled = getCancel(id);
require(block.number == canceled, "Error: Cancel ignored");
setCanceled(id, false);
bondage.escrowDots(subscriber, provider, endpoint, 1);
emit RevertCancelation(id, subscriber, provider);
}
setFulfilled(id);
bondage.releaseDots(subscriber, provider, endpoint, 1);
emit FulfillQuery(subscriber, provider, endpoint);
return true;
}
function cancelQuery(uint256 id) external {
address subscriber = getSubscriber(id);
address provider = getProvider(id);
bytes32 endpoint = getEndpoint(id);
require(subscriber == msg.sender, "Error: Wrong subscriber");
require(Status(getStatus(id)) == Status.Pending, "Error: Query is not pending");
setCanceled(id, true);
bondage.returnDots(subscriber, provider, endpoint, 1);
emit CanceledRequest(id, getSubscriber(id), getProvider(id));
}
function respondBytes32Array(
uint256 id,
bytes32[] response
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
ClientBytes32Array(getSubscriber(id)).callback(id, response);
}
else {
emit OffchainResponse(id, getSubscriber(id), msg.sender, response);
}
return true;
}
function respondIntArray(
uint256 id,
int[] response
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
ClientIntArray(getSubscriber(id)).callback(id, response);
}
else {
emit OffchainResponseInt(id, getSubscriber(id), msg.sender, response);
}
return true;
}
function respond1(
uint256 id,
string response
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
Client1(getSubscriber(id)).callback(id, response);
}
else {
emit OffchainResult1(id, getSubscriber(id), msg.sender, response);
}
return true;
}
function respond2(
uint256 id,
string response1,
string response2
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
Client2(getSubscriber(id)).callback(id, response1, response2);
}
else {
emit OffchainResult2(id, getSubscriber(id), msg.sender, response1, response2);
}
return true;
}
function respond3(
uint256 id,
string response1,
string response2,
string response3
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
Client3(getSubscriber(id)).callback(id, response1, response2, response3);
}
else {
emit OffchainResult3(id, getSubscriber(id), msg.sender, response1, response2, response3);
}
return true;
}
function respond4(
uint256 id,
string response1,
string response2,
string response3,
string response4
)
external
returns (bool)
{
if (getProvider(id) != msg.sender || !fulfillQuery(id))
revert();
if(getSubscriberOnchain(id)) {
Client4(getSubscriber(id)).callback(id, response1, response2, response3, response4);
}
else {
emit OffchainResult4(id, getSubscriber(id), msg.sender, response1, response2, response3, response4);
}
return true;
}
function getProvider(uint256 id) public view returns (address) {
return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'provider'))));
}
function getSubscriber(uint256 id) public view returns (address) {
return address(db.getNumber(keccak256(abi.encodePacked('queries', id, 'subscriber'))));
}
function getEndpoint(uint256 id) public view returns (bytes32) {
return db.getBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint')));
}
function getStatus(uint256 id) public view returns (uint256) {
return db.getNumber(keccak256(abi.encodePacked('queries', id, 'status')));
}
function getCancel(uint256 id) public view returns (uint256) {
return db.getNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')));
}
function getUserQuery(uint256 id) public view returns (string) {
return db.getString(keccak256(abi.encodePacked('queries', id, 'userQuery')));
}
function getSubscriberOnchain(uint256 id) public view returns (bool) {
uint res = db.getNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber')));
return res == 1 ? true : false;
}
function createQuery(
uint256 id,
address provider,
address subscriber,
bytes32 endpoint,
string userQuery,
bool onchainSubscriber
)
private
{
db.setNumber(keccak256(abi.encodePacked('queries', id, 'provider')), uint256(provider));
db.setNumber(keccak256(abi.encodePacked('queries', id, 'subscriber')), uint256(subscriber));
db.setBytes32(keccak256(abi.encodePacked('queries', id, 'endpoint')), endpoint);
db.setString(keccak256(abi.encodePacked('queries', id, 'userQuery')), userQuery);
db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending));
db.setNumber(keccak256(abi.encodePacked('queries', id, 'onchainSubscriber')), onchainSubscriber ? 1 : 0);
}
function setFulfilled(uint256 id) private {
db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Fulfilled));
}
function setCanceled(uint256 id, bool canceled) private {
if ( canceled ) {
db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), block.number);
db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Canceled));
}
else {
db.setNumber(keccak256(abi.encodePacked('queries', id, 'cancelBlock')), 0);
db.setNumber(keccak256(abi.encodePacked('queries', id, 'status')), uint256(Status.Pending));
}
}
function isContract(address addr) private view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
} | 0 |
pragma solidity ^0.4.13;
contract DaoToken {
uint256 public CAP;
uint256 public totalEthers;
function proxyPayment(address participant) payable;
function transfer(address _to, uint _amount) returns (bool success);
}
contract ZiberToken {
mapping (address => uint256) public balances;
mapping (address => bool) public checked_in;
uint256 public ico;
bool public bought_tokens;
uint256 public time_bought;
uint256 public extra_time_bought;
bool public kill_switch;
string public name;
string public symbol;
uint8 public decimals;
uint256 ZBR_per_eth = 17440;
uint256 ZBR_total_reserve = 100000000;
uint256 ZBR_dev_reserved = 10000000;
uint256 ZBR_for_selling = 80000000;
uint256 ZBR_for_ico= 10000000;
uint256 min_eth_to_end = 50000 ether;
uint256 max_eth_to_end = 100000 ether;
uint registredTo;
uint256 loadedRefund;
uint256 _supply;
string _name;
string _symbol;
uint8 _decimals;
DaoToken public token = DaoToken(0xa9d585CE3B227d69985c3F7A866fE7d0e510da50);
address developer_address = 0x004B74Ea737AFD25ce083573fB45a49da762aCD4;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function ZiberToken() {
_supply = 10000000000;
balanceOf[msg.sender] = _supply;
name = "ZIBER LTD Crowdsale Tokens";
symbol = "ZBR";
decimals = 2;
}
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
function loadRefund() payable {
if(msg.value == 0) throw;
loadedRefund = safeAdd(loadedRefund, msg.value);
}
function refund() private {
uint256 weiValue = this.balance;
if (weiValue == 0) throw;
uint256 weiRefunded;
weiRefunded = safeAdd(weiRefunded, weiValue);
refund();
if (!msg.sender.send(weiValue)) throw;
}
function transfer(address _to, uint256 _value) {
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function activate_kill_switch() {
if (msg.sender != developer_address) throw;
kill_switch = true;
}
function withdraw(){
if (!bought_tokens) {
uint256 eth_amount = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(eth_amount);
}
else {
uint256 ZBR_amount = balances[msg.sender] * ZBR_per_eth;
balances[msg.sender] = 0;
uint256 fee = 0;
if (!checked_in[msg.sender]) {
fee = ZBR_amount / 100;
if(!token.transfer(developer_address, fee)) throw;
}
if(!token.transfer(msg.sender, ZBR_amount - fee)) throw;
}
}
function add_to_ico() payable {
if (msg.sender != developer_address) throw;
if (kill_switch) throw;
if (bought_tokens) throw;
ico += msg.value;
}
function claim_ico(){
if (bought_tokens) return;
if (kill_switch) throw;
bought_tokens = true;
time_bought = now + 1 days;
token.proxyPayment.value(this.balance - ico)(address(this));
if(this.balance > max_eth_to_end)
{
msg.sender.transfer(ico);
}
else {
extra_time_bought = now + 1 days * 10;
if(this.balance < min_eth_to_end) throw;
else {
if (now > extra_time_bought) {
msg.sender.transfer(ico);
}
}
}
}
modifier onlyOwner() {
if (msg.sender != developer_address) {
throw;
}
_;
}
function withdrawEth() onlyOwner {
msg.sender.transfer(this.balance);
}
function kill() onlyOwner {
selfdestruct(developer_address);
}
function default_helper() payable {
if (now < 1500655200 ) throw;
else {
if (msg.value <= 1 finney) {
if (bought_tokens) {
if (token.totalEthers() >= token.CAP()) throw;
checked_in[msg.sender] = true;
}
else {
withdraw();
}
}
else {
if (kill_switch) throw;
if (bought_tokens) throw;
balances[msg.sender] += msg.value;
}
}
}
function () payable {
default_helper();
}
} | 0 |
pragma solidity ^0.4.21;
contract Owned {
address public owner;
address public newOwner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract ReentrancyHandlingContract{
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
}
contract KycContractInterface {
function isAddressVerified(address _address) public view returns (bool);
}
contract MintingContractInterface {
address public crowdsaleContractAddress;
address public tokenContractAddress;
uint public tokenTotalSupply;
event MintMade(address _to, uint _ethAmount, uint _tokensMinted, string _message);
function doPresaleMinting(address _destination, uint _tokensAmount) public;
function doCrowdsaleMinting(address _destination, uint _tokensAmount) public;
function doTeamMinting(address _destination) public;
function setTokenContractAddress(address _newAddress) public;
function setCrowdsaleContractAddress(address _newAddress) public;
function killContract() public;
}
contract ERC20TokenInterface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function 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 Crowdsale is ReentrancyHandlingContract, Owned {
enum state { pendingStart, crowdsale, crowdsaleEnded }
struct ContributorData {
uint contributionAmount;
uint tokensIssued;
}
state public crowdsaleState = state.pendingStart;
address public multisigAddress = 0x0;
address public kycAddress = 0x0;
address public mintingContractAddress = 0x0;
uint public startPhaseLength = 720;
uint public startPhaseMaximumcontribution = 10 * 10**18;
uint public crowdsaleStartBlock;
uint public crowdsaleEndedBlock;
mapping(address => ContributorData) public contributorList;
uint nextContributorIndex;
mapping(uint => address) contributorIndexes;
uint public minCap;
uint public maxCap;
uint public ethRaised;
uint public tokensIssued = 0;
event CrowdsaleStarted(uint blockNumber);
event CrowdsaleEnded(uint blockNumber);
event ErrorSendingETH(address to, uint amount);
event MinCapReached(uint blockNumber);
event MaxCapReached(uint blockNumber);
uint nextContributorToClaim;
mapping(address => bool) hasClaimedEthWhenFail;
function() noReentrancy payable public {
require(msg.value >= 100000000000000000);
require(crowdsaleState != state.crowdsaleEnded);
require(KycContractInterface(kycAddress).isAddressVerified(msg.sender));
bool stateChanged = checkCrowdsaleState();
if (crowdsaleState == state.crowdsale) {
processTransaction(msg.sender, msg.value);
} else {
refundTransaction(stateChanged);
}
}
function checkCrowdsaleState() internal returns (bool) {
if (tokensIssued == maxCap && crowdsaleState != state.crowdsaleEnded) {
crowdsaleState = state.crowdsaleEnded;
emit CrowdsaleEnded(block.number);
return true;
}
if (block.number >= crowdsaleStartBlock && block.number <= crowdsaleEndedBlock) {
if (crowdsaleState != state.crowdsale) {
crowdsaleState = state.crowdsale;
emit CrowdsaleStarted(block.number);
return true;
}
} else {
if (crowdsaleState != state.crowdsaleEnded && block.number > crowdsaleEndedBlock) {
crowdsaleState = state.crowdsaleEnded;
emit CrowdsaleEnded(block.number);
return true;
}
}
return false;
}
function refundTransaction(bool _stateChanged) internal {
if (_stateChanged) {
msg.sender.transfer(msg.value);
} else {
revert();
}
}
function calculateEthToToken(uint _eth, uint _blockNumber) constant public returns(uint) {
if (tokensIssued <= 20000000 * 10**18) {
return _eth * 8640;
} else if(tokensIssued <= 40000000 * 10**18) {
return _eth * 8480;
} else if(tokensIssued <= 60000000 * 10**18) {
return _eth * 8320;
} else if(tokensIssued <= 80000000 * 10**18) {
return _eth * 8160;
} else {
return _eth * 8000;
}
}
function calculateTokenToEth(uint _token, uint _blockNumber) constant public returns(uint) {
uint tempTokenAmount;
if (tokensIssued <= 20000000 * 10**18) {
tempTokenAmount = (_token * 1000) / 1008640;
} else if(tokensIssued <= 40000000 * 10**18) {
tempTokenAmount = (_token * 1000) / 8480;
} else if(tokensIssued <= 60000000 * 10**18) {
tempTokenAmount = (_token * 1000) / 8320;
} else if(tokensIssued <= 80000000 * 10**18) {
tempTokenAmount = (_token * 1000) / 8160;
} else {
tempTokenAmount = (_token * 1000) / 8000;
}
return tempTokenAmount / 1000;
}
function processTransaction(address _contributor, uint _amount) internal {
uint contributionAmount = 0;
uint returnAmount = 0;
uint tokensToGive = 0;
if (block.number < crowdsaleStartBlock + startPhaseLength) {
if((_amount + contributorList[_contributor].contributionAmount) > startPhaseMaximumcontribution) {
if (contributorList[_contributor].contributionAmount < startPhaseMaximumcontribution) {
contributionAmount = startPhaseMaximumcontribution - contributorList[_contributor].contributionAmount;
returnAmount = _amount - contributionAmount;
} else {
revert();
}
} else {
contributionAmount = _amount;
}
} else {
contributionAmount = _amount;
}
tokensToGive = calculateEthToToken(contributionAmount, block.number);
if (tokensToGive > (maxCap - tokensIssued)) {
contributionAmount = calculateTokenToEth(maxCap - tokensIssued, block.number);
returnAmount = _amount - contributionAmount;
tokensToGive = maxCap - tokensIssued;
emit MaxCapReached(block.number);
}
if (contributorList[_contributor].contributionAmount == 0) {
contributorIndexes[nextContributorIndex] = _contributor;
nextContributorIndex += 1;
}
contributorList[_contributor].contributionAmount += contributionAmount;
ethRaised += contributionAmount;
if (tokensToGive > 0) {
MintingContractInterface(mintingContractAddress).doCrowdsaleMinting(_contributor, tokensToGive);
contributorList[_contributor].tokensIssued += tokensToGive;
tokensIssued += tokensToGive;
}
if (returnAmount != 0) {
_contributor.transfer(returnAmount);
}
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public {
ERC20TokenInterface(_tokenAddress).transfer(_to, _amount);
}
function withdrawEth() onlyOwner public {
require(address(this).balance != 0);
require(tokensIssued >= minCap);
multisigAddress.transfer(address(this).balance);
}
function claimEthIfFailed() public {
require(block.number > crowdsaleEndedBlock && tokensIssued < minCap);
require(contributorList[msg.sender].contributionAmount > 0);
require(!hasClaimedEthWhenFail[msg.sender]);
uint ethContributed = contributorList[msg.sender].contributionAmount;
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)) {
emit ErrorSendingETH(msg.sender, ethContributed);
}
}
function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner public {
require(block.number > crowdsaleEndedBlock && tokensIssued < minCap);
address currentParticipantAddress;
uint contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++) {
currentParticipantAddress = contributorIndexes[nextContributorToClaim];
if (currentParticipantAddress == 0x0) {
return;
}
if (!hasClaimedEthWhenFail[currentParticipantAddress]) {
contribution = contributorList[currentParticipantAddress].contributionAmount;
hasClaimedEthWhenFail[currentParticipantAddress] = true;
if (!currentParticipantAddress.send(contribution)) {
emit ErrorSendingETH(currentParticipantAddress, contribution);
}
}
nextContributorToClaim += 1;
}
}
function withdrawRemainingBalanceForManualRecovery() onlyOwner public {
require(address(this).balance != 0);
require(block.number > crowdsaleEndedBlock);
require(contributorIndexes[nextContributorToClaim] == 0x0);
multisigAddress.transfer(address(this).balance);
}
function setMultisigAddress(address _newAddress) onlyOwner public {
multisigAddress = _newAddress;
}
function setMintingContractAddress(address _newAddress) onlyOwner public {
mintingContractAddress = _newAddress;
}
function setKycAddress(address _newAddress) onlyOwner public {
kycAddress = _newAddress;
}
function investorCount() constant public returns(uint) {
return nextContributorIndex;
}
function setCrowdsaleStartBlock(uint _block) onlyOwner public {
crowdsaleStartBlock = _block;
}
}
contract EligmaCrowdsaleContract is Crowdsale {
function EligmaCrowdsaleContract() public {
crowdsaleStartBlock = 5456462;
crowdsaleEndedBlock = 5584081;
minCap = 0 * 10**18;
maxCap = 161054117 * 10**18;
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ERC20Token is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function ERC20Token(
) {
balances[msg.sender] = 2100000000000000;
totalSupply = 2100000000000000;
name = "Satoshi Token";
decimals = 0;
symbol = "SAT";
}
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.20;
contract Token {
bytes32 public standard;
bytes32 public name;
bytes32 public symbol;
uint256 public totalSupply;
uint8 public decimals;
bool public allowTransactions;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowed;
function transfer(address _to, uint256 _value) public returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
}
contract F1C_01Test
{
address public adminaddr;
address public useraddr;
address public owner;
mapping (address => mapping(address => uint256)) public dep_token;
mapping (address => uint256) public dep_ETH;
function F1C_01Test() public
{
adminaddr = msg.sender;
}
modifier onlyOwner() {
_;
}
function safeAdd(uint crtbal, uint depbal) public returns (uint)
{
uint totalbal = crtbal + depbal;
return totalbal;
}
function safeSub(uint crtbal, uint depbal) public returns (uint)
{
uint totalbal = crtbal - depbal;
return totalbal;
}
function balanceOf(address token,address user) public returns(uint256)
{
return Token(token).balanceOf(user);
}
function transfer(address token, uint256 tokens)public payable
{
if(Token(token).approve(address(this),tokens))
{
dep_token[msg.sender][token] = safeAdd(dep_token[msg.sender][token], tokens);
Token(token).transferFrom(msg.sender,address(this), tokens);
}
}
function token_withdraw(address token, address to, uint256 tokens)public payable
{
if(adminaddr==msg.sender)
{
dep_token[msg.sender][token] = safeSub(dep_token[msg.sender][token] , tokens) ;
Token(token).transfer(to, tokens);
}
}
function admin_token_withdraw(address token, address to, uint256 tokens)public payable
{
if(adminaddr==msg.sender)
{
if(dep_token[msg.sender][token]>=tokens)
{
dep_token[msg.sender][token] = safeSub(dep_token[msg.sender][token] , tokens) ;
Token(token).transfer(to, tokens);
}
}
}
function tok_bal_contract(address token) public view returns(uint256)
{
return Token(token).balanceOf(address(this));
}
function depositETH() payable external
{
}
function withdrawETH(address to, uint256 value) public payable returns (bool)
{
to.transfer(value);
return true;
}
function admin_withdrawETH(address to, uint256 value) public payable returns (bool)
{
if(adminaddr==msg.sender)
{
to.transfer(value);
return true;
}
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract FractionToken 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 FractionCoin is FractionToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function FractionCoin(
) {
balances[msg.sender] = 888888888888;
totalSupply = 888888888888;
name = "FractionCoin";
decimals = 0;
symbol = "FRA";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.18;
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 InbestToken is StandardToken {
string public constant name = "Inbest Token";
string public constant symbol = "IBST";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 17656263110 * (10 ** uint256(decimals));
function InbestToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
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 InbestDistribution is Ownable {
using SafeMath for uint256;
InbestToken public IBST;
mapping (address => bool) public admins;
uint256 private constant DECIMALFACTOR = 10**uint256(18);
uint256 CLIFF = 180 days;
uint256 VESTING = 365 days;
uint256 public constant INITIAL_SUPPLY = 17656263110 * DECIMALFACTOR;
uint256 public AVAILABLE_TOTAL_SUPPLY = 17656263110 * DECIMALFACTOR;
uint256 public AVAILABLE_PRESALE_SUPPLY = 16656263110 * DECIMALFACTOR;
uint256 public AVAILABLE_COMPANY_SUPPLY = 1000000000 * DECIMALFACTOR;
enum AllocationType { PRESALE, COMPANY}
uint256 public grandTotalClaimed = 0;
uint256 public startTime;
address public companyWallet;
struct Allocation {
uint8 allocationType;
uint256 endCliff;
uint256 endVesting;
uint256 totalAllocated;
uint256 amountClaimed;
}
mapping (address => Allocation) public allocations;
modifier onlyOwnerOrAdmin() {
require(msg.sender == owner || admins[msg.sender]);
_;
}
event LogNewAllocation(address indexed _recipient, AllocationType indexed _fromSupply, uint256 _totalAllocated, uint256 _grandTotalAllocated);
event LogIBSTClaimed(address indexed _recipient, uint8 indexed _fromSupply, uint256 _amountClaimed, uint256 _totalAllocated, uint256 _grandTotalClaimed);
event SetAdmin(address _caller, address _admin, bool _allowed);
event RefundTokens(address _token, address _refund, uint256 _value);
function InbestDistribution(uint256 _startTime, address _companyWallet) public {
require(_companyWallet != address(0));
require(_startTime >= now);
require(AVAILABLE_TOTAL_SUPPLY == AVAILABLE_PRESALE_SUPPLY.add(AVAILABLE_COMPANY_SUPPLY));
startTime = _startTime;
companyWallet = _companyWallet;
IBST = new InbestToken();
require(AVAILABLE_TOTAL_SUPPLY == IBST.totalSupply());
uint256 tokensToAllocate = AVAILABLE_COMPANY_SUPPLY;
AVAILABLE_COMPANY_SUPPLY = 0;
allocations[companyWallet] = Allocation(uint8(AllocationType.COMPANY), 0, 0, tokensToAllocate, 0);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(tokensToAllocate);
LogNewAllocation(companyWallet, AllocationType.COMPANY, tokensToAllocate, grandTotalAllocated());
}
function setAllocation (address _recipient, uint256 _totalAllocated) public onlyOwnerOrAdmin {
require(_recipient != address(0));
require(startTime > now);
require(AVAILABLE_PRESALE_SUPPLY >= _totalAllocated);
require(allocations[_recipient].totalAllocated == 0 && _totalAllocated > 0);
require(_recipient != companyWallet);
AVAILABLE_PRESALE_SUPPLY = AVAILABLE_PRESALE_SUPPLY.sub(_totalAllocated);
allocations[_recipient] = Allocation(uint8(AllocationType.PRESALE), startTime.add(CLIFF), startTime.add(CLIFF).add(VESTING), _totalAllocated, 0);
AVAILABLE_TOTAL_SUPPLY = AVAILABLE_TOTAL_SUPPLY.sub(_totalAllocated);
LogNewAllocation(_recipient, AllocationType.PRESALE, _totalAllocated, grandTotalAllocated());
}
function transferTokens (address _recipient) public {
require(_recipient != address(0));
require(now >= startTime);
require(_recipient != companyWallet);
require(now >= allocations[_recipient].endCliff);
require(allocations[_recipient].amountClaimed < allocations[_recipient].totalAllocated);
uint256 newAmountClaimed;
if (allocations[_recipient].endVesting > now) {
newAmountClaimed = allocations[_recipient].totalAllocated.mul(now.sub(allocations[_recipient].endCliff)).div(allocations[_recipient].endVesting.sub(allocations[_recipient].endCliff));
} else {
newAmountClaimed = allocations[_recipient].totalAllocated;
}
uint256 tokensToTransfer = newAmountClaimed.sub(allocations[_recipient].amountClaimed);
allocations[_recipient].amountClaimed = newAmountClaimed;
require(IBST.transfer(_recipient, tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(tokensToTransfer);
LogIBSTClaimed(_recipient, allocations[_recipient].allocationType, tokensToTransfer, newAmountClaimed, grandTotalClaimed);
}
function manualContribution(address _recipient, uint256 _tokensToTransfer) public onlyOwnerOrAdmin {
require(_recipient != address(0));
require(_recipient != companyWallet);
require(_tokensToTransfer > 0);
require(now >= startTime);
require(allocations[companyWallet].amountClaimed.add(_tokensToTransfer) <= allocations[companyWallet].totalAllocated);
allocations[companyWallet].amountClaimed = allocations[companyWallet].amountClaimed.add(_tokensToTransfer);
require(IBST.transfer(_recipient, _tokensToTransfer));
grandTotalClaimed = grandTotalClaimed.add(_tokensToTransfer);
LogIBSTClaimed(_recipient, uint8(AllocationType.COMPANY), _tokensToTransfer, allocations[companyWallet].amountClaimed, grandTotalClaimed);
}
function companyRemainingAllocation() public view returns (uint256) {
return allocations[companyWallet].totalAllocated.sub(allocations[companyWallet].amountClaimed);
}
function grandTotalAllocated() public view returns (uint256) {
return INITIAL_SUPPLY.sub(AVAILABLE_TOTAL_SUPPLY);
}
function setAdmin(address _admin, bool _allowed) public onlyOwner {
require(_admin != address(0));
admins[_admin] = _allowed;
SetAdmin(msg.sender,_admin,_allowed);
}
function refundTokens(address _token, address _refund, uint256 _value) public onlyOwner {
require(_refund != address(0));
require(_token != address(0));
require(_token != address(IBST));
ERC20 token = ERC20(_token);
require(token.transfer(_refund, _value));
RefundTokens(_token, _refund, _value);
}
}
contract InbestTokenDistributor is Ownable {
InbestDistribution public inbestDistribution;
address[] public walletsToDistribute;
mapping (address => address) public walletsToDistributeMapp;
mapping (address => bool) public admins;
function InbestTokenDistributor (InbestDistribution _inbestDistribution) public {
require(_inbestDistribution != address(0));
inbestDistribution = _inbestDistribution;
}
function distributeTokens() public{
require(walletsToDistribute.length > 0);
uint arrayLength = walletsToDistribute.length;
for (uint i=0; i < arrayLength; i++) {
inbestDistribution.transferTokens(walletsToDistribute[i]);
}
}
function distributeTokensToWallets(address[] _addresses) public onlyOwner{
require(_addresses.length > 0);
uint arrayLength = _addresses.length;
for (uint i=0; i < arrayLength; i++) {
inbestDistribution.transferTokens(_addresses[i]);
}
}
function addWallet(address _newAddress) public onlyOwner{
require(_newAddress != address(0));
require(walletsToDistributeMapp[_newAddress] == address(0));
walletsToDistribute.push(_newAddress);
walletsToDistributeMapp[_newAddress] = _newAddress;
}
function addWallets(address[] _addresses) public onlyOwner{
for(uint i = 0; i < _addresses.length; i++){
addWallet(_addresses[i]);
}
}
function removeWallet(address _removeAddress) public onlyOwner {
for (uint i = 0; i < walletsToDistribute.length; i++){
if (_removeAddress == walletsToDistribute[i]) {
walletsToDistribute[i] = walletsToDistribute[walletsToDistribute.length-1];
walletsToDistribute.length--;
delete walletsToDistributeMapp[_removeAddress];
}
}
}
} | 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 = 29808000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x7a385c7c56D4A54f3e9f778b3801783228Ea3aF7;
}
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 Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Haltable is Ownable {
bool public halted;
modifier stopInEmergency {
if (halted) throw;
_;
}
modifier stopNonOwnersInEmergency {
if (halted && msg.sender != owner) throw;
_;
}
modifier onlyInEmergency {
if (!halted) throw;
_;
}
function halt() external onlyOwner {
halted = true;
}
function unhalt() external onlyOwner onlyInEmergency {
halted = false;
}
}
library SafeMathLib {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
contract 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 FractionalERC20 is ERC20 {
uint public decimals;
}
contract PricingStrategy {
function isPricingStrategy() public constant returns (bool) {
return true;
}
function isSane(address crowdsale) public constant returns (bool) {
return true;
}
function isPresalePurchase(address purchaser) public constant returns (bool) {
return false;
}
function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount);
}
contract FinalizeAgent {
function isFinalizeAgent() public constant returns(bool) {
return true;
}
function isSane() public constant returns (bool);
function finalizeCrowdsale();
}
contract CrowdsaleBase is Haltable {
uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5;
using SafeMathLib for uint;
FractionalERC20 public token;
PricingStrategy public pricingStrategy;
FinalizeAgent public finalizeAgent;
address public multisigWallet;
uint public minimumFundingGoal;
uint public startsAt;
uint public endsAt;
uint public tokensSold = 0;
uint public weiRaised = 0;
uint public presaleWeiRaised = 0;
uint public investorCount = 0;
uint public loadedRefund = 0;
uint public weiRefunded = 0;
bool public finalized;
mapping (address => uint256) public investedAmountOf;
mapping (address => uint256) public tokenAmountOf;
mapping (address => bool) public earlyParticipantWhitelist;
uint public ownerTestValue;
enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding}
event Invested(address investor, uint weiAmount, uint tokenAmount, uint128 customerId);
event Refund(address investor, uint weiAmount);
event InvestmentPolicyChanged(bool newRequireCustomerId, bool newRequiredSignedAddress, address newSignerAddress);
event Whitelisted(address addr, bool status);
event EndsAtChanged(uint newEndsAt);
State public testState;
function CrowdsaleBase(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) {
owner = msg.sender;
token = FractionalERC20(_token);
setPricingStrategy(_pricingStrategy);
multisigWallet = _multisigWallet;
if(multisigWallet == 0) {
throw;
}
if(_start == 0) {
throw;
}
startsAt = _start;
if(_end == 0) {
throw;
}
endsAt = _end;
if(startsAt >= endsAt) {
throw;
}
minimumFundingGoal = _minimumFundingGoal;
}
function() payable {
throw;
}
function investInternal(address receiver, uint128 customerId) stopInEmergency internal returns(uint tokensBought) {
if(getState() == State.PreFunding) {
if(!earlyParticipantWhitelist[receiver]) {
throw;
}
} else if(getState() == State.Funding) {
} else {
throw;
}
uint weiAmount = msg.value;
uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised - presaleWeiRaised, tokensSold, msg.sender, token.decimals());
require(tokenAmount != 0);
if(investedAmountOf[receiver] == 0) {
investorCount++;
}
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSold.plus(tokenAmount);
if(pricingStrategy.isPresalePurchase(receiver)) {
presaleWeiRaised = presaleWeiRaised.plus(weiAmount);
}
require(!isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold));
assignTokens(receiver, tokenAmount);
if(!multisigWallet.send(weiAmount)) throw;
Invested(receiver, weiAmount, tokenAmount, customerId);
return tokenAmount;
}
function finalize() public inState(State.Success) onlyOwner stopInEmergency {
if(finalized) {
throw;
}
if(address(finalizeAgent) != 0) {
finalizeAgent.finalizeCrowdsale();
}
finalized = true;
}
function setFinalizeAgent(FinalizeAgent addr) onlyOwner {
finalizeAgent = addr;
if(!finalizeAgent.isFinalizeAgent()) {
throw;
}
}
function setEndsAt(uint time) onlyOwner {
if(now > time) {
throw;
}
if(startsAt > time) {
throw;
}
endsAt = time;
EndsAtChanged(endsAt);
}
function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner {
pricingStrategy = _pricingStrategy;
if(!pricingStrategy.isPricingStrategy()) {
throw;
}
}
function setMultisig(address addr) public onlyOwner {
if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) {
throw;
}
multisigWallet = addr;
}
function loadRefund() public payable inState(State.Failure) {
if(msg.value == 0) throw;
loadedRefund = loadedRefund.plus(msg.value);
}
function refund() public inState(State.Refunding) {
uint256 weiValue = investedAmountOf[msg.sender];
if (weiValue == 0) throw;
investedAmountOf[msg.sender] = 0;
weiRefunded = weiRefunded.plus(weiValue);
Refund(msg.sender, weiValue);
if (!msg.sender.send(weiValue)) throw;
}
function isMinimumGoalReached() public constant returns (bool reached) {
return weiRaised >= minimumFundingGoal;
}
function isFinalizerSane() public constant returns (bool sane) {
return finalizeAgent.isSane();
}
function isPricingSane() public constant returns (bool sane) {
return pricingStrategy.isSane(address(this));
}
function getState() public constant returns (State) {
if(finalized) return State.Finalized;
else if (address(finalizeAgent) == 0) return State.Preparing;
else if (!finalizeAgent.isSane()) return State.Preparing;
else if (!pricingStrategy.isSane(address(this))) return State.Preparing;
else if (block.timestamp < startsAt) return State.PreFunding;
else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding;
else if (isMinimumGoalReached()) return State.Success;
else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding;
else return State.Failure;
}
function setOwnerTestValue(uint val) onlyOwner {
ownerTestValue = val;
}
function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner {
earlyParticipantWhitelist[addr] = status;
Whitelisted(addr, status);
}
function isCrowdsale() public constant returns (bool) {
return true;
}
modifier inState(State state) {
if(getState() != state) throw;
_;
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken);
function isCrowdsaleFull() public constant returns (bool);
function assignTokens(address receiver, uint tokenAmount) internal;
}
contract AllocatedCrowdsaleMixin is CrowdsaleBase {
address public beneficiary;
function AllocatedCrowdsaleMixin(address _beneficiary) {
beneficiary = _beneficiary;
}
function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken) {
if(tokenAmount > getTokensLeft()) {
return true;
} else {
return false;
}
}
function isCrowdsaleFull() public constant returns (bool) {
return getTokensLeft() == 0;
}
function getTokensLeft() public constant returns (uint) {
return token.allowance(owner, this);
}
function assignTokens(address receiver, uint tokenAmount) internal {
if(!token.transferFrom(beneficiary, receiver, tokenAmount)) throw;
}
}
contract Crowdsale is CrowdsaleBase {
bool public requireCustomerId;
bool public requiredSignedAddress;
address public signerAddress;
function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) CrowdsaleBase(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) {
}
function preallocate(address receiver, uint fullTokens, uint weiPrice) public onlyOwner {
uint tokenAmount = fullTokens * 10**token.decimals();
uint weiAmount = weiPrice * fullTokens;
weiRaised = weiRaised.plus(weiAmount);
tokensSold = tokensSold.plus(tokenAmount);
investedAmountOf[receiver] = investedAmountOf[receiver].plus(weiAmount);
tokenAmountOf[receiver] = tokenAmountOf[receiver].plus(tokenAmount);
assignTokens(receiver, tokenAmount);
Invested(receiver, weiAmount, tokenAmount, 0);
}
function investWithSignedAddress(address addr, uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
bytes32 hash = sha256(addr);
if (ecrecover(hash, v, r, s) != signerAddress) throw;
if(customerId == 0) throw;
investInternal(addr, customerId);
}
function investWithCustomerId(address addr, uint128 customerId) public payable {
if(requiredSignedAddress) throw;
if(customerId == 0) throw;
investInternal(addr, customerId);
}
function invest(address addr) public payable {
if(requireCustomerId) throw;
if(requiredSignedAddress) throw;
investInternal(addr, 0);
}
function buyWithSignedAddress(uint128 customerId, uint8 v, bytes32 r, bytes32 s) public payable {
investWithSignedAddress(msg.sender, customerId, v, r, s);
}
function buyWithCustomerIdWithChecksum(uint128 customerId, bytes1 checksum) public payable {
if (bytes1(sha3(customerId)) != checksum) throw;
investWithCustomerId(msg.sender, customerId);
}
function buyWithCustomerId(uint128 customerId) public payable {
investWithCustomerId(msg.sender, customerId);
}
function buy() public payable {
invest(msg.sender);
}
function setRequireCustomerId(bool value) onlyOwner {
requireCustomerId = value;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
function setRequireSignedAddress(bool value, address _signerAddress) onlyOwner {
requiredSignedAddress = value;
signerAddress = _signerAddress;
InvestmentPolicyChanged(requireCustomerId, requiredSignedAddress, signerAddress);
}
}
contract AllocatedCrowdsale is AllocatedCrowdsaleMixin, Crowdsale {
function AllocatedCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal, address _beneficiary) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, _minimumFundingGoal) AllocatedCrowdsaleMixin(_beneficiary) {
}
} | 0 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TheCryptoTech is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function TheCryptoTech() public {
symbol = "TCT";
name = "The Crypto Tech";
decimals = 18;
_totalSupply = 950000000000000000000000000;
balances[0x59e47c9984d391f4A6095f25d8fA2570e34D87CC] = _totalSupply;
Transfer(address(0), 0x59e47c9984d391f4A6095f25d8fA2570e34D87CC, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 |
pragma solidity ^ 0.4 .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 Hostelcoin {
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 Hostelcoin() {
totalSupply = 100000000;
symbol = 'Hostel Token';
owner = 0x3ee8f2a4ad734cbebde350dbda28e0da56812830;
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;
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract StandardToken is SafeMath {
uint256 public totalSupply;
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
modifier onlyPayloadSize(uint256 size) {
require(msg.data.length == size + 4);
_;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != 0);
uint256 balanceFrom = balances[msg.sender];
require(_value <= balanceFrom);
balances[msg.sender] = safeSub(balanceFrom, _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_to != 0);
uint256 allowToTrans = allowed[_from][msg.sender];
uint256 balanceFrom = balances[_from];
require(_value <= balanceFrom);
require(_value <= allowToTrans);
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balanceFrom, _value);
allowed[_from][msg.sender] = safeSub(allowToTrans, _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];
}
function addApproval(address _spender, uint256 _addedValue)
onlyPayloadSize(2 * 32)
public returns (bool success) {
uint256 oldValue = allowed[msg.sender][_spender];
allowed[msg.sender][_spender] = safeAdd(oldValue, _addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function subApproval(address _spender, uint256 _subtractedValue)
onlyPayloadSize(2 * 32)
public returns (bool success) {
uint256 oldVal = allowed[msg.sender][_spender];
if (_subtractedValue > oldVal) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSub(oldVal, _subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is Ownable, StandardToken {
address public migrationAgent;
event Upgrade(address indexed from, address indexed to, uint256 value);
event UpgradeAgentSet(address agent);
function migrate() public {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] = safeSub(balances[msg.sender], value);
totalSupply = safeSub(totalSupply, value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Upgrade(msg.sender, migrationAgent, value);
}
function () public payable {
require(migrationAgent != 0);
require(balances[msg.sender] > 0);
migrate();
msg.sender.transfer(msg.value);
}
function setMigrationAgent(address _agent) onlyOwner external {
migrationAgent = _agent;
UpgradeAgentSet(_agent);
}
}
contract SABToken is UpgradeableToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
address public allTokenOwnerOnStart;
string public constant name = "SABCoin";
string public constant symbol = "SAB";
uint256 public constant decimals = 6;
function SABToken() public {
allTokenOwnerOnStart = msg.sender;
totalSupply = 100000000000000;
balances[allTokenOwnerOnStart] = totalSupply;
Mint(allTokenOwnerOnStart, totalSupply);
Transfer(0x0, allTokenOwnerOnStart ,totalSupply);
MintFinished();
}
}
contract IcoSABToken is Ownable, SafeMath {
address public wallet;
address public allTokenAddress;
bool public emergencyFlagAndHiddenCap = false;
uint256 public startTime = 1515499200;
uint256 public endTime = 1518523200;
uint256 public USDto1ETH = 1250;
uint256 public price;
uint256 public totalTokensSold = 0;
uint256 public constant maxTokensToSold = 60000000000000;
SABToken public token;
function IcoSABToken(address _wallet, SABToken _token) public {
wallet = _wallet;
token = _token;
allTokenAddress = token.allTokenOwnerOnStart();
price = 1 ether / USDto1ETH / 1000000;
}
function () public payable {
require(now <= endTime && now >= startTime);
require(!emergencyFlagAndHiddenCap);
require(totalTokensSold < maxTokensToSold);
uint256 value = msg.value;
uint256 tokensToSend = safeDiv(value, price);
require(tokensToSend >= 1000000 && tokensToSend <= 350000000000);
uint256 valueToReturn = safeSub(value, tokensToSend * price);
uint256 valueToWallet = safeSub(value, valueToReturn);
wallet.transfer(valueToWallet);
if (valueToReturn > 0) {
msg.sender.transfer(valueToReturn);
}
token.transferFrom(allTokenAddress, msg.sender, tokensToSend);
totalTokensSold += tokensToSend;
}
function ChangeUSDto1ETH(uint256 _USDto1ETH) onlyOwner public {
USDto1ETH = _USDto1ETH;
ChangePrice();
}
function ChangePrice() onlyOwner public {
uint256 priceWeiToUSD = 1 ether / USDto1ETH;
uint256 price1mToken = priceWeiToUSD / 1000000;
if ( now <= startTime + 15 days) {
price = price1mToken * 1 / 4 ;
}
else {
if ( now <= startTime + 25 days ) {
price = price1mToken * 1 / 2;
}
else {
price = price1mToken;
}
}
}
function ChangeStart(uint _startTime) onlyOwner public {
startTime = _startTime;
}
function ChangeEnd(uint _endTime) onlyOwner public {
endTime = _endTime;
}
function emergencyAndHiddenCapToggle() onlyOwner public {
emergencyFlagAndHiddenCap = !emergencyFlagAndHiddenCap;
}
} | 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 = 0x43cAE449cdD4E7cCC1a647E17cC2c40128d4a895;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
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 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 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);
constructor(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;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
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 = "CPollo";
string public constant TOKEN_SYMBOL = "CPLO";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0x3374EB92854FF40c1E74a8FE2114d99b38214070;
uint public constant START_TIME = 1534737600;
bool public constant CONTINUE_MINTING = false;
}
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 RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public goal;
RefundVault public vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
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 TemplateCrowdsale is Consts, MainCrowdsale
, RefundableCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(200000 * TOKEN_DECIMAL_MULTIPLIER, 0x3374EB92854FF40c1E74a8FE2114d99b38214070, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1538366400)
CappedCrowdsale(50000000000000000000000)
RefundableCrowdsale(1000000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[4] memory addresses = [address(0x85efaea2ba17104a6fd41099cececf29dc6bcfe6),address(0x3681d701b8679c6adb866736d3e523e8856dfa7a),address(0xbb0cd3ab7cb7aff6298dc25ce710052a6c9cb764),address(0x7376a1b427693a78b741fac92824f0ad0988ec28)];
uint[4] memory amounts = [uint(1500000000000000000000000000),uint(1500000000000000000000000000),uint(2000000000000000000000000000),uint(5000000000000000000000000000)];
uint64[4] memory freezes = [uint64(0),uint64(0),uint64(0),uint64(0)];
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.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract FXBSCoin is ERC20 {
using SafeMath for uint256;
address public owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "FXB";
string public constant symbol = "FXB";
uint public constant decimals = 8;
uint256 public totalSupply = 100000000e8;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed burner, uint256 value);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function FXBSCoin () public {
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
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) {
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 burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
} | 1 |
pragma solidity ^0.4.13;
contract ReentrancyGuard {
bool private reentrancy_lock = false;
modifier nonReentrant() {
require(!reentrancy_lock);
reentrancy_lock = true;
_;
reentrancy_lock = false;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract 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 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 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 DataWalletCrowdsale is Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 public firstDayCap;
uint256 public cap;
uint256 public goal;
uint256 public rate;
uint256 public constant WEI_TO_INSIGHTS = 10**uint256(10);
RefundVault public vault;
DataWalletToken public token;
uint256 public startTime;
uint256 public endTime;
uint256 public firstDay;
bool public isFinalized = false;
uint256 public weiRaised;
mapping(address => bool) public whitelist;
mapping(address => uint256) public contribution;
event WhitelistUpdate(address indexed purchaser, bool status);
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenRefund(address indexed refundee, uint256 amount);
event Finalized();
function DataWalletCrowdsale(
address _token,
address _wallet,
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
uint256 _cap,
uint256 _firstDayCap,
uint256 _goal
) {
require(_startTime >= getBlockTimestamp());
require(_endTime >= _startTime);
require(_rate > 0);
require(_goal > 0);
require(_cap > 0);
require(_wallet != 0x0);
vault = new RefundVault(_wallet);
token = DataWalletToken(_token);
startTime = _startTime;
endTime = _endTime;
firstDay = startTime + 1 * 1 days;
firstDayCap = _firstDayCap;
rate = _rate;
goal = _goal;
cap = _cap;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) internal {
require(beneficiary != 0x0);
require(whitelist[beneficiary]);
require(validPurchase());
uint256 weiAmount = msg.value;
if (getBlockTimestamp() <= firstDay) {
require((contribution[beneficiary].add(weiAmount)) <= firstDayCap);
}
uint256 remainingToFund = cap.sub(weiRaised);
if (weiAmount > remainingToFund) {
weiAmount = remainingToFund;
}
uint256 weiToReturn = msg.value.sub(weiAmount);
forwardFunds(weiAmount);
if (weiToReturn > 0) {
beneficiary.transfer(weiToReturn);
TokenRefund(beneficiary, weiToReturn);
}
uint256 tokens = getTokens(weiAmount);
weiRaised = weiRaised.add(weiAmount);
contribution[beneficiary] = contribution[beneficiary].add(weiAmount);
TokenPurchase(beneficiary, weiAmount, tokens);
token.transfer(beneficiary, tokens);
}
function getTokens(uint256 amount) internal constant returns (uint256) {
return amount.mul(rate).div(WEI_TO_INSIGHTS);
}
function claimRefund() nonReentrant external {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
function claimUnsold() onlyOwner {
require(endTime <= getBlockTimestamp());
uint256 unsold = token.balanceOf(this);
if (unsold > 0) {
require(token.transfer(msg.sender, unsold));
}
}
function updateWhitelist(address[] addresses, bool status) public onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
address contributorAddress = addresses[i];
whitelist[contributorAddress] = status;
WhitelistUpdate(contributorAddress, status);
}
}
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
isFinalized = true;
Finalized();
if (goalReached()) {
vault.close();
token.unpause();
token.transferOwnership(owner);
} else {
vault.enableRefunds();
}
}
function forwardFunds(uint256 weiAmount) internal {
vault.deposit.value(weiAmount)(msg.sender);
}
function hasEnded() public constant returns (bool) {
bool passedEndTime = getBlockTimestamp() > endTime;
return passedEndTime || capReached();
}
function capReached() public constant returns (bool) {
return weiRaised >= cap;
}
function goalReached() public constant returns (bool) {
return weiRaised >= goal;
}
function isWhitelisted(address contributor) public constant returns (bool) {
return whitelist[contributor];
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = getBlockTimestamp() >= startTime && getBlockTimestamp() <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool capNotReached = weiRaised < cap;
return withinPeriod && nonZeroPurchase && capNotReached;
}
function getBlockTimestamp() internal constant returns (uint256) {
return block.timestamp;
}
}
contract DataWalletToken is PausableToken, BurnableToken {
string public constant name = "DataWallet Token";
string public constant symbol = "DXT";
uint8 public constant decimals = 8;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(decimals);
function DataWalletToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transfer(address beneficiary, uint256 amount) public returns (bool) {
if (msg.sender != owner) {
require(!paused);
}
require(beneficiary != address(0));
require(amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[beneficiary] = balances[beneficiary].add(amount);
Transfer(msg.sender, beneficiary, amount);
return true;
}
} | 0 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.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 CARDANOCLASSIC is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function CARDANOCLASSIC(
) {
balances[msg.sender] = 450000000000000000000000000000;
totalSupply = 450000000000000000000000000000;
name = "CARDANOCLASSIC";
decimals = 18;
symbol = "CADAC";
}
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.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 Netkrone is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public Netkrone ;
uint256 public totalEthInWei;
address fundsWallet;
function Netkrone() {
balances[msg.sender] = 500000000;
totalSupply = 500000000;
name = "Netkrone";
decimals = 0;
symbol = "NKR";
fundsWallet = msg.sender;
}
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 Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
library addressSet {
struct _addressSet {
address[] members;
mapping(address => uint) memberIndices;
}
function insert(_addressSet storage self, address other) public {
if (!contains(self, other)) {
assert(length(self) < 2**256-1);
self.members.push(other);
self.memberIndices[other] = length(self);
}
}
function remove(_addressSet storage self, address other) public {
if (contains(self, other)) {
uint replaceIndex = self.memberIndices[other];
address lastMember = self.members[length(self)-1];
self.members[replaceIndex-1] = lastMember;
self.members.length--;
self.memberIndices[lastMember] = replaceIndex;
delete self.memberIndices[other];
}
}
function contains(_addressSet storage self, address other) public view returns (bool) {
return self.memberIndices[other] > 0;
}
function length(_addressSet storage self) public view returns (uint) {
return self.members.length;
}
}
interface ERC20 {
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
interface SnowflakeResolver {
function callOnSignUp() external returns (bool);
function onSignUp(string hydroId, uint allowance) external returns (bool);
function callOnRemoval() external returns (bool);
function onRemoval(string hydroId) external returns(bool);
}
interface ClientRaindrop {
function getUserByAddress(address _address) external view returns (string userName);
function isSigned(
address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s
) external pure returns (bool);
}
interface ViaContract {
function snowflakeCall(address resolver, string hydroIdFrom, string hydroIdTo, uint amount, bytes _bytes) external;
function snowflakeCall(address resolver, string hydroIdFrom, address to, uint amount, bytes _bytes) external;
}
contract Snowflake is Ownable {
using SafeMath for uint;
using addressSet for addressSet._addressSet;
mapping (string => uint) internal deposits;
uint signatureTimeout;
mapping (bytes32 => bool) signatureLog;
mapping (string => Identity) internal directory;
mapping (address => string) internal addressDirectory;
mapping (bytes32 => string) internal initiatedAddressClaims;
address public clientRaindropAddress;
address public hydroTokenAddress;
addressSet._addressSet resolverWhitelist;
constructor() public {
setSignatureTimeout(7200);
}
struct Identity {
address owner;
addressSet._addressSet addresses;
addressSet._addressSet resolvers;
mapping(address => uint) resolverAllowances;
}
function hasToken(address _address) public view returns (bool) {
return bytes(addressDirectory[_address]).length != 0;
}
modifier _hasToken(address _address, bool check) {
require(hasToken(_address) == check, "The transaction sender does not have a Snowflake.");
_;
}
function getHydroId(address _address) public view returns (string hydroId) {
require(hasToken(_address), "The address does not have a hydroId");
return addressDirectory[_address];
}
function whitelistResolver(address resolver) public {
resolverWhitelist.insert(resolver);
emit ResolverWhitelisted(resolver);
}
function isWhitelisted(address resolver) public view returns(bool) {
return resolverWhitelist.contains(resolver);
}
function getWhitelistedResolvers() public view returns(address[]) {
return resolverWhitelist.members;
}
function setSignatureTimeout(uint newTimeout) public {
require(newTimeout >= 1800, "Timeout must be at least 30 minutes.");
require(newTimeout <= 604800, "Timeout must be less than a week.");
signatureTimeout = newTimeout;
}
function setAddresses(address clientRaindrop, address hydroToken) public onlyOwner {
clientRaindropAddress = clientRaindrop;
hydroTokenAddress = hydroToken;
}
function mintIdentityToken() public _hasToken(msg.sender, false) {
_mintIdentityToken(msg.sender);
}
function mintIdentityTokenDelegated(address _address, uint8 v, bytes32 r, bytes32 s)
public _hasToken(_address, false)
{
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
_address, keccak256(abi.encodePacked("Create Snowflake", _address)), v, r, s
),
"Permission denied."
);
_mintIdentityToken(_address);
}
function _mintIdentityToken(address _address) internal {
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
string memory hydroId = clientRaindrop.getUserByAddress(_address);
Identity storage identity = directory[hydroId];
identity.owner = _address;
identity.addresses.insert(_address);
addressDirectory[_address] = hydroId;
emit SnowflakeMinted(hydroId);
}
function addResolvers(address[] resolvers, uint[] withdrawAllowances) public _hasToken(msg.sender, true) {
_addResolvers(addressDirectory[msg.sender], resolvers, withdrawAllowances);
}
function addResolversDelegated(
string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp
) public
{
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
require(timestamp.add(signatureTimeout) > block.timestamp, "Message was signed too long ago.");
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
directory[hydroId].owner,
keccak256(abi.encodePacked("Add Resolvers", resolvers, withdrawAllowances, timestamp)),
v, r, s
),
"Permission denied."
);
_addResolvers(hydroId, resolvers, withdrawAllowances);
}
function _addResolvers(
string hydroId, address[] resolvers, uint[] withdrawAllowances
) internal {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
Identity storage identity = directory[hydroId];
for (uint i; i < resolvers.length; i++) {
require(resolverWhitelist.contains(resolvers[i]), "The given resolver is not on the whitelist.");
require(!identity.resolvers.contains(resolvers[i]), "Snowflake has already set this resolver.");
SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]);
identity.resolvers.insert(resolvers[i]);
identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i];
if (snowflakeResolver.callOnSignUp()) {
require(
snowflakeResolver.onSignUp(hydroId, withdrawAllowances[i]),
"Sign up failure."
);
}
emit ResolverAdded(hydroId, resolvers[i], withdrawAllowances[i]);
}
}
function changeResolverAllowances(address[] resolvers, uint[] withdrawAllowances)
public _hasToken(msg.sender, true)
{
_changeResolverAllowances(addressDirectory[msg.sender], resolvers, withdrawAllowances);
}
function changeResolverAllowancesDelegated(
string hydroId, address[] resolvers, uint[] withdrawAllowances, uint8 v, bytes32 r, bytes32 s, uint timestamp
) public
{
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
bytes32 _hash = keccak256(
abi.encodePacked("Change Resolver Allowances", resolvers, withdrawAllowances, timestamp)
);
require(signatureLog[_hash] == false, "Signature was already submitted");
signatureLog[_hash] = true;
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(clientRaindrop.isSigned(directory[hydroId].owner, _hash, v, r, s), "Permission denied.");
_changeResolverAllowances(hydroId, resolvers, withdrawAllowances);
}
function _changeResolverAllowances(string hydroId, address[] resolvers, uint[] withdrawAllowances) internal {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
Identity storage identity = directory[hydroId];
for (uint i; i < resolvers.length; i++) {
require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver.");
identity.resolverAllowances[resolvers[i]] = withdrawAllowances[i];
emit ResolverAllowanceChanged(hydroId, resolvers[i], withdrawAllowances[i]);
}
}
function removeResolvers(address[] resolvers, bool force) public _hasToken(msg.sender, true) {
Identity storage identity = directory[addressDirectory[msg.sender]];
for (uint i; i < resolvers.length; i++) {
require(identity.resolvers.contains(resolvers[i]), "Snowflake has not set this resolver.");
identity.resolvers.remove(resolvers[i]);
delete identity.resolverAllowances[resolvers[i]];
if (!force) {
SnowflakeResolver snowflakeResolver = SnowflakeResolver(resolvers[i]);
if (snowflakeResolver.callOnRemoval()) {
require(
snowflakeResolver.onRemoval(addressDirectory[msg.sender]),
"Removal failure."
);
}
}
emit ResolverRemoved(addressDirectory[msg.sender], resolvers[i]);
}
}
function getDetails(string hydroId) public view returns (
address owner,
address[] resolvers,
address[] ownedAddresses,
uint256 balance
) {
Identity storage identity = directory[hydroId];
return (
identity.owner,
identity.resolvers.members,
identity.addresses.members,
deposits[hydroId]
);
}
function hasResolver(string hydroId, address resolver) public view returns (bool) {
Identity storage identity = directory[hydroId];
return identity.resolvers.contains(resolver);
}
function ownsAddress(string hydroId, address _address) public view returns (bool) {
Identity storage identity = directory[hydroId];
return identity.addresses.contains(_address);
}
function getResolverAllowance(string hydroId, address resolver) public view returns (uint withdrawAllowance) {
Identity storage identity = directory[hydroId];
return identity.resolverAllowances[resolver];
}
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == hydroTokenAddress, "Sender is not the HYDRO token smart contract.");
address recipient;
if (_bytes.length == 20) {
assembly {
recipient := div(mload(add(add(_bytes, 0x20), 0)), 0x1000000000000000000000000)
}
} else {
recipient = sender;
}
require(hasToken(recipient), "Invalid token recipient");
ERC20 hydro = ERC20(_tokenAddress);
require(hydro.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
deposits[addressDirectory[recipient]] = deposits[addressDirectory[recipient]].add(amount);
emit SnowflakeDeposit(addressDirectory[recipient], sender, amount);
}
function snowflakeBalance(string hydroId) public view returns (uint) {
return deposits[hydroId];
}
function transferSnowflakeBalance(string hydroIdTo, uint amount) public _hasToken(msg.sender, true) {
_transfer(addressDirectory[msg.sender], hydroIdTo, amount);
}
function withdrawSnowflakeBalance(address to, uint amount) public _hasToken(msg.sender, true) {
_withdraw(addressDirectory[msg.sender], to, amount);
}
function transferSnowflakeBalanceFrom(string hydroIdFrom, string hydroIdTo, uint amount) public {
handleAllowance(hydroIdFrom, amount);
_transfer(hydroIdFrom, hydroIdTo, amount);
}
function withdrawSnowflakeBalanceFrom(string hydroIdFrom, address to, uint amount) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, to, amount);
}
function withdrawSnowflakeBalanceFromVia(
string hydroIdFrom, address via, string hydroIdTo, uint amount, bytes _bytes
) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, via, amount);
ViaContract viaContract = ViaContract(via);
viaContract.snowflakeCall(msg.sender, hydroIdFrom, hydroIdTo, amount, _bytes);
}
function withdrawSnowflakeBalanceFromVia(
string hydroIdFrom, address via, address to, uint amount, bytes _bytes
) public {
handleAllowance(hydroIdFrom, amount);
_withdraw(hydroIdFrom, via, amount);
ViaContract viaContract = ViaContract(via);
viaContract.snowflakeCall(msg.sender, hydroIdFrom, to, amount, _bytes);
}
function _transfer(string hydroIdFrom, string hydroIdTo, uint amount) internal returns (bool) {
require(directory[hydroIdTo].owner != address(0), "Must transfer to an HydroID with a Snowflake");
require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount);
deposits[hydroIdTo] = deposits[hydroIdTo].add(amount);
emit SnowflakeTransfer(hydroIdFrom, hydroIdTo, amount);
}
function _withdraw(string hydroIdFrom, address to, uint amount) internal {
require(to != address(this), "Cannot transfer to the Snowflake smart contract itself.");
require(deposits[hydroIdFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[hydroIdFrom] = deposits[hydroIdFrom].sub(amount);
ERC20 hydro = ERC20(hydroTokenAddress);
require(hydro.transfer(to, amount), "Transfer was unsuccessful");
emit SnowflakeWithdraw(to, amount);
}
function handleAllowance(string hydroIdFrom, uint amount) internal {
Identity storage identity = directory[hydroIdFrom];
require(identity.owner != address(0), "Must withdraw from a HydroID with a Snowflake");
require(identity.resolvers.contains(msg.sender), "Resolver has not been set by from tokenholder.");
if (identity.resolverAllowances[msg.sender] < amount) {
emit InsufficientAllowance(hydroIdFrom, msg.sender, identity.resolverAllowances[msg.sender], amount);
require(false, "Insufficient Allowance");
}
identity.resolverAllowances[msg.sender] = identity.resolverAllowances[msg.sender].sub(amount);
}
function initiateClaimDelegated(string hydroId, bytes32 sealedClaim, uint8 v, bytes32 r, bytes32 s) public {
require(directory[hydroId].owner != address(0), "Must initiate claim for a HydroID with a Snowflake");
ClientRaindrop clientRaindrop = ClientRaindrop(clientRaindropAddress);
require(
clientRaindrop.isSigned(
directory[hydroId].owner, keccak256(abi.encodePacked("Initiate Claim", sealedClaim)), v, r, s
),
"Permission denied."
);
_initiateClaim(hydroId, sealedClaim);
}
function initiateClaim(bytes32 sealedClaim) public _hasToken(msg.sender, true) {
_initiateClaim(addressDirectory[msg.sender], sealedClaim);
}
function _initiateClaim(string hydroId, bytes32 sealedClaim) internal {
require(bytes(initiatedAddressClaims[sealedClaim]).length == 0, "This sealed claim has been submitted.");
initiatedAddressClaims[sealedClaim] = hydroId;
}
function finalizeClaim(bytes32 secret, string hydroId) public {
bytes32 possibleSealedClaim = keccak256(abi.encodePacked(msg.sender, secret, hydroId));
require(
bytes(initiatedAddressClaims[possibleSealedClaim]).length != 0, "This sealed claim hasn't been submitted."
);
require(
keccak256(abi.encodePacked(initiatedAddressClaims[possibleSealedClaim])) ==
keccak256(abi.encodePacked(hydroId)),
"Invalid signature."
);
directory[hydroId].addresses.insert(msg.sender);
addressDirectory[msg.sender] = hydroId;
emit AddressClaimed(msg.sender, hydroId);
}
function unclaim(address[] addresses) public _hasToken(msg.sender, true) {
for (uint i; i < addresses.length; i++) {
require(addresses[i] != directory[addressDirectory[msg.sender]].owner, "Cannot unclaim owner address.");
directory[addressDirectory[msg.sender]].addresses.remove(addresses[i]);
delete addressDirectory[addresses[i]];
emit AddressUnclaimed(addresses[i], addressDirectory[msg.sender]);
}
}
event SnowflakeMinted(string hydroId);
event ResolverWhitelisted(address indexed resolver);
event ResolverAdded(string hydroId, address resolver, uint withdrawAllowance);
event ResolverAllowanceChanged(string hydroId, address resolver, uint withdrawAllowance);
event ResolverRemoved(string hydroId, address resolver);
event SnowflakeDeposit(string hydroId, address from, uint amount);
event SnowflakeTransfer(string hydroIdFrom, string hydroIdTo, uint amount);
event SnowflakeWithdraw(address to, uint amount);
event InsufficientAllowance(
string hydroId, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
event AddressClaimed(address indexed _address, string hydroId);
event AddressUnclaimed(address indexed _address, string hydroId);
} | 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 = 29203200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x355f15fD0541c6b4A6E4c4f6c1F71BA32F7054e9;
}
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 Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract 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 ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
contract ERC721Token is ERC721 {
using SafeMath for uint256;
uint256 private totalTokens;
mapping (uint256 => address) private tokenOwner;
mapping (uint256 => address) private tokenApprovals;
mapping (address => uint256[]) private ownedTokens;
mapping(uint256 => uint256) private ownedTokensIndex;
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
function totalSupply() public view returns (uint256) {
return totalTokens;
}
function balanceOf(address _owner) public view returns (uint256) {
return ownedTokens[_owner].length;
}
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function approvedFor(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
address owner = ownerOf(_tokenId);
require(_to != owner);
if (approvedFor(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
function takeOwnership(uint256 _tokenId) public {
require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addToken(_to, _tokenId);
Transfer(0x0, _to, _tokenId);
}
function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal {
if (approvedFor(_tokenId) != 0) {
clearApproval(msg.sender, _tokenId);
}
removeToken(msg.sender, _tokenId);
Transfer(msg.sender, 0x0, _tokenId);
}
function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) {
return approvedFor(_tokenId) == _owner;
}
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
clearApproval(_from, _tokenId);
removeToken(_from, _tokenId);
addToken(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
Approval(_owner, 0, _tokenId);
}
function addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
function removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract AccessDeposit is Claimable {
mapping(address => bool) private depositAccess;
modifier onlyAccessDeposit {
require(msg.sender == owner || depositAccess[msg.sender] == true);
_;
}
function grantAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = true;
}
function revokeAccessDeposit(address _address)
onlyOwner
public
{
depositAccess[_address] = false;
}
}
contract AccessDeploy is Claimable {
mapping(address => bool) private deployAccess;
modifier onlyAccessDeploy {
require(msg.sender == owner || deployAccess[msg.sender] == true);
_;
}
function grantAccessDeploy(address _address)
onlyOwner
public
{
deployAccess[_address] = true;
}
function revokeAccessDeploy(address _address)
onlyOwner
public
{
deployAccess[_address] = false;
}
}
contract AccessMint is Claimable {
mapping(address => bool) private mintAccess;
modifier onlyAccessMint {
require(msg.sender == owner || mintAccess[msg.sender] == true);
_;
}
function grantAccessMint(address _address)
onlyOwner
public
{
mintAccess[_address] = true;
}
function revokeAccessMint(address _address)
onlyOwner
public
{
mintAccess[_address] = false;
}
}
contract Gold is StandardToken, Claimable, AccessMint {
string public constant name = "Gold";
string public constant symbol = "G";
uint8 public constant decimals = 18;
event Mint(
address indexed _to,
uint256 indexed _tokenId
);
function mint(address _to, uint256 _amount)
onlyAccessMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
}
contract CryptoSagaCard is ERC721Token, Claimable, AccessMint {
string public constant name = "CryptoSaga Card";
string public constant symbol = "CARD";
mapping(uint256 => uint8) public tokenIdToRank;
uint256 public numberOfTokenId;
CryptoSagaCardSwap private swapContract;
event CardSwap(address indexed _by, uint256 _tokenId, uint256 _rewardId);
function setCryptoSagaCardSwapContract(address _contractAddress)
public
onlyOwner
{
swapContract = CryptoSagaCardSwap(_contractAddress);
}
function rankOf(uint256 _tokenId)
public view
returns (uint8)
{
return tokenIdToRank[_tokenId];
}
function mint(address _beneficiary, uint256 _amount, uint8 _rank)
onlyAccessMint
public
{
for (uint256 i = 0; i < _amount; i++) {
_mint(_beneficiary, numberOfTokenId);
tokenIdToRank[numberOfTokenId] = _rank;
numberOfTokenId ++;
}
}
function swap(uint256 _tokenId)
onlyOwnerOf(_tokenId)
public
returns (uint256)
{
require(address(swapContract) != address(0));
var _rank = tokenIdToRank[_tokenId];
var _rewardId = swapContract.swapCardForReward(this, _rank);
CardSwap(ownerOf(_tokenId), _tokenId, _rewardId);
_burn(_tokenId);
return _rewardId;
}
}
contract CryptoSagaCardSwap is Ownable {
address internal cardAddess;
modifier onlyCard {
require(msg.sender == cardAddess);
_;
}
function setCardContract(address _contractAddress)
public
onlyOwner
{
cardAddess = _contractAddress;
}
function swapCardForReward(address _by, uint8 _rank)
onlyCard
public
returns (uint256);
}
contract CryptoSagaHero is ERC721Token, Claimable, Pausable, AccessMint, AccessDeploy, AccessDeposit {
string public constant name = "CryptoSaga Hero";
string public constant symbol = "HERO";
struct HeroClass {
string className;
uint8 classRank;
uint8 classRace;
uint32 classAge;
uint8 classType;
uint32 maxLevel;
uint8 aura;
uint32[5] baseStats;
uint32[5] minIVForStats;
uint32[5] maxIVForStats;
uint32 currentNumberOfInstancedHeroes;
}
struct HeroInstance {
uint32 heroClassId;
string heroName;
uint32 currentLevel;
uint32 currentExp;
uint32 lastLocationId;
uint256 availableAt;
uint32[5] currentStats;
uint32[5] ivForStats;
}
uint32 public requiredExpIncreaseFactor = 100;
uint256 public requiredGoldIncreaseFactor = 1000000000000000000;
mapping(uint32 => HeroClass) public heroClasses;
uint32 public numberOfHeroClasses;
mapping(uint256 => HeroInstance) public tokenIdToHeroInstance;
uint256 public numberOfTokenIds;
Gold public goldContract;
mapping(address => uint256) public addressToGoldDeposit;
uint32 private seed = 0;
event DefineType(
address indexed _by,
uint32 indexed _typeId,
string _className
);
event LevelUp(
address indexed _by,
uint256 indexed _tokenId,
uint32 _newLevel
);
event Deploy(
address indexed _by,
uint256 indexed _tokenId,
uint32 _locationId,
uint256 _duration
);
function getClassInfo(uint32 _classId)
external view
returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs)
{
var _cl = heroClasses[_classId];
return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats);
}
function getClassName(uint32 _classId)
external view
returns (string)
{
return heroClasses[_classId].className;
}
function getClassRank(uint32 _classId)
external view
returns (uint8)
{
return heroClasses[_classId].classRank;
}
function getClassMintCount(uint32 _classId)
external view
returns (uint32)
{
return heroClasses[_classId].currentNumberOfInstancedHeroes;
}
function getHeroInfo(uint256 _tokenId)
external view
returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp)
{
HeroInstance memory _h = tokenIdToHeroInstance[_tokenId];
var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4];
return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp);
}
function getHeroClassId(uint256 _tokenId)
external view
returns (uint32)
{
return tokenIdToHeroInstance[_tokenId].heroClassId;
}
function getHeroName(uint256 _tokenId)
external view
returns (string)
{
return tokenIdToHeroInstance[_tokenId].heroName;
}
function getHeroLevel(uint256 _tokenId)
external view
returns (uint32)
{
return tokenIdToHeroInstance[_tokenId].currentLevel;
}
function getHeroLocation(uint256 _tokenId)
external view
returns (uint32)
{
return tokenIdToHeroInstance[_tokenId].lastLocationId;
}
function getHeroAvailableAt(uint256 _tokenId)
external view
returns (uint256)
{
return tokenIdToHeroInstance[_tokenId].availableAt;
}
function getHeroBP(uint256 _tokenId)
public view
returns (uint32)
{
var _tmp = tokenIdToHeroInstance[_tokenId].currentStats;
return (_tmp[0] + _tmp[1] + _tmp[2] + _tmp[3] + _tmp[4]);
}
function getHeroRequiredGoldForLevelUp(uint256 _tokenId)
public view
returns (uint256)
{
return (uint256(2) ** (tokenIdToHeroInstance[_tokenId].currentLevel / 10)) * requiredGoldIncreaseFactor;
}
function getHeroRequiredExpForLevelUp(uint256 _tokenId)
public view
returns (uint32)
{
return ((tokenIdToHeroInstance[_tokenId].currentLevel + 2) * requiredExpIncreaseFactor);
}
function getGoldDepositOfAddress(address _address)
external view
returns (uint256)
{
return addressToGoldDeposit[_address];
}
function getTokenIdOfAddressAndIndex(address _address, uint256 _index)
external view
returns (uint256)
{
return tokensOf(_address)[_index];
}
function getTotalBPOfAddress(address _address)
external view
returns (uint32)
{
var _tokens = tokensOf(_address);
uint32 _totalBP = 0;
for (uint256 i = 0; i < _tokens.length; i ++) {
_totalBP += getHeroBP(_tokens[i]);
}
return _totalBP;
}
function setHeroName(uint256 _tokenId, string _name)
onlyOwnerOf(_tokenId)
public
{
tokenIdToHeroInstance[_tokenId].heroName = _name;
}
function setGoldContract(address _contractAddress)
onlyOwner
public
{
goldContract = Gold(_contractAddress);
}
function setRequiredExpIncreaseFactor(uint32 _value)
onlyOwner
public
{
requiredExpIncreaseFactor = _value;
}
function setRequiredGoldIncreaseFactor(uint256 _value)
onlyOwner
public
{
requiredGoldIncreaseFactor = _value;
}
function CryptoSagaHero(address _goldAddress)
public
{
require(_goldAddress != address(0));
setGoldContract(_goldAddress);
defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]);
defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]);
defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]);
defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]);
defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]);
}
function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats)
onlyOwner
public
{
require(_classRank < 5);
require(_classType < 3);
require(_aura < 5);
require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]);
HeroClass memory _heroType = HeroClass({
className: _className,
classRank: _classRank,
classRace: _classRace,
classAge: _classAge,
classType: _classType,
maxLevel: _maxLevel,
aura: _aura,
baseStats: _baseStats,
minIVForStats: _minIVForStats,
maxIVForStats: _maxIVForStats,
currentNumberOfInstancedHeroes: 0
});
heroClasses[numberOfHeroClasses] = _heroType;
DefineType(msg.sender, numberOfHeroClasses, _heroType.className);
numberOfHeroClasses ++;
}
function mint(address _owner, uint32 _heroClassId)
onlyAccessMint
public
returns (uint256)
{
require(_owner != address(0));
require(_heroClassId < numberOfHeroClasses);
var _heroClassInfo = heroClasses[_heroClassId];
_mint(_owner, numberOfTokenIds);
uint32[5] memory _ivForStats;
uint32[5] memory _initialStats;
for (uint8 i = 0; i < 5; i++) {
_ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i]));
_initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i];
}
HeroInstance memory _heroInstance = HeroInstance({
heroClassId: _heroClassId,
heroName: "",
currentLevel: 1,
currentExp: 0,
lastLocationId: 0,
availableAt: now,
currentStats: _initialStats,
ivForStats: _ivForStats
});
tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance;
numberOfTokenIds ++;
_heroClassInfo.currentNumberOfInstancedHeroes ++;
return numberOfTokenIds - 1;
}
function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration)
onlyAccessDeploy
public
returns (bool)
{
require(ownerOf(_tokenId) != address(0));
var _heroInstance = tokenIdToHeroInstance[_tokenId];
require(_heroInstance.availableAt <= now);
_heroInstance.lastLocationId = _locationId;
_heroInstance.availableAt = now + _duration;
Deploy(msg.sender, _tokenId, _locationId, _duration);
}
function addExp(uint256 _tokenId, uint32 _exp)
onlyAccessDeploy
public
returns (bool)
{
require(ownerOf(_tokenId) != address(0));
var _heroInstance = tokenIdToHeroInstance[_tokenId];
var _newExp = _heroInstance.currentExp + _exp;
require(_newExp == uint256(uint128(_newExp)));
_heroInstance.currentExp += _newExp;
}
function addDeposit(address _to, uint256 _amount)
onlyAccessDeposit
public
{
addressToGoldDeposit[_to] += _amount;
}
function levelUp(uint256 _tokenId)
onlyOwnerOf(_tokenId) whenNotPaused
public
{
var _heroInstance = tokenIdToHeroInstance[_tokenId];
require(_heroInstance.availableAt <= now);
var _heroClassInfo = heroClasses[_heroInstance.heroClassId];
require(_heroInstance.currentLevel < _heroClassInfo.maxLevel);
var requiredExp = getHeroRequiredExpForLevelUp(_tokenId);
require(_heroInstance.currentExp >= requiredExp);
var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId);
var _ownerOfToken = ownerOf(_tokenId);
require(addressToGoldDeposit[_ownerOfToken] >= requiredGold);
_heroInstance.currentLevel += 1;
for (uint8 i = 0; i < 5; i++) {
_heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i];
}
_heroInstance.currentExp -= requiredExp;
addressToGoldDeposit[_ownerOfToken] -= requiredGold;
LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel);
}
function transferDeposit(uint256 _amount)
whenNotPaused
public
{
require(goldContract.allowance(msg.sender, this) >= _amount);
if (goldContract.transferFrom(msg.sender, this, _amount)) {
addressToGoldDeposit[msg.sender] += _amount;
}
}
function withdrawDeposit(uint256 _amount)
public
{
require(addressToGoldDeposit[msg.sender] >= _amount);
if (goldContract.transfer(msg.sender, _amount)) {
addressToGoldDeposit[msg.sender] -= _amount;
}
}
function random(uint32 _upper, uint32 _lower)
private
returns (uint32)
{
require(_upper > _lower);
seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now));
return seed % (_upper - _lower) + _lower;
}
}
contract CryptoSagaCardSwapMerculet is Pausable{
address public wallet1;
address public wallet2;
ERC20 public merculetContract;
CryptoSagaHero public heroContract;
uint256 public merculetPrice = 1000000000000000000000;
mapping(uint32 => bool) public blackList;
uint32 private seed = 0;
function setMerculetPrice(uint256 _value)
onlyOwner
public
{
merculetPrice = _value;
}
function setBlacklist(uint32 _classId, bool _value)
onlyOwner
public
{
blackList[_classId] = _value;
}
function CryptoSagaCardSwapMerculet(address _heroAddress, address _tokenAddress, address _walletAddress1, address _walletAddress2)
public
{
require(_heroAddress != address(0));
require(_walletAddress1 != address(0));
require(_walletAddress2 != address(0));
wallet1 = _walletAddress1;
wallet2 = _walletAddress1;
heroContract = CryptoSagaHero(_heroAddress);
merculetContract = ERC20(_tokenAddress);
}
function payWithMerculet(uint256 _amount)
whenNotPaused
public
{
require(msg.sender != address(0));
require(_amount >= 1 && _amount <= 5);
var _priceOfBundle = merculetPrice * _amount;
require(merculetContract.allowance(msg.sender, this) >= _priceOfBundle);
if (merculetContract.transferFrom(msg.sender, this, _priceOfBundle)) {
merculetContract.transfer(wallet1, _priceOfBundle / 2);
merculetContract.transfer(wallet2, _priceOfBundle / 2);
for (uint i = 0; i < _amount; i ++) {
var _randomValue = random(10000, 0);
uint8 _heroRankToMint = 0;
if (_randomValue < 5000) {
_heroRankToMint = 1;
} else if (_randomValue < 9550) {
_heroRankToMint = 2;
} else if (_randomValue < 9950) {
_heroRankToMint = 3;
} else {
_heroRankToMint = 4;
}
summonHero(msg.sender, _heroRankToMint);
}
}
}
function summonHero(address _to, uint8 _heroRankToMint)
private
returns (uint256)
{
uint32 _numberOfClasses = heroContract.numberOfHeroClasses();
uint32[] memory _candidates = new uint32[](_numberOfClasses);
uint32 _count = 0;
for (uint32 i = 0; i < _numberOfClasses; i ++) {
if (heroContract.getClassRank(i) == _heroRankToMint && blackList[i] != true) {
_candidates[_count] = i;
_count++;
}
}
require(_count != 0);
return heroContract.mint(_to, _candidates[random(_count, 0)]);
}
function random(uint32 _upper, uint32 _lower)
private
returns (uint32)
{
require(_upper > _lower);
seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now));
return seed % (_upper - _lower) + _lower;
}
} | 0 |
pragma solidity ^0.4.24;
contract dappVolumeHearts {
mapping(uint256 => uint256) public totals;
function getTotalHeartsByDappId(uint256 dapp_id) public view returns(uint256) {
return totals[dapp_id];
}
}
contract DappVolumeHearts {
dappVolumeHearts firstContract;
using SafeMath for uint256;
address public contractOwner;
address public lastAddress;
address constant public firstContractAddress = 0x6ACD16200a2a046bf207D1B263202ec1A75a7D51;
mapping(uint256 => uint256) public totals;
modifier onlyContractOwner {
require(msg.sender == contractOwner);
_;
}
constructor() public {
contractOwner = msg.sender;
lastAddress = msg.sender;
firstContract = dappVolumeHearts(firstContractAddress);
}
function withdraw() public onlyContractOwner {
contractOwner.transfer(address(this).balance);
}
function update(uint256 dapp_id) public payable {
require(msg.value >= 2000000000000000);
require(dapp_id > 0);
totals[dapp_id] = totals[dapp_id].add(msg.value);
if (lastAddress.send(msg.value.div(2)) == true) {
lastAddress = msg.sender;
}
}
function getTotalHeartsByDappId(uint256 dapp_id) public view returns(uint256) {
return totals[dapp_id].add(firstContract.getTotalHeartsByDappId(dapp_id));
}
function getBalance() public view returns(uint256){
return address(this).balance;
}
}
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.21;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant 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() {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
modifier authorized(bytes4 sig) {
assert(isAuthorized(msg.sender, sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal 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);
}
}
function assert(bool x) internal {
if (!x) throw;
}
}
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(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 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);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
contract DSThing is DSAuth, DSNote, DSMath {
}
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() constant returns (bytes32, bool) {
return (val,has);
}
function read() constant returns (bytes32) {
var (wut, has) = peek();
assert(has);
return wut;
}
function poke(bytes32 wut) note auth {
val = wut;
has = true;
}
function void() note auth {
has = false;
}
}
contract Medianizer is DSValue {
mapping (bytes12 => address) public values;
mapping (address => bytes12) public indexes;
bytes12 public next = 0x1;
uint96 public min = 0x1;
function set(address wat) auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) note auth {
if (pos == 0x0) throw;
if (wat != 0 && indexes[wat] != 0) throw;
indexes[values[pos]] = 0;
if (wat != 0) {
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) note auth {
if (min_ == 0x0) throw;
min = min_;
}
function setNext(bytes12 next_) note auth {
if (next_ == 0x0) throw;
next = next_;
}
function unset(bytes12 pos) {
set(pos, 0);
}
function unset(address wat) {
set(indexes[wat], 0);
}
function poke() {
poke(0);
}
function poke(bytes32) note {
(val, has) = compute();
}
function compute() constant returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (values[bytes12(i)] != 0) {
var (wut, wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < min) return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(wuts[(ctr / 2) - 1]);
uint128 val2 = uint128(wuts[ctr / 2]);
value = bytes32(wdiv(hadd(val1, val2), 2 ether));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract ChainmonstersMedianizer is Ownable {
address medianizerBase;
Medianizer makerMed;
constructor(address _medianizerContract) public {
owner = msg.sender;
medianizerBase = _medianizerContract;
makerMed = Medianizer(medianizerBase);
}
function updateMedianizerBase(address _medianizerContract) public onlyOwner {
medianizerBase = _medianizerContract;
makerMed = Medianizer(medianizerBase);
}
function getUSDPrice() public view returns (uint256) {
return bytesToUint(toBytes(makerMed.read()));
}
function isMedianizer() public view returns (bool) {
return true;
}
function toBytes(bytes32 _data) public pure returns (bytes) {
return abi.encodePacked(_data);
}
function bytesToUint(bytes b) public pure returns (uint256){
uint256 number;
for(uint i=0;i<b.length;i++){
number = number + uint(b[i])*(2**(8*(b.length-(i+1))));
}
return number;
}
}
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) {
if (b >= a) {
return 0;
}
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ChainmonstersShop {
using SafeMath for uint256;
address public owner;
bool started;
uint256 public totalCoinsSold;
address medianizer;
uint256 shiftValue = 100;
uint256 multiplier = 10000;
struct Package {
uint256 price;
string packageReference;
bool isActive;
uint256 coinsAmount;
}
event LogPurchase(address _from, uint256 _price, string _packageReference);
mapping(address => uint256) public addressToCoinsPurchased;
Package[] packages;
constructor() public {
owner = msg.sender;
started = false;
}
function startShop() public onlyOwner {
require(started == false);
}
function pauseShop() public onlyOwner {
require(started == true);
}
function isStarted() public view returns (bool success) {
return started;
}
function purchasePackage(uint256 _id) public
payable
returns (bool success)
{
require(started == true);
require(packages[_id].isActive == true);
require(msg.sender != owner);
require(msg.value == priceOf(packages[_id].price));
addressToCoinsPurchased[msg.sender] += packages[_id].coinsAmount;
totalCoinsSold += packages[_id].coinsAmount;
emit LogPurchase(msg.sender, msg.value, packages[_id].packageReference);
}
function addPackage(uint256 _price, string _packageReference, bool _isActive, uint256 _coinsAmount)
external
onlyOwner
{
require(_price > 0);
Package memory _package = Package({
price: uint256(_price),
packageReference: string(_packageReference),
isActive: bool(_isActive),
coinsAmount: uint256(_coinsAmount)
});
uint256 newPackageId = packages.push(_package);
}
function setPrice(uint256 _packageId, uint256 _newPrice)
external
onlyOwner
{
require(packages[_packageId].price > 0);
packages[_packageId].price = _newPrice;
}
function getPackage(uint256 _id)
external
view
returns (uint256 priceInETH, uint256 priceInUSD, string packageReference, uint256 coinsAmount )
{
Package storage package = packages[_id];
priceInETH = priceOf(_id);
priceInUSD = package.price;
packageReference = package.packageReference;
coinsAmount = package.coinsAmount;
}
function priceOf(uint256 _packageId)
public
view
returns (uint256)
{
if (medianizer == address(0x0)) {
return packages[_packageId].price;
}
else {
uint256 USDinWei = ChainmonstersMedianizer(medianizer).getUSDPrice();
uint256 multValue = (packages[_packageId].price.mul(multiplier)).div(USDinWei.div(1 ether));
uint256 inWei = multValue.mul(1 ether);
uint256 result = inWei.div(shiftValue.mul(multiplier));
return result;
}
}
function getPackagesCount()
public
view
returns (uint256)
{
return packages.length;
}
function setMedianizer(ChainmonstersMedianizer _medianizer)
public
onlyOwner
{
require(_medianizer.isMedianizer(), "given address is not a medianizer contract!");
medianizer = _medianizer;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
} | 0 |
pragma solidity ^0.4.24;
interface HourglassInterface {
function() payable external;
function buy(address _playerAddress) payable external returns(uint256);
function sell(uint256 _amountOfTokens) external;
function reinvest() external;
function withdraw() external;
function exit() external;
function dividendsOf(address _playerAddress) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function stakingRequirement() external view returns(uint256);
}
contract Divies {
using SafeMath for uint256;
using UintCompressor for uint256;
HourglassInterface constant BTBcontract_ = HourglassInterface(0xEDEaB579e57a7D66297D0a67302647bB109db7A8);
uint256 public pusherTracker_ = 100;
mapping (address => Pusher) public pushers_;
struct Pusher
{
uint256 tracker;
uint256 time;
}
uint256 public rateLimiter_;
modifier isHuman() {
require(tx.origin == msg.sender);
_;
}
function balances()
public
view
returns(uint256)
{
return (address(this).balance);
}
function deposit()
external
payable
{
}
function() external payable {}
event onDistribute(
address pusher,
uint256 startingBalance,
uint256 masternodePayout,
uint256 finalBalance,
uint256 compressedData
);
function distribute(uint256 _percent)
public
isHuman()
{
require(_percent > 0 && _percent < 100, "please pick a percent between 1 and 99");
address _pusher = msg.sender;
uint256 _bal = address(this).balance;
uint256 _mnPayout;
uint256 _compressedData;
if (
pushers_[_pusher].tracker <= pusherTracker_.sub(100) &&
pushers_[_pusher].time.add(1 hours) < now
)
{
pushers_[_pusher].tracker = pusherTracker_;
pusherTracker_++;
if (BTBcontract_.balanceOf(_pusher) >= BTBcontract_.stakingRequirement())
_mnPayout = (_bal / 10) / 3;
uint256 _stop = (_bal.mul(100 - _percent)) / 100;
BTBcontract_.buy.value(_bal)(_pusher);
BTBcontract_.sell(BTBcontract_.balanceOf(address(this)));
uint256 _tracker = BTBcontract_.dividendsOf(address(this));
while (_tracker >= _stop)
{
BTBcontract_.reinvest();
BTBcontract_.sell(BTBcontract_.balanceOf(address(this)));
_tracker = (_tracker.mul(81)) / 100;
}
BTBcontract_.withdraw();
} else {
_compressedData = _compressedData.insert(1, 47, 47);
}
pushers_[_pusher].time = now;
_compressedData = _compressedData.insert(now, 0, 14);
_compressedData = _compressedData.insert(pushers_[_pusher].tracker, 15, 29);
_compressedData = _compressedData.insert(pusherTracker_, 30, 44);
_compressedData = _compressedData.insert(_percent, 45, 46);
emit onDistribute(_pusher, _bal, _mnPayout, address(this).balance, _compressedData);
}
}
library UintCompressor {
using SafeMath for *;
function insert(uint256 _var, uint256 _include, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
_end = exponent(_end).mul(10);
_start = exponent(_start);
require(_include < (_end / _start));
if (_include > 0)
_include = _include.mul(_start);
return((_var.sub((_var / _start).mul(_start))).add(_include).add((_var / _end).mul(_end)));
}
function extract(uint256 _input, uint256 _start, uint256 _end)
internal
pure
returns(uint256)
{
require(_end < 77 && _start < 77, "start/end must be less than 77");
require(_end >= _start, "end must be >= start");
_end = exponent(_end).mul(10);
_start = exponent(_start);
return((((_input / _start).mul(_start)).sub((_input / _end).mul(_end))) / _start);
}
function exponent(uint256 _position)
private
pure
returns(uint256)
{
return((10).pwr(_position));
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.16;
contract Token {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) returns (bool);
event Transfer(address indexed from, address indexed to, 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 Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract BillPokerPreICO is Ownable, Pausable {
using SafeMath for uint;
address public tokenWallet = 0xf91E6d611ec35B985bADAD2F0DA96820930B9BD2;
uint public tokensSold;
uint public weiRaised;
mapping (address => uint256) public holdTokens;
mapping (address => uint256) public purchaseTokens;
address[] public holdTokenInvestors;
Token public token = Token(0xc305fcdc300fa43c527e9327711f360e79528a70);
uint public constant minInvest = 0.0001 ether;
uint public constant tokensLimit = 25000000 ether;
uint256 public startTime = 1510339500;
uint256 public endTime = 1519689600;
uint public price = 0.0001 ether;
bool public isHoldTokens = false;
uint public investorCount;
mapping (bytes32 => Promo) public promoMap;
struct Promo {
bool enable;
uint investorPercentToken;
address dealer;
uint dealerPercentToken;
uint dealerPercentETH;
uint buyCount;
uint investorTokenAmount;
uint dealerTokenAmount;
uint investorEthAmount;
uint dealerEthAmount;
}
function addPromo(bytes32 promoPublicKey, uint userPercentToken, address dealer, uint dealerPercentToken, uint dealerPercentETH) public onlyOwner {
promoMap[promoPublicKey] = Promo(true, userPercentToken, dealer, dealerPercentToken, dealerPercentETH, 0, 0, 0, 0, 0);
}
function removePromo(bytes32 promoPublicKey) public onlyOwner {
promoMap[promoPublicKey].enable = false;
}
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function() public payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public whenNotPaused payable {
require(startTime <= now && now <= endTime);
uint weiAmount = msg.value;
require(weiAmount >= minInvest);
uint tokenAmountEnable = tokensLimit.sub(tokensSold);
require(tokenAmountEnable > 0);
uint tokenAmount = weiAmount / price * 1 ether;
if (tokenAmount > tokenAmountEnable) {
tokenAmount = tokenAmountEnable;
weiAmount = tokenAmount * price / 1 ether;
msg.sender.transfer(msg.value.sub(weiAmount));
if (msg.data.length > 0) {
Promo storage promo = promoMap[sha3(msg.data)];
if (promo.enable && promo.dealerPercentETH > 0) {
uint dealerEthAmount = weiAmount * promo.dealerPercentETH / 10000;
promo.dealer.transfer(dealerEthAmount);
weiAmount = weiAmount.sub(dealerEthAmount);
promo.dealerEthAmount += dealerEthAmount;
}
}
}
else {
uint countBonusAmount = tokenAmount * getCountBonus(weiAmount) / 1000;
uint timeBonusAmount = tokenAmount * getTimeBonus(now) / 1000;
if (msg.data.length > 0) {
bytes32 promoPublicKey = sha3(msg.data);
promo = promoMap[promoPublicKey];
if (promo.enable) {
promo.buyCount++;
promo.investorTokenAmount += tokenAmount;
promo.investorEthAmount += weiAmount;
if (promo.dealerPercentToken > 0) {
uint dealerTokenAmount = tokenAmount * promo.dealerPercentToken / 10000;
sendTokens(promo.dealer, dealerTokenAmount);
promo.dealerTokenAmount += dealerTokenAmount;
}
if (promo.dealerPercentETH > 0) {
dealerEthAmount = weiAmount * promo.dealerPercentETH / 10000;
promo.dealer.transfer(dealerEthAmount);
weiAmount = weiAmount.sub(dealerEthAmount);
promo.dealerEthAmount += dealerEthAmount;
}
if (promo.investorPercentToken > 0) {
uint promoBonusAmount = tokenAmount * promo.investorPercentToken / 10000;
tokenAmount += promoBonusAmount;
}
}
}
tokenAmount += countBonusAmount + timeBonusAmount;
if (tokenAmount > tokenAmountEnable) {
tokenAmount = tokenAmountEnable;
}
}
if (purchaseTokens[beneficiary] == 0) investorCount++;
purchaseTokens[beneficiary] = purchaseTokens[beneficiary].add(tokenAmount);
sendTokens(beneficiary, tokenAmount);
weiRaised = weiRaised.add(weiAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokenAmount);
}
function sendTokens(address to, uint tokenAmount) private {
if (isHoldTokens) {
if (holdTokens[to] == 0) holdTokenInvestors.push(to);
holdTokens[to] = holdTokens[to].add(tokenAmount);
}
else {
require(token.transferFrom(tokenWallet, to, tokenAmount));
}
tokensSold = tokensSold.add(tokenAmount);
}
uint[] etherForCountBonus = [2 ether, 3 ether, 5 ether, 7 ether, 9 ether, 12 ether, 15 ether, 20 ether, 25 ether, 30 ether, 35 ether, 40 ether, 45 ether, 50 ether, 60 ether, 70 ether, 80 ether, 90 ether, 100 ether, 120 ether, 150 ether, 200 ether, 250 ether, 300 ether, 350 ether, 400 ether, 450 ether, 500 ether];
uint[] amountForCountBonus = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 90, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150];
function getCountBonus(uint weiAmount) public constant returns (uint) {
for (uint i = 0; i < etherForCountBonus.length; i++) {
if (weiAmount < etherForCountBonus[i]) return amountForCountBonus[i];
}
return amountForCountBonus[amountForCountBonus.length - 1];
}
function getTimeBonus(uint time) public constant returns (uint) {
if (time < startTime + 604800) return 250;
if (time < startTime + 604800) return 200;
if (time < startTime + 259200) return 100;
return 0;
}
function withdrawal(address to) public onlyOwner {
to.transfer(this.balance);
}
function holdTokenInvestorsCount() public constant returns(uint){
return holdTokenInvestors.length;
}
uint public sendInvestorIndex = 0;
function finalSendTokens() public onlyOwner {
isHoldTokens = false;
for (uint i = sendInvestorIndex; i < holdTokenInvestors.length; i++) {
address investor = holdTokenInvestors[i];
uint tokenAmount = holdTokens[investor];
if (tokenAmount > 0) {
holdTokens[investor] = 0;
require(token.transferFrom(tokenWallet, investor, tokenAmount));
}
if (msg.gas < 100000) {
sendInvestorIndex = i;
return;
}
}
sendInvestorIndex = holdTokenInvestors.length;
}
} | 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);
function burn(uint256 value) external;
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 FinexboxToken is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string public name;
uint8 public decimals;
string public symbol;
constructor() public {
decimals = 8;
_totalSupply = 33500000 * 10 ** uint(decimals);
_balances[msg.sender] = _totalSupply;
name = "FinexboxToken";
symbol = "FNB";
}
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 _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 burn(uint256 value) public {
require(value <= _balances[msg.sender]);
_totalSupply = _totalSupply.sub(value);
_balances[msg.sender] = _balances[msg.sender].sub(value);
emit Transfer(msg.sender, address(0), value);
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Admin is Ownable {
mapping(address => bool) public adminlist;
event AdminAddressAdded(address addr);
event AdminAddressRemoved(address addr);
function isAdmin() public view returns(bool) {
if (owner == msg.sender) {
return true;
}
return adminlist[msg.sender];
}
function isAdminAddress(address addr) view public returns(bool) {
return adminlist[addr];
}
function addAddressToAdminlist(address addr) onlyOwner public returns(bool success) {
if (!adminlist[addr]) {
adminlist[addr] = true;
AdminAddressAdded(addr);
success = true;
}
}
function removeAddressFromAdminlist(address addr) onlyOwner public returns(bool success) {
if (adminlist[addr]) {
adminlist[addr] = false;
AdminAddressRemoved(addr);
success = true;
}
}
}
contract Pausable is Ownable, Admin {
event Pause();
event Unpause();
bool public paused = true;
modifier whenNotPaused() {
require(!paused || isAdmin());
_;
}
modifier whenPaused() {
require(paused || isAdmin());
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x / y;
return z;
}
}
contract StandardToken is ERC20, SafeMath {
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4) ;
_;
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) public returns (bool){
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSubtract(balances[_from], _value);
allowed[_from][msg.sender] = safeSubtract(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint) {
return balances[_owner];
}
function approve(address _spender, uint _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint) {
return allowed[_owner][_spender];
}
}
contract HeroNodeToken is StandardToken, Pausable {
string public constant name = "HeroNodeToken";
string public constant symbol = "HNC";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public constant total = 20 * (10**8) * 10**decimals;
function HeroNodeToken() public {
balances[msg.sender] = total;
Transfer(0x0, msg.sender, total);
}
function totalSupply() public view returns (uint256) {
return total;
}
function transfer(address _to, uint _value) whenNotPaused public returns (bool) {
return super.transfer(_to,_value);
}
function approve(address _spender, uint _value) whenNotPaused public returns (bool) {
return super.approve(_spender,_value);
}
function airdropToAddresses(address[] addrs, uint256 amount) whenNotPaused public {
for (uint256 i = 0; i < addrs.length; i++) {
transfer(addrs[i], amount);
}
}
} | 1 |
pragma solidity ^0.4.11;
contract Grid {
address admin;
uint public defaultPrice;
uint public feeRatio;
uint public incrementRate;
struct Pixel {
address owner;
uint price;
uint24 color;
}
Pixel[1000][1000] pixels;
mapping(address => uint) pendingWithdrawals;
mapping(address => string) messages;
event PixelTransfer(uint16 row, uint16 col, uint price, address prevOwner, address newOwner);
event PixelColor(uint16 row, uint16 col, address owner, uint24 color);
event PixelPrice(uint16 row, uint16 col, address owner, uint price);
function Grid(
uint _defaultPrice,
uint _feeRatio,
uint _incrementRate) {
admin = msg.sender;
defaultPrice = _defaultPrice;
feeRatio = _feeRatio;
incrementRate = _incrementRate;
}
modifier onlyAdmin {
require(msg.sender == admin);
_;
}
modifier onlyOwner(uint16 row, uint16 col) {
require(msg.sender == getPixelOwner(row, col));
_;
}
modifier validPixel(uint16 row, uint16 col) {
require(row < 1000 && col < 1000);
_;
}
function() payable {}
function setAdmin(address _admin) onlyAdmin {
admin = _admin;
}
function setFeeRatio(uint _feeRatio) onlyAdmin {
feeRatio = _feeRatio;
}
function setDefaultPrice(uint _defaultPrice) onlyAdmin {
defaultPrice = _defaultPrice;
}
function getPixelColor(uint16 row, uint16 col) constant
validPixel(row, col) returns (uint24) {
return pixels[row][col].color;
}
function getPixelOwner(uint16 row, uint16 col) constant
validPixel(row, col) returns (address) {
if (pixels[row][col].owner == 0) {
return admin;
}
return pixels[row][col].owner;
}
function getPixelPrice(uint16 row, uint16 col) constant
validPixel(row,col) returns (uint) {
if (pixels[row][col].owner == 0) {
return defaultPrice;
}
return pixels[row][col].price;
}
function getUserMessage(address user) constant returns (string) {
return messages[user];
}
function checkPendingWithdrawal() constant returns (uint) {
return pendingWithdrawals[msg.sender];
}
function withdraw() {
if (pendingWithdrawals[msg.sender] > 0) {
uint amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
}
function buyPixel(uint16 row, uint16 col, uint24 newColor) payable {
uint balance = pendingWithdrawals[msg.sender];
if (row >= 1000 || col >= 1000) {
pendingWithdrawals[msg.sender] = SafeMath.add(balance, msg.value);
return;
}
uint price = getPixelPrice(row, col);
address owner = getPixelOwner(row, col);
if (msg.value < price) {
pendingWithdrawals[msg.sender] = SafeMath.add(balance, msg.value);
return;
}
uint fee = SafeMath.div(msg.value, feeRatio);
uint payout = SafeMath.sub(msg.value, fee);
uint adminBalance = pendingWithdrawals[admin];
pendingWithdrawals[admin] = SafeMath.add(adminBalance, fee);
uint ownerBalance = pendingWithdrawals[owner];
pendingWithdrawals[owner] = SafeMath.add(ownerBalance, payout);
uint increase = SafeMath.div(SafeMath.mul(price, incrementRate), 100);
pixels[row][col].price = SafeMath.add(price, increase);
pixels[row][col].owner = msg.sender;
PixelTransfer(row, col, price, owner, msg.sender);
setPixelColor(row, col, newColor);
}
function setPixelColor(uint16 row, uint16 col, uint24 color)
validPixel(row, col) onlyOwner(row, col) {
if (pixels[row][col].color != color) {
pixels[row][col].color = color;
PixelColor(row, col, pixels[row][col].owner, color);
}
}
function setPixelPrice(uint16 row, uint16 col, uint newPrice)
validPixel(row, col) onlyOwner(row, col) {
require(pixels[row][col].price > newPrice);
pixels[row][col].price = newPrice;
PixelPrice(row, col, pixels[row][col].owner, newPrice);
}
function setUserMessage(string message) {
messages[msg.sender] = message;
}
}
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;
}
} | 1 |
pragma solidity ^0.4.21;
contract SafeMath {
uint256 constant MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) {
require(x <= MAX_UINT256 - y);
return x + y;
}
function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) {
require(x >= y);
return x - y;
}
function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) {
if (y == 0) {
return 0;
}
require(x <= (MAX_UINT256 / y));
return x * y;
}
}
contract Owned {
address public owner;
address public newOwner;
function Owned() public{
owner = msg.sender;
}
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnerUpdate(address _prevOwner, address _newOwner);
}
contract IERC20Token {
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 CreditGAMEInterface {
function isGameApproved(address _gameAddress) view public returns(bool);
function createLock(address _winner, uint _totalParticipationAmount, uint _tokenLockDuration) public;
function removeFailedGame() public;
function removeLock() public;
function cleanUp() public;
function checkIfLockCanBeRemoved(address _gameAddress) public view returns(bool);
}
contract LuckyTree is Owned, SafeMath{
uint public leafPrice;
uint public gameStart;
uint public gameDuration;
uint public tokenLockDuration;
uint public totalParticipationAmount;
uint public totalLockedAmount;
uint public numberOfLeafs;
uint public participantIndex;
bool public fundsTransfered;
address public winner;
mapping(uint => address) public participants;
mapping(uint => uint) public participationAmount;
mapping(address => bool) public hasParticipated;
mapping(address => bool) public hasWithdrawn;
mapping(address => uint) public participantIndexes;
mapping(uint => address) public leafOwners;
event GameWinner(address winner);
event GameEnded(uint block);
event GameStarted(uint block);
event GameFailed(uint block);
event GameLocked(uint block);
event GameUnlocked(uint block);
enum state{
pending,
running,
paused,
finished,
closed,
claimed
}
state public gameState;
address public tokenAddress = 0xfc6b46d20584a7f736c0d9084ab8b1a8e8c01a38;
address public creditGameAddress = 0x7f135d5d5c1d2d44cf6abb7d09735466ba474799;
function LuckyTree(
uint _leafPrice,
uint _gameStart,
uint _gameDuration,
uint _tokenLockDuration) public{
leafPrice = _leafPrice;
gameStart = _gameStart;
gameDuration = _gameDuration;
tokenLockDuration = _tokenLockDuration;
gameState = state.pending;
totalParticipationAmount = 0;
numberOfLeafs = 0;
participantIndex = 0;
fundsTransfered = false;
winner = 0x0;
}
function random() internal view returns(uint){
return uint(keccak256(block.number, block.difficulty, numberOfLeafs));
}
function setTokenAddress(address _tokenAddress) public onlyOwner{
tokenAddress = _tokenAddress;
}
function setCreditGameAddress(address _creditGameAddress) public onlyOwner{
creditGameAddress = _creditGameAddress;
}
function pickWinner() internal{
if(numberOfLeafs > 0){
if(participantIndex == 1){
IERC20Token(tokenAddress).transfer(leafOwners[0], totalParticipationAmount);
hasWithdrawn[leafOwners[0]] = true;
CreditGAMEInterface(creditGameAddress).removeFailedGame();
emit GameFailed(block.number);
}else{
uint leafOwnerIndex = random() % numberOfLeafs;
winner = leafOwners[leafOwnerIndex];
emit GameWinner(winner);
lockFunds(winner);
}
}
gameState = state.closed;
}
function lockFunds(address _winner) internal{
require(totalParticipationAmount != 0);
IERC20Token(tokenAddress).transfer(creditGameAddress, totalParticipationAmount);
CreditGAMEInterface(creditGameAddress).createLock(_winner, totalParticipationAmount, tokenLockDuration);
totalLockedAmount = totalParticipationAmount;
emit GameLocked(block.number);
}
function manualLockFunds() public onlyOwner{
require(totalParticipationAmount != 0);
require(CreditGAMEInterface(creditGameAddress).isGameApproved(address(this)) == true);
require(gameState == state.closed);
pickWinner();
}
function closeGame() public onlyOwner{
gameState = state.closed;
}
function unlockFunds() public {
require(gameState == state.closed);
require(hasParticipated[msg.sender] == true);
require(hasWithdrawn[msg.sender] == false);
if(fundsTransfered == false){
require(CreditGAMEInterface(creditGameAddress).checkIfLockCanBeRemoved(address(this)) == true);
CreditGAMEInterface(creditGameAddress).removeLock();
fundsTransfered = true;
emit GameUnlocked(block.number);
}
hasWithdrawn[msg.sender] = true;
uint index = participantIndexes[msg.sender];
uint amount = participationAmount[index];
IERC20Token(tokenAddress).transfer(msg.sender, amount);
totalLockedAmount = IERC20Token(tokenAddress).balanceOf(address(this));
if(totalLockedAmount == 0){
gameState = state.claimed;
CreditGAMEInterface(creditGameAddress).cleanUp();
}
}
function checkInternalBalance() public view returns(uint256 tokenBalance) {
return IERC20Token(tokenAddress).balanceOf(address(this));
}
function receiveApproval(address _from, uint256 _value, address _to, bytes _extraData) public {
require(_to == tokenAddress);
require(_value == leafPrice);
require(gameState != state.closed);
require(CreditGAMEInterface(creditGameAddress).isGameApproved(address(this)) == true);
uint tokensToTake = processTransaction(_from, _value);
IERC20Token(tokenAddress).transferFrom(_from, address(this), tokensToTake);
}
function processTransaction(address _from, uint _value) internal returns (uint) {
require(gameStart <= block.number);
uint valueToProcess = 0;
if(gameStart <= block.number && gameDuration >= block.number){
if(gameState != state.running){
gameState = state.running;
emit GameStarted(block.number);
}
leafOwners[numberOfLeafs] = _from;
numberOfLeafs++;
totalParticipationAmount += _value;
if(hasParticipated[_from] == false){
hasParticipated[_from] = true;
participants[participantIndex] = _from;
participationAmount[participantIndex] = _value;
participantIndexes[_from] = participantIndex;
participantIndex++;
}else{
uint index = participantIndexes[_from];
participationAmount[index] = participationAmount[index] + _value;
}
valueToProcess = _value;
return valueToProcess;
}else if(gameDuration < block.number){
gameState = state.finished;
pickWinner();
return valueToProcess;
}
}
function getVariablesForDapp() public view returns(uint, uint, uint, uint, uint, uint, state){
return(leafPrice, gameStart, gameDuration, tokenLockDuration, totalParticipationAmount, numberOfLeafs, gameState);
}
function manuallyProcessTransaction(address _from, uint _value) onlyOwner public {
require(_value == leafPrice);
require(IERC20Token(tokenAddress).balanceOf(address(this)) >= _value + totalParticipationAmount);
if(gameState == state.running && block.number < gameDuration){
uint tokensToTake = processTransaction(_from, _value);
IERC20Token(tokenAddress).transferFrom(_from, address(this), tokensToTake);
}
}
function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner public {
require(_tokenAddress != tokenAddress);
IERC20Token(_tokenAddress).transfer(_to, _amount);
}
function killContract() onlyOwner public {
selfdestruct(owner);
}
} | 0 |
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
using SafeMath for uint256;
string public name;
string public symbol;
uint256 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 ERC20Token (
string _name,
string _symbol,
uint256 _decimals,
uint256 _totalSupply) public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply * 10 ** decimals;
balanceOf[msg.sender] = totalSupply;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to].add(_value) > balanceOf[_to]);
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract Totti is Ownable, ERC20Token {
event Burn(address indexed from, uint256 value);
function Totti (
string name,
string symbol,
uint256 decimals,
uint256 totalSupply
) ERC20Token (name, symbol, decimals, totalSupply) public {}
function() payable public {
revert();
}
function burn(uint256 _value) onlyOwner 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;
}
} | 1 |
pragma solidity ^0.4.13;
interface tokenRecipient {
function receiveApproval(
address _from,
uint256 _value,
address _token,
bytes _extraData
) public;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract 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 ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract 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 DRCTestToken is BurnableToken, MintableToken, PausableToken {
string public name = 'DRC Test Token';
string public symbol = 'DRCT';
uint8 public decimals = 18;
uint public INITIAL_SUPPLY = 250000000;
uint public SECOND_SUPPLY = 450000000;
uint public THIRD_SUPPLY = 300000000;
uint8 public phase = 1;
function DRCTestToken() public {
totalSupply = INITIAL_SUPPLY + SECOND_SUPPLY + THIRD_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function startSecondPhase() public {
balances[msg.sender] = balances[msg.sender].add(SECOND_SUPPLY);
phase = 2;
}
function startThirdPhase() public {
balances[msg.sender] = balances[msg.sender].add(THIRD_SUPPLY);
phase = 3;
}
function getFirstPhaseCap() public view returns (uint256 firstSupply) {
return INITIAL_SUPPLY;
}
function getSecondPhaseCap() public view returns (uint256 secondSupply) {
return SECOND_SUPPLY;
}
function getThirdPhaseCap() public view returns (uint256 thirdSupply) {
return THIRD_SUPPLY;
}
function getPhase() public view returns (uint8 phaseNumber) {
return phase;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_from, _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;
}
}
} | 1 |
pragma solidity ^0.4.18;
contract InsightsNetwork1 {
address public owner;
address public successor;
mapping (address => uint) public balances;
mapping (address => uint) public unlockTimes;
bool public active;
uint256 _totalSupply;
string public constant name = "INS";
string public constant symbol = "INS";
uint8 public constant decimals = 0;
function InsightsNetwork1() {
owner = msg.sender;
active = true;
}
function register(address newTokenHolder, uint issueAmount) {
require(active);
require(msg.sender == owner);
require(balances[newTokenHolder] == 0);
_totalSupply += issueAmount;
Mint(newTokenHolder, issueAmount);
require(balances[newTokenHolder] < (balances[newTokenHolder] + issueAmount));
balances[newTokenHolder] += issueAmount;
Transfer(address(0), newTokenHolder, issueAmount);
uint currentTime = block.timestamp;
uint unlockTime = currentTime + 365*24*60*60;
assert(unlockTime > currentTime);
unlockTimes[newTokenHolder] = unlockTime;
}
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) returns (bool success) {
return false;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
return false;
}
function approve(address _spender, uint256 _value) returns (bool success) {
return false;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return 0;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function getUnlockTime(address _accountHolder) constant returns (uint256) {
return unlockTimes[_accountHolder];
}
event Mint(address indexed _to, uint256 _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function makeSuccessor(address successorAddr) {
require(active);
require(msg.sender == owner);
successor = successorAddr;
}
function deactivate() {
require(active);
require(msg.sender == owner || (successor != address(0) && msg.sender == successor));
active = false;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract 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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function 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 InsightsNetwork2Base is DetailedERC20("Insights Network", "INSTAR", 18), PausableToken, CappedToken{
uint256 constant ATTOTOKEN_FACTOR = 10**18;
address public predecessor;
address public successor;
uint constant MAX_LENGTH = 1024;
uint constant MAX_PURCHASES = 64;
mapping (address => uint256[]) public lockedBalances;
mapping (address => uint256[]) public unlockTimes;
mapping (address => bool) public imported;
event Import(address indexed account, uint256 amount, uint256 unlockTime);
function InsightsNetwork2Base() public CappedToken(300*1000000*ATTOTOKEN_FACTOR) {
paused = true;
mintingFinished = true;
}
function activate(address _predecessor) public onlyOwner {
require(predecessor == 0);
require(_predecessor != 0);
require(predecessorDeactivated(_predecessor));
predecessor = _predecessor;
unpause();
mintingFinished = false;
}
function lockedBalanceOf(address account) public view returns (uint256 balance) {
uint256 amount;
for (uint256 index = 0; index < lockedBalances[account].length; index++)
if (unlockTimes[account][index] > now)
amount += lockedBalances[account][index];
return amount;
}
function mintBatch(address[] accounts, uint256[] amounts) public onlyOwner canMint returns (bool) {
require(accounts.length == amounts.length);
require(accounts.length <= MAX_LENGTH);
for (uint index = 0; index < accounts.length; index++)
require(mint(accounts[index], amounts[index]));
return true;
}
function mintUnlockTime(address account, uint256 amount, uint256 unlockTime) public onlyOwner canMint returns (bool) {
require(unlockTime > now);
require(lockedBalances[account].length < MAX_PURCHASES);
lockedBalances[account].push(amount);
unlockTimes[account].push(unlockTime);
return super.mint(account, amount);
}
function mintUnlockTimeBatch(address[] accounts, uint256[] amounts, uint256 unlockTime) public onlyOwner canMint returns (bool) {
require(accounts.length == amounts.length);
require(accounts.length <= MAX_LENGTH);
for (uint index = 0; index < accounts.length; index++)
require(mintUnlockTime(accounts[index], amounts[index], unlockTime));
return true;
}
function mintLockPeriod(address account, uint256 amount, uint256 lockPeriod) public onlyOwner canMint returns (bool) {
return mintUnlockTime(account, amount, now + lockPeriod);
}
function mintLockPeriodBatch(address[] accounts, uint256[] amounts, uint256 lockPeriod) public onlyOwner canMint returns (bool) {
return mintUnlockTimeBatch(accounts, amounts, now + lockPeriod);
}
function importBalance(address account) public onlyOwner canMint returns (bool);
function importBalanceBatch(address[] accounts) public onlyOwner canMint returns (bool) {
require(accounts.length <= MAX_LENGTH);
for (uint index = 0; index < accounts.length; index++)
require(importBalance(accounts[index]));
return true;
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= balances[msg.sender] - lockedBalanceOf(msg.sender));
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(value <= balances[from] - lockedBalanceOf(from));
return super.transferFrom(from, to, value);
}
function selfDestruct(address _successor) public onlyOwner whenPaused {
require(mintingFinished);
successor = _successor;
selfdestruct(owner);
}
function predecessorDeactivated(address _predecessor) internal view onlyOwner returns (bool);
}
contract InsightsNetwork3 is InsightsNetwork2Base {
function importBalance(address account) public onlyOwner canMint returns (bool) {
require(!imported[account]);
InsightsNetwork2Base source = InsightsNetwork2Base(predecessor);
uint256 amount = source.balanceOf(account);
require(amount > 0);
imported[account] = true;
uint256 mintAmount = amount - source.lockedBalanceOf(account);
Import(account, mintAmount, now);
assert(mint(account, mintAmount));
amount -= mintAmount;
for (uint index = 0; amount > 0; index++) {
uint256 unlockTime = source.unlockTimes(account, index);
if ( unlockTime > now ) {
mintAmount = source.lockedBalances(account, index);
Import(account, mintAmount, unlockTime);
assert(mintUnlockTime(account, mintAmount, unlockTime));
amount -= mintAmount;
}
}
return true;
}
function predecessorDeactivated(address _predecessor) internal view onlyOwner returns (bool) {
return InsightsNetwork2Base(_predecessor).paused() && InsightsNetwork2Base(_predecessor).mintingFinished();
}
} | 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 ReadOnlyToken {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function allowance(address owner, address spender) public constant returns (uint256);
}
contract Token is ReadOnlyToken {
function transfer(address to, uint256 value) public returns (bool);
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);
}
contract ReadOnlyTokenImpl is ReadOnlyToken {
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) internal allowed;
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract TokenImpl is Token, ReadOnlyTokenImpl {
using SafeMath for uint256;
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);
emitTransfer(msg.sender, _to, _value);
return true;
}
function emitTransfer(address _from, address _to, uint256 _value) internal {
Transfer(_from, _to, _value);
}
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);
emitTransfer(_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 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 BurnableToken is Token {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public;
}
contract BurnableTokenImpl is TokenImpl, BurnableToken {
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 Ownable {
modifier onlyOwner() {
checkOwner();
_;
}
function checkOwner() internal;
}
contract MintableToken is Token {
event Mint(address indexed to, uint256 amount);
function mint(address _to, uint256 _amount) public returns (bool);
}
contract MintableTokenImpl is Ownable, TokenImpl, MintableToken {
function mint(address _to, uint256 _amount) onlyOwner public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emitMint(_to, _amount);
emitTransfer(address(0), _to, _amount);
return true;
}
function emitMint(address _to, uint256 _value) internal {
Mint(_to, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is Pausable, TokenImpl {
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 OwnableImpl is Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function OwnableImpl() public {
owner = msg.sender;
}
function checkOwner() internal {
require(msg.sender == owner);
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ZenomeToken is OwnableImpl, PausableToken, MintableTokenImpl, BurnableTokenImpl {
string public constant name = "Zenome";
string public constant symbol = "sZNA";
uint8 public constant decimals = 18;
function burn(uint256 _value) public whenNotPaused {
super.burn(_value);
}
} | 1 |
pragma solidity ^0.4.11;
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract MessageToken {
string public standard = 'Token 0.1';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address owner;
address EMSAddress;
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 MessageToken() {
balanceOf[this] = 10000000000000000000000000000000000000;
totalSupply = 10000000000000000000000000000000000000;
name = "Messages";
symbol = "\u2709";
decimals = 0;
owner = msg.sender;
}
function transfer(address _to, uint256 _value) {
if (_to != address(this)) throw;
if (balanceOf[msg.sender] < _value) throw;
if (balanceOf[_to] + _value < balanceOf[_to]) throw;
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function approve(address _spender, uint256 _value)
returns (bool success) {
if(msg.sender == owner){
EMSAddress = _spender;
allowance[this][_spender] = _value;
return true;
}
}
function register(address _address)
returns (bool success){
if(msg.sender == EMSAddress){
allowance[_address][EMSAddress] = totalSupply;
return true;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (_to == 0x0) throw;
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 getBalance(address _address) constant returns (uint256 balance){
return balanceOf[_address];
}
}
contract EMS{
address messageTokenContract = 0xb535394330357396680a5542767A190193F9D2Ab;
MessageToken m = MessageToken(messageTokenContract);
struct message{
address sender;
address recipient;
string message;
}
struct inbox{
string[] messages;
uint256 numMessages;
bool registered;
}
mapping (address => inbox) inboxes;
function sendMessage(address recipient, string message){
if(inboxes[msg.sender].registered != true){
m.register(msg.sender);
}
m.transferFrom(messageTokenContract, recipient, 1);
inboxes[recipient].messages.push(message);
inboxes[recipient].numMessages++;
}
function markAllRead(){
if(inboxes[msg.sender].registered != true){
m.register(msg.sender);
}
m.transferFrom(msg.sender, messageTokenContract, m.getBalance(msg.sender));
}
function markRead(uint numMessages){
if(inboxes[msg.sender].registered != true){
m.register(msg.sender);
}
m.transferFrom(msg.sender, messageTokenContract, numMessages);
}
function deleteAllMessages(){
markAllRead();
for(uint i = 0; i < inboxes[msg.sender].numMessages; i++){
inboxes[msg.sender].messages[i] = "";
}
}
function deleteMessage(uint messageNumber){
if(inboxes[msg.sender].registered != true){
m.register(msg.sender);
}
inboxes[msg.sender].messages[messageNumber] = "";
m.transferFrom(msg.sender, messageTokenContract, 1);
}
function getInbox(address _address, uint messageNumber) constant returns (string messages){
return inboxes[_address].messages[messageNumber];
}
} | 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;
}
}
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);
}
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool);
}
contract IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId)
public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator)
public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId)
public;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes data
)
public;
}
contract IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes data
)
public
returns(bytes4);
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) private _tokenOwner;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => uint256) private _ownedTokensCount;
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
constructor()
public
{
_registerInterface(_InterfaceId_ERC721);
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes _data
)
public
{
transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
mapping(address => uint256[]) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
constructor() public {
_registerInterface(_InterfaceId_ERC721Enumerable);
}
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
_ownedTokens[from].length--;
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string);
function symbol() external view returns (string);
function tokenURI(uint256 tokenId) external view returns (string);
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
string private _name;
string private _symbol;
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
constructor(string name, string symbol) public {
_name = name;
_symbol = symbol;
_registerInterface(InterfaceId_ERC721Metadata);
}
function name() external view returns (string) {
return _name;
}
function symbol() external view returns (string) {
return _symbol;
}
function tokenURI(uint256 tokenId) external view returns (string) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
function _setTokenURI(uint256 tokenId, string uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string name, string symbol) ERC721Metadata(name, symbol)
public
{
}
}
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 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 TokenRecover is Ownable {
function recoverERC20(
address tokenAddress,
uint256 tokenAmount
)
public
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
contract StructureInterface {
function getValue (uint256 _id) public view returns (uint256);
}
library StructuredLinkedList {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct List {
mapping (uint256 => mapping (bool => uint256)) list;
}
function listExists(
List storage self
)
internal
view
returns (bool)
{
if (self.list[HEAD][PREV] != HEAD || self.list[HEAD][NEXT] != HEAD) {
return true;
} else {
return false;
}
}
function nodeExists(
List storage self,
uint256 _node
)
internal
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(
List storage self
)
internal
view
returns (uint256)
{
bool exists;
uint256 i;
uint256 numElements;
(exists, i) = getAdjacent(self, HEAD, NEXT);
while (i != HEAD) {
(exists, i) = getAdjacent(self, i, NEXT);
numElements++;
}
return numElements;
}
function getNode(
List storage self,
uint256 _node
)
internal
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(
List storage self,
uint256 _node,
bool _direction
)
internal
view
returns (bool, uint256)
{
if (!nodeExists(self, _node)) {
return (false, 0);
} else {
return (true, self.list[_node][_direction]);
}
}
function getNextNode(
List storage self,
uint256 _node
)
internal
view
returns (bool, uint256)
{
return getAdjacent(self, _node, NEXT);
}
function getPreviousNode(
List storage self,
uint256 _node
)
internal
view
returns (bool, uint256)
{
return getAdjacent(self, _node, PREV);
}
function getSortedSpot(
List storage self,
address _structure,
uint256 _value
)
internal view returns (uint256)
{
if (sizeOf(self) == 0) {
return 0;
}
bool exists;
uint256 next;
(exists, next) = getAdjacent(self, HEAD, NEXT);
while (
(next != 0) && ((_value < StructureInterface(_structure).getValue(next)) != NEXT)
) {
next = self.list[next][NEXT];
}
return next;
}
function createLink(
List storage self,
uint256 _node,
uint256 _link,
bool _direction
)
internal
{
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
function insert(
List 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 insertAfter(
List storage self,
uint256 _node,
uint256 _new
)
internal
returns (bool)
{
return insert(
self,
_node,
_new,
NEXT
);
}
function insertBefore(
List storage self,
uint256 _node,
uint256 _new
)
internal
returns (bool)
{
return insert(
self,
_node,
_new,
PREV
);
}
function remove(
List 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(
List storage self,
uint256 _node,
bool _direction
)
internal
returns (bool)
{
return insert(
self,
HEAD,
_node,
_direction
);
}
function pop(
List storage self,
bool _direction
)
internal
returns (uint256)
{
bool exists;
uint256 adj;
(exists, adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
contract WallOfChainToken is ERC721Full, TokenRecover, MinterRole {
using StructuredLinkedList for StructuredLinkedList.List;
StructuredLinkedList.List list;
struct WallStructure {
uint256 value;
string firstName;
string lastName;
uint256 pattern;
uint256 icon;
}
bool public mintingFinished = false;
uint256 public progressiveId = 0;
mapping(uint256 => WallStructure) structureIndex;
modifier canGenerate() {
require(
!mintingFinished,
"Minting is finished"
);
_;
}
constructor(string _name, string _symbol) public
ERC721Full(_name, _symbol)
{}
function finishMinting() public onlyOwner canGenerate {
mintingFinished = true;
}
function newToken(
address _beneficiary,
uint256 _value,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
canGenerate
onlyMinter
returns (uint256)
{
uint256 tokenId = progressiveId.add(1);
_mint(_beneficiary, tokenId);
structureIndex[tokenId] = WallStructure(
_value,
_firstName,
_lastName,
_value == 0 ? 0 : _pattern,
_value == 0 ? 0 : _icon
);
progressiveId = tokenId;
uint256 position = list.getSortedSpot(StructureInterface(this), _value);
list.insertBefore(position, tokenId);
return tokenId;
}
function editToken (
uint256 _tokenId,
uint256 _value,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
onlyMinter
returns (uint256)
{
require(
_exists(_tokenId),
"Token must exists"
);
uint256 value = getValue(_tokenId);
if (_value > 0) {
value = value.add(_value);
list.remove(_tokenId);
uint256 position = list.getSortedSpot(StructureInterface(this), value);
list.insertBefore(position, _tokenId);
}
structureIndex[_tokenId] = WallStructure(
value,
_firstName,
_lastName,
value == 0 ? 0 : _pattern,
value == 0 ? 0 : _icon
);
return _tokenId;
}
function getWall (
uint256 _tokenId
)
public
view
returns (
address tokenOwner,
uint256 value,
string firstName,
string lastName,
uint256 pattern,
uint256 icon
)
{
require(
_exists(_tokenId),
"Token must exists"
);
WallStructure storage wall = structureIndex[_tokenId];
tokenOwner = ownerOf(_tokenId);
value = wall.value;
firstName = wall.firstName;
lastName = wall.lastName;
pattern = wall.pattern;
icon = wall.icon;
}
function getValue (uint256 _tokenId) public view returns (uint256) {
require(
_exists(_tokenId),
"Token must exists"
);
WallStructure storage wall = structureIndex[_tokenId];
return wall.value;
}
function getNextNode(uint256 _tokenId) public view returns (bool, uint256) {
return list.getNextNode(_tokenId);
}
function getPreviousNode(
uint256 _tokenId
)
public
view
returns (bool, uint256)
{
return list.getPreviousNode(_tokenId);
}
function burn(uint256 _tokenId) public {
address tokenOwner = isOwner() ? ownerOf(_tokenId) : msg.sender;
super._burn(tokenOwner, _tokenId);
list.remove(_tokenId);
delete structureIndex[_tokenId];
}
}
contract WallOfChainMarket is TokenRecover {
using SafeMath for uint256;
WallOfChainToken public token;
address public wallet;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
event TokenEdit(
address indexed beneficiary,
uint256 value,
uint256 tokenId
);
constructor(address _wallet, WallOfChainToken _token) public {
require(
_wallet != address(0),
"Wallet can't be the zero address"
);
require(
_token != address(0),
"Token can't be the zero address"
);
wallet = _wallet;
token = _token;
}
function buyToken(
address _beneficiary,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary);
weiRaised = weiRaised.add(weiAmount);
uint256 lastTokenId = _processPurchase(
_beneficiary,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
lastTokenId
);
_forwardFunds();
}
function editToken(
uint256 _tokenId,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
public
payable
{
address tokenOwner = token.ownerOf(_tokenId);
require(msg.sender == tokenOwner, "Sender must be token owner");
uint256 weiAmount = msg.value;
weiRaised = weiRaised.add(weiAmount);
uint256 currentTokenId = _processEdit(
_tokenId,
weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
emit TokenEdit(
tokenOwner,
weiAmount,
currentTokenId
);
_forwardFunds();
}
function changeWallet(address _newWallet) public onlyOwner {
require(
_newWallet != address(0),
"Wallet can't be the zero address"
);
wallet = _newWallet;
}
function _preValidatePurchase(
address _beneficiary
)
internal
pure
{
require(
_beneficiary != address(0),
"Beneficiary can't be the zero address"
);
}
function _processPurchase(
address _beneficiary,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.newToken(
_beneficiary,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
function _processEdit(
uint256 _tokenId,
uint256 _weiAmount,
string _firstName,
string _lastName,
uint256 _pattern,
uint256 _icon
)
internal
returns (uint256)
{
return token.editToken(
_tokenId,
_weiAmount,
_firstName,
_lastName,
_pattern,
_icon
);
}
function _forwardFunds() internal {
if (msg.value > 0) {
wallet.transfer(msg.value);
}
}
} | 0 |